Author Archives: Chris Owens

About Chris Owens

Web Developer based in Brisbane, Australia.

.NET Core 2.1 is Returning JSON with Lowercase Properties

Hi everyone,

Just testing out .Net Core 2.1 and noticed that all of my JSON properties are being returned in lowercase despite being defined as uppercase. It turns out that this is configurable:


// Change from this
services.AddMvc();

// To this
services
        .AddMvc()
        .AddJsonOptions(options => options.SerializerSettings.ContractResolver = new DefaultContractResolver());

Check out these links for more info:
https://stackoverflow.com/a/38202543/522859
https://github.com/aspnet/Announcements/issues/194

Parsing Hash Args for Cognito Auth – Javascript

Hi everyone,

A quick post on a function for parsing hash args when using AWS Congito.

Just in case the fiddle ever disappears:

const parseHashArgs = aURL => {

  aURL = aURL || window.location.href;

  var vars = {};
  var hashes = aURL.slice(aURL.indexOf('#') + 1).split('&');

  for (var i = 0; i < hashes.length; i++) {
    var hash = hashes[i].split('=');

    if (hash.length > 1) {
      vars[hash[0]] = hash[1];
    } else {
      vars[hash[0]] = null;
    }
  }

  return vars;
};

document.body.append(parseHashArgs("#id_token=testtokenval&token_type=bearer&expires_in=3600")["id_token"]);

Thanks to this link on Github: https://gist.github.com/miohtama/1570295/289d5a82e65663c9b515c88186a268c6dd1fddb7

AWS Installing AWS Inspector Agent on Windows EC2 Instance

Hi everyone,

Just a quick post on installing the AWS Inspector Agent on a Windows EC2 instance.

Open PowerShell and run the following command:

(new-object System.Net.WebClient).DownloadFile('https://inspector-agent.amazonaws.com/windows/installer/latest/AWSAgentInstall.exe','C:\Users\Administrator\Desktop\AWSAgentInstall.exe')

On your desktop, right click on AWSAgentInstall.exe and select run as administrator. Follow the prompts.

Go to run, and execute services.msc. You should now see the Amazon SSM Agent:

If you go to your amazon console > amazon inspector > assessment targets > Click on your relevant target > Preview Target:

Your agent status should now be healthy.

Thanks to these links for the info:
https://superuser.com/a/330754/124014
https://docs.aws.amazon.com/inspector/latest/userguide/inspector_installing-uninstalling-agents.html#install-windows

Dynamic Robots.txt with Web Api 2

Hi everyone,

For a project I’m currently working on I needed a dynamic robots.txt. Because our test environment is public facing we want to keep it from being indexed by Google etc. It took a bit of Googling to find a solution that worked, but in the end it was actually pretty simple.

Here’s the action in one of the API Controllers:

    public class UtilitiesController : CustomBaseApiController
    {
        [Route("Robots.txt")]
        [HttpGet]
        public HttpResponseMessage GetRobotsFile()
        {
            var resp = new HttpResponseMessage(HttpStatusCode.OK);
            var stringBuilder = new StringBuilder();
 
            if (Helpers.IsProduction())
            {
                // Allow bots in production
                stringBuilder.AppendLine("user-agent: *");
                stringBuilder.AppendLine("disallow: ");
            }
            else
            {
                // Don't allow bots in non-production environments
                stringBuilder.AppendLine("user-agent: *");
                stringBuilder.AppendLine("disallow: *");
            }
 
            resp.Content = new StringContent(stringBuilder.ToString());
 
            return resp;
        }
    }

Also need to add the following to your web.config so that the robots.txt file can processed by the routing handler. Without this IIS will attempt to serve it as a static file and will return a 404 when it’s not found:

<system.webServer>
    <modules>
    <!-- ... -->
        <handlers>
        <add name="RobotsTxt" path="robots.txt" verb="GET" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
        <!-- Other handlers -->
    </modules>
    <!-- ... -->
</system.webServer>

In production you’ll end up with the following:

user-agent: *
disallow:

And any other environments:

user-agent: *
disallow: *

Thanks to these answers on stackoverflow for the info:
https://stackoverflow.com/a/52270877/522859
https://stackoverflow.com/a/17037935/522859

AWS EC2 Elastic Beanstalk Going to Sleep – .Net/Windows/MSSQL Server Express

Hi everyone,

I’ve been having a bit of an issue with my AWS app going to sleep and taking a long time to handle initial requests.

I’m using .NET with Elastic Beanstalk on a T2 Micro Instance and MSSQL Server Express on RDS. My FrontEnd is a static ReactJS app that sits in S3 behind CloudFront. There’s also a load balancer across the backend.

My frontend was always instant but my initial Api calls were timing out. This ruled out S3 and CloudFront, leaving the following:

  • Load balancer
  • RDS/MSSQL
  • EC2/IIS

