Tag Archives: guide

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

Including an Externally Hosted Script in ReactJs

Hi everyone,

Just a quick example of how to include an externally hosted js file in a reactjs app. In index.html add your script tag as you would in a normal app:

  <head>
    <script src="https://js.prelive.promisepay.com/PromisePay.js " type="text/javascript"></script>
  </head>

Then in the file you plan to use the library you can add a const and reference it normally:

const promisepay = window.promisepay;

Thanks to this link for the info: https://stackoverflow.com/a/44877953/522859

Allow Number and String for PropTypes – ReactJS

Hi everyone,

A quick post on how to allow a string or number when defining PropTypes:

static propTypes = {
        numberField: PropTypes.number.isRequired,
        stringField: PropTypes.number.isRequired,
        mixedField: PropTypes.oneOfType([PropTypes.string, PropTypes.number]).isRequired
    }

Thanks to this stackoverflow post for the info: https://stackoverflow.com/a/41808543/522859

Overriding Button Styles and Hover Effects – Material UI

Hi everyone,

Just a quick post on how to override the background color and hover effects for buttons in material ui:

Define your class as follows:

 
const styles = theme => ({
    ...
    greenButton: {
        backgroundColor: green[500],
        color: '#FFF',
        '&:hover': {
            backgroundColor: green[400],
            color: '#FFF'
        }
    }

Then just reference it as you normally would:

 
const styles = theme => ({
 
const { classes } = this.props;
 
<Button size="small" className={classes.greenButton} variant="raised">
      <AddShoppingCartIcon />
</Button>

Avoiding Wrapper Divs in ReactJs

Hi everyone,

Just a quick post on how you can avoid wrapper divs in ReactJs. It’s particularly useful when populating tables or creating parts of a larger component. Instead of the following:

return (
  <div>
    <td>Frogs</td>
    <td>Turtles</td>
  </div>
);

You can use fragments:

import React, { Fragment } from 'react'
...
return (
  <Fragment>
    <td>Frogs</td>
    <td>Turtles</td>
  </Fragment>
);

The fragment won’t polute the dom and mean that you don’t need to add any additional styling. Check out these links for more info:
https://reactjs.org/docs/fragments.html
https://stackoverflow.com/a/49375945/522859
https://reactjs.org/blog/2017/11/28/react-v16.2.0-fragment-support.html

Adding a Link to a Drawer – Material UI and ReactJS

Hi everyone,

I ran into a bit of an issue turning a menuitem into a link with Material UI and React-Router. The main problems being that underlines appeared and threw the spacing out.

To summarize, use the component attribute on the ListItem:

<List>
   <ListItem button component={Link} to="https://www.whatibroke.com">
        <ListItemText primary="WhatIBroke" />
   </ListItem>
</List>

The official docs cover it here: https://material-ui.com/api/list-item/

See the following stackoverflow post for more info: https://stackoverflow.com/a/50558139/522859

Full Page Layout Example for Material UI – ReactJS

Hi everyone,

I’ve spent the last couple of days looking into MaterialUI. It seems really good however there are very few examples of a layout wireframe. After digging through Github I came across the following CodeSandbox:

There are a number of other themes and templates available (such as the amazing Material Dashboard) but they are all very in depth and not really suitable for a quick prototype or mock.

Thanks to Luke Peavey for posting the answer on StackOverflow. It definitely deserves a lot more views: https://stackoverflow.com/a/50312721/522859

Hopefully, this will be able to save someone else a bit of time!

Cheers,
Chris

Pass a Component as a Child Prop and Render it – ReactJs

Hi everyone,

A quick post on how to pass a component as a prop and then render it as a child.

const ChildComponent = () => <div>Child Component</div>;
 
const MainComponent = (props) => <div><div>Main component. Child appears below</div>{props.content}</div>;
 
class App extends React.Component {
 
  render () {                                        
    return (
      <div>          
          <MainComponent content={<ChildComponent />} />          
      </div>
    );
  }
}

An alternative to all of this that I wasn’t aware of is to to use “children”:

See the Pen ozqNOV by Dan Abramov (@gaearon) on CodePen.

Thanks to the following stackoverflow post for the info: https://stackoverflow.com/a/41499555/522859