After a bit of Googling I came across something that looked fairly promising – MSSQL Server Express has a property called AutoClose set to ‘ON’ by default. AWS appears to correct this as mine was off however it’s worth checking:

-- If set to zero then auto close is off
SELECT DATABASEPROPERTY('mydatabasename','IsAutoShrink')
 
-- Check all instances at once
SELECT name,is_auto_close_on FROM sys.databases
 
-- Turn off if on
ALTER DATABASE myDB SET AUTO_CLOSE OFF

In my case the actual problem turned out to be IIS idle timeout. By default IIS automatically times out an application after 20 minutes. In order to disable this create the following ebextension:

commands:
    setIdleTimeoutToZero:
        cwd: "C:\\windows\\system32\\inetsrv"
        command: "appcmd set apppool /apppool.name:DefaultAppPool /.processModel.idleTimeout:0.00:00:00"

If you haven’t done this before, all you need to do is create a folder called .ebextensions under your project directory. Then create a new file called iis-idle-timeout.config and add the yaml to it. If you need more information on iis timing out check out this great blog post: https://notebookheavy.com/2017/06/21/set-iis-idle-timeout-elastic-beanstalk/

Thanks to these sources for the solutions:
Disable auto_close: https://stackoverflow.com/a/1750400/522859
IIS Timeout: https://notebookheavy.com/2017/06/21/set-iis-idle-timeout-elastic-beanstalk/
EBExtension Info: http://notebookheavy.com/2017/05/01/auto-install-newrelic-agent-elastic-beanstalk/

NavLink ListItems not Applying activeClassName class when Clicked On – ReactJS React-Router MaterialUI

Hi everyone,

A bit of a hairy issue I ran into today that took a while to track down. I’m using React Router with Material UI to render a Drawer as a sidebar:

The issue was that some links were not applying the expected activeclass:

<ListItem button component={NavLink} to="/about" onClick={this.handleItemClick} className={classes.sidebarContentListItem} activeClassName={classes.active}>
	<ListItemIcon className={classes.sidebarText}>
		<Info />
	</ListItemIcon>
	<ListItemText primary={
		<Typography type="body2" className={classes.sidebarText}>
			About
		</Typography>
	} />
</ListItem>

After trawling through react-router I eventually found a post on github that mentioned a similar issue: https://github.com/ReactTraining/react-router/issues/4638

The solution turned out to be wrapping all relevant components with withrouter.

Uncaught SyntaxError: Unexpected token < - ReactJS Build

Hi everyone,

A ReactJS issue I ran into after running npm run build:

Uncaught SyntaxError: Unexpected token <

This one took a while to track down but it essentially boils down to the built index.html file referencing paths relatively:

Issue: index.html was referencing
"<script ... src="./static/js/main.e7b5bb28.js"></script></body></html".
 
Instead of:
"<script ... src="/static/js/main.e7b5bb28.js"></script></body></html".

This meant that anytime a page was accessed directly it attempted to load the static files from the wrong directory. To fix it, I had to update the homepage node in package.json

Original:
...
"version": "0.1.0",
  "homepage": "./",
  "private": true,
...
 
Instead use:
"version": "0.1.0",
  "homepage": "/",
  "private": true,

Hopefully that’s able to help someone else out, took a while to track down!

npm ERR! missing script: flow npm ERR! A complete log of this run can be found in: – ReactJS and Flow

Hi everyone,

I ran into the following error while trying to setup flow:

npm ERR! missing script: flow
npm ERR! A complete log of this run can be found in:

To fix this, just add “flow”: “flow” as a new entry under “scripts” in your package.json file.

See the following link for more info:
https://github.com/facebook/create-react-app/blob/master/packages/react-scripts/template/README.md#adding-flow

Error Adding Card – Assembly Payments

Hi everyone,

Just working with Assembly Payments and ran into the following error while following their documentation on Capturing a Credit Card:

errors”:{“card_account”:[“Error adding card. If error persists, please contact our support team.”]

The error is pretty vague, but it does seem that the credit card info they use in the documentation has expired. I tested with another credit card and it went through:

                    promisepay.createCardAccount(token, {
 
                        full_name: "Bella Buyer",
                        number: "4242424242424242",
                        expiry_month: "12",
                        expiry_year: "2021",
                        cvv: "123"
                    }, success, fail)

Update
I was talking to support about another issue and they mentioned the following page: https://reference.assemblypayments.com/#credit-card-data

Tab Key not Working as Expected – Visual Code

Hi everyone,

I ran into a bit of a strange issue with visual code today. Tabs suddenly stopped working for creating an indent. Instead, the focus of the cursor changed.

It turns out that I’d inadvertently toggled a setting that causes the tab key to move focus instead of indenting. The hotkey in windows is ctrl + m.

Thanks to this link for the find: https://github.com/Microsoft/vscode/issues/21638