Categories
Software Development Web Development

How to get URL Routes in your Javascript in Symfony 5+

This is something I needed to know how to do so I could generate URLs inside my javascript more easily.

Currently the docs on this are outdated so I will record what I did here so I can know later, or for others who need this info.

The docs say something about app/appKernel.php that file no longer exists.  It has been replaced with just kernel.php and you do pretty much nothing to that file.

I am not sure what version Symfony started this but I know in 5+ you don’t have to register the bundle like step 2 of the old docs shows. This is done automatically for you in a new file named config/bundles.php which is where all bundles are automatically registered when you install them.

So all you do is this command now in the terminal

composer require friendsofsymfony/jsrouting-bundle

inside your apps root level. It is auto registered for you.

You don’t have to do step 3 of the old docs either as the config system has changed. There is no

app/config/routing.yml

file anymore. When you install the bundle the new system creates a new file named app/config/routes/fos_js_routing.yaml for you
For step 4 the required code has changed you need to enter this now.

$ php bin/console assets:install --symlink public

Basically to install the bundle you just use the composer command and most of the stuff is now done for you.

A silent secret.

In order for the routes to work you must add something new to every single route definition you want to be able to generate a route in your javascript for.

You must add this to the annotation or where ever you define your routes. I use annotations so I can just look to the controllers, plus when I split the system into microservices the routes go with their services.

options={"expose"=true}

So for my menu route the definition in the controller looks like this.

@Route("/menu", name="menu", options={"expose"=true}, methods={"GET"})
</code.

Now how to use it?

So now that it is installed how do you use it? One more step. Now you must include the needed Javascript in your page with these tags.

<script src="{{ asset('bundles/fosjsrouting/js/router.js') }}"></script>
<script src="{{ path('fos_js_routing_js', { callback: 'fos.Router.setData' }) }}"></script>

Place those anywhere you want. What I did is put them in my base twig template in a section where I include my Javascript this way it is available on every page because I will probably be needing access to routes as I build the app.

Once you have all of the above done you can use it like this

let testUrl = Routing.generate( 'menu');
console.log(testUrl); //outputs /menu

Route not found errors?

Yes I got these too. You must add expose

options={"expose"=true}

to every single route you want to use. And your IDE probably won’t be very helpful so double check the spellings. Routing probably won’t be found by your IDE.

Here is a link to my favorite HTMLEntities converter if you write articles about programming you will need this.

 

Categories
Software Development Web Development

How to create and use a custom Javascript Event

You have probably used events in Javascript many times.  Especially if you have done any User Interface programming. There are many types of events provided by browsers and the Javascript engines.

Did you know you can create your own custom events with the CustomEvent() constructor? Here is a minimal example. In this article I will explain custom events and how to use them.

First off what would you use a custom event for? You use them to notify other objects in your app that actions have occurred such as “user clicked x” or “user closed dialog”. Using events prevents code coupling and reduces dependencies.

I came across this need when creating a dialog box where I wanted an overlay to show beneath it blocking out the page behind. I didn’t want my DialogBox to have to know about my Overlay.  I didn’t want them coupled. I didn’t want my DialogBox to have to have an Overlay object as an argument creating a dependency. I didn’t want my DialogBox to even know that an Overlay object existed.

The answer is for my DialogBox to emit/create/dispatch a custom Javascript Event and have a listener for that event to close the Overlay.

So lets look at some code.


import {Utils} from "./Utils";

class DialogBox {

    /**
     *
     * @param {string} dialogId
     * @param {string} dialogClass
     */
    constructor(dialogId = 'dialogId', dialogClass = '') {
        this.closeDialogId = 'closeDialog';
        this.dialogBoxBottomRowId = 'dialogBoxBottomRow';
        this.dialogBoxClass = 'dialogBox ' + dialogClass;
        this.contentContainerId = 'dialogContentContainer';
        this.dialogHtml = '';
        this.dialogBoxId = dialogId;
        this.closeHandler = null;
        this.divElement = null;
    }

    /**
     *
     * @param {string} rowContent : the content HTML etc to be added as a row
     * @param {string} cssClass : applied only if passed in
     * @returns {void}
     */
    bottomRow(rowContent = '', cssClass = 'dialog-bottom-row') {

        let bottomRow = document.getElementById(this.dialogBoxBottomRowId);

        //if the bottom row does not exist add it to the html
        if ( Utils.isEmpty(bottomRow)) {
            let rowHtml = '<div id="' + this.dialogBoxBottomRowId + '" ';
            rowHtml += ' class="' + cssClass + '" ';
            rowHtml += ' >' + rowContent + '</div>';
            this.dialogHtml += rowHtml;
        } else {
            //if a bottom row exists replace it
            bottomRow.className = cssClass;
            bottomRow.innerText = rowContent;
        }
    }
    /**
     * Centers the dialog vertically and horizontally in the parent element
     * @param {string} parentElementId
     */
    centerDialog(parentElementId = 'body') {

        let parentWidth = 0;
        let parentHeight = 0;
        //need the dialog boxes calculated width and height
        let dialogHeight = this.divElement.clientHeight;
        let dialogWidth = this.divElement.clientWidth;

        //must use two different ways to get the height and width
        if (parentElementId === 'body') {
            parentWidth = window.innerWidth;
            parentHeight = window.innerHeight;
        } else {
            let parentElement = document.getElementById(parentElementId);
            //make sure null or undefined were not returned
            if (!Utils.isEmpty(parentElement)) {
                parentHeight = parentElement.clientHeight;
                parentWidth = parentElement.clientWidth;
            }
        }
        let left = (parentWidth / 2) - (dialogWidth / 2);
        let top = (parentHeight / 2) - (dialogHeight / 2);
        //must add px or it doesn't work at all
        this.divElement.style.top = top + 'px';
        this.divElement.style.left = left + 'px';
    }
    /**
     *
     * @param {string} content
     * @param {string} containerClass
     */
    contentContainer(content, containerClass = 'dialog-content') {
        let contentDiv = document.getElementById(this.contentContainerId);

        //if the container exists replace it contents
        if (Utils.isEmpty(contentDiv)) {
            let contentHtml = '<div id="' + this.contentContainerId + '"';
            contentHtml += ' class="' + containerClass + '" >';
            contentHtml += content + '</div>';
            this.dialogHtml += contentHtml;
        } else {
            contentDiv.innerHTML = content;
            contentDiv.className = containerClass;
        }
    }
    /**
     * calls removeDialogBox which removes the dialog and event listeners
     */
    hideDialogBox() {
        this.removeDialogBox();
    }

    /**
     *
     * @param {string} menuText
     * @param {string} menuTextClass
     */
    menuBar(menuText, menuTextClass = '') {
        let menuTextId = 'dialog-menu-text';
        /*
         * if dialogMenuBar is present then the length will be non zero or true
         * if this is the case replace the content, this allows this method to be called
         * again later to change the value
         */
        let menuBarID = 'dialog-menu-bar';
        let menuTextDiv = document.getElementById(menuTextId);

        if (Utils.isEmpty(menuTextDiv)) {
            this.dialogHtml = '<div class="dialog-menu-bar" id="dialog-menu-bar" >';
            this.dialogHtml += '<div id="' + menuTextId + '" class="dialog-menu-text ';
            this.dialogHtml += menuTextClass + '" >' + menuText + '</div>';
            this.dialogHtml += '<div id="' + this.closeDialogId + '" class="close-dialog" >';
            this.dialogHtml += '<img src="/images/drawing/close-window.png" ';
            this.dialogHtml += 'alt="Close dialog" >';
            this.dialogHtml += '</div></div>';
        } else {
            menuTextDiv.innerText = menuText;
            menuTextDiv.className = menuTextClass;
        }
    }

    /**
     * displays the dialog box, you must call centerDialog to center it
     */
    showDialogBox() {
        //remove any existing dialog boxes first
        this.removeDialogBox();
        this.divElement = document.createElement("div");
        this.divElement.id = this.dialogBoxId;
        this.divElement.className = this.dialogBoxClass;
        this.divElement.innerHTML = this.dialogHtml;
        //position the dialog box now give it the highest z-index to be on top
        this.divElement.style.zIndex = Utils.getHighestZIndex() + 1;
        document.body.appendChild(this.divElement);
        //add the listener for when the user clicks to close

        this.closeHandler = function ( ) {
        this.removeDialogBox();
        }.bind(this);

        let close = document.getElementById(this.closeDialogId);
        close.addEventListener('click', this.closeHandler, false);
    }

    /**
     * removes the dialog html from the page and removes the close listener
     * dispatches event 'dialogClosed' to be used to close an overlay etc.
     */
    removeDialogBox() {
        let dialogElem = document.getElementById(this.dialogBoxId);
        //if a dialog box of the same id exists delete it first to prevent errors and issues
        if (dialogElem) {
            let close = document.getElementById(this.closeDialogId);
            close.removeEventListener('click', this.closeHandler, false);
            dialogElem.remove();
            const dialogEvent = new CustomEvent('dialogClosed');
            document.body.dispatchEvent(dialogEvent);
        }
    }
}

export {DialogBox}

That is a lot of code 169 lines to be exact. I am still in the process of converting this code, still going to add some Template literals instead of the old fashioned string concatenation technique.

There are several very import things to note here in this code. For example the way the addEventListener() and removeEventListener are used. These functions have to be passed THE EXACT SAME parameters or removeEventListener() fails to remove the event listener and that clutters your memory up because you will have listeners referring to elements that don’t exist.

That is why I have this code this.closeHandler


//add the listener for when the user clicks to close

        this.closeHandler = function ( ) {
        this.removeDialogBox();
        }.bind(this);

        let close = document.getElementById(this.closeDialogId);
        close.addEventListener('click', this.closeHandler, false);

See this.closeHandler = function  that stores the function to handle the click on the close button. Both the add and remove event listener functions have to be passed the exact same function.

Look at the removeDialogBox function closer.


let dialogElem = document.getElementById(this.dialogBoxId);
        //if a dialog box of the same id exists delete it first to prevent errors and issues
        if (dialogElem) {
            let close = document.getElementById(this.closeDialogId);
            close.removeEventListener('click', this.closeHandler, false);
            dialogElem.remove();
            const dialogEvent = new CustomEvent('dialogClosed');
            document.body.dispatchEvent(dialogEvent);
        }

Notice that the second argument to removeEventListener is this.closeHandler that is the same function passed to the addEventListener above.

If you use anonymous functions inside add and remove event listeners instead, then they wont be the same function and so your event listener won’t be removed and your memory fills up faster.

Another important note is that the this.handler function must use bind(this) like so

this.closeHandler = function ( ) { this.removeDialogBox(); }.bind(this);

If you don’t bind the function expression then you will get an error about this.removeDialogBox is not a function.
This is because you are storing the closeHandler in memory for later use.  At that later time the context will be different, the code won’t be executing within your class anymore, it will be in it’s own context. That means “this” that was alive in your class, no longer exists. Which means that function no longer exists You must bind “this” by using “.bind(this) at the end of the function.

And now about the Custom Event. You will see it at the bottom of the removeDialogbox() function

const dialogEvent = new CustomEvent('dialogClosed');
document.body.dispatchEvent(dialogEvent);

Those two lines is all it takes to create and dispatch your own Custom event. This means you write code that listens for the custom “dialogClosed” event to be fired like this.

document.body.addEventListener('dialogClosed', function (){
overlay.hideOverlay();
});

Notice I am using document.body this is a very easy way to create the listener. This is using an anonymous function which is bad because this listener can’t be removed. It should be removed right below this. In order to do that you would need to create the handler function above it and pass it to both the add and remove event listeners.

Adding information to the event.
This is one of the most handy parts of custom events, the ability to pass information in the event. This can be any information, a full object even.
In this article it mentions adding custom data with “detail”.  Here is an example from the code above.

const dialogEvent = new CustomEvent('dialogClosed',{ detail: {
        id: this.dialogBoxId
    } });

Here I am passing id you can use this same format to pass many more values just add a comma to the end of each one. Then to access the extra information in your listener you do like this.

document.body.addEventListener( 'dialogClosed', function (event) {

let dialogId = event.detail.id
switch (dialogId) {
case mainDialogId :
mainOverlay.hideOverlay();
break;
case colorDialogId :
overlay2.hideOverlay();
break;
}

}, false);

Above I am using event.detail.id to get the value I stored in id in the detail of the custom event. Notice how I am using a switch statement to compare the id’s of the dialog that closed to close the correct overlay. There is no default behavior for this action, either one dialog closes or another. I could have 5 different dialogs if I wanted.

Categories
Software Development Web Development Web Security

Authentication vs Authorization what is the difference?

Authentication/Authorization these terms are often confused. Here I will clarify them.

Authentication — Login, proving who a user is one way or another. After a user is logged into a system a session cookie is usually created to re-authenticate the user so they don’t have to login every single page view.

Authorization — Can a user view or access something once Authenticated? Authorization includes things like administration panel access, viewing a users profile or post or media etc.

Categories
Resources Software Development

Ethereum Solidity programming links and resources.

Links and resources about Ethereum Solidity programming language.

Videos

Categories
Software Development Web Development

How to remove unused or broken docker container images.

Sometimes we make mistakes. When first learning docker we probably make many mistakes and end up with tons of unused docker images.

If you are on Linux like me, you won’t have a desktop dashboard like Mac and Windows get, so things are harder. To see a list of what images you have created you use the following command

docker ps -a

That command will output something like this.
It will show the CONTAINER ID, IMAGE, COMMAND etc. as you can see. To delete an image you use the container id with docker rm like this.

docker rm b5f8fae52bce

I’ve seen older internet posts using the IMAGE value but I had no success with that method. I am guessing something changed. I didn’t even see an example of this I just tried it. I don’t see any mention of this in the docs either. But it works. This part in the getting started intro actually explains it. I think something did change.

Docker container rm documentation.

Docker rm documentation.

Categories
Resources Software Development Web Development

HTTP headers and caching resources.

Resources all about HTTP headers and caching.

Caching tutorial -> great article to start with, explains all the basics of caching.

Hypertext Transfer Protocol (HTTP/1.1): Caching  rfc spec

Categories
Software Development Web Development Web Security

How to create ssh keys for admin user login without passwords

The idea is to have a way for an admins to SSH into a server without having to use passwords. This adds a level of security to your server setup. Without private keys you have to enter your user name and password. This can be less secure than generating SSH keys and adding your public key to SSH, plus with keys you don’t have to remember passwords.

First you need to generate the SSH keys. I prefer the ed25519 algorithm which is a newer one. You can get more info here.  

The code to create an ed25519 ssh key in the current users .ssh directory will look like this.


ssh-keygen -f ~/.ssh/key-name -t ed25519  

The -f flag tells ssh-keygen the name of the files you want to create. The above command would create key-name(private key) and key-name.pub(public) key, in the current users .ssh directory. The ~ is a Linux shortcut meaning /home/current_user/ so you don’t have to type all that.

The -t flag tells ssh-keygen what type of algorithm to use. If you don’t specify the -f flag and give the file a name, then both files are output in the current users .ssh directory as ed25519 and ed25519.pub

Categories
Software Development

Why doesn’t bash script recognize aliases

Here I won’t be doing much explaining, just listing links so people can read about this befuddling issue.

It often boggles my mind how differently you must write shell scripts vs the command line commands. It is often very inconsistent, I hate inconsistencies.

Basically Aliases within Linux shell are not recognized without some fancy hacky code, WOOHOO. So you will lose your mind if you are trying to set and use aliases in shell scripts.

You can set aliases all day long, but your scripts wont use them.

Yes you read that correctly. You can set aliases in your script, even right before you want to use it and Linux is like GTFO, I have no idea what that is. It even fails without a notice/error most times. What you can do is set a normal variable and use it in place of an alias though.

Say you had a script named do-this-thing.sh  and it was located deep in a directory like /etc/directory/directory/directory/directory/do-echo “$yarnBin” > /etc/profile.d/server-alias.shthis-thing.sh
You could do the following in BASH


not_alias=/etc/directory/directory/directory/directory/do-this-thing.shalias not working inside bash shell script

bash not_alias

The above would execute the do-this-thing.sh file. You can also permanently set aliases in your Shell script. This is handy even if you can’t use the aliases in your script directly, you can use them in the terminal command line later.

To permanently set aliases alias when not working inside bash shell script place them in your .bashrc file for the user you are logged in   This is usually located in /home/username/.bashrc  or you can put it in the user profile .profile file or other places.
How you do this varies by Linux shell.

Links to more info

Why doesn’t my Bash script recognize aliases?

Alias not working inside bash shell script

Creating permanent executable aliases

How to create permanent Linux Aliases

How to create a permanent Bash alias on Linux/Unix 

Categories
Resources Software Development Web Security

Stupid linux issues.

This is my collection of stupid.

Top of the list Debian/Ubuntu removes apt-key support and doesn’t tell anyone they did it, doesn’t give anyone a single hint as to what to do. No just remove/deprecate shit and don’t tell a single soul on earth. This kind of stupid makes me want to leave the industry entirely. I get so tired of messed up  and undocumented shit that wastes hours and hours and hours of my time. Someone needs kicked for this.

More info and links about the above issue or removing apt-key support. Yarn suggests using apt-key so this means hundreds of millions of people are having this issue or will or could.
Even more info about the stupid ideas from above.

Categories
Software Development Web Development

Where does symfony php framework hide the errors?

I kept saying this over and over and looking everywhere for answers. I finally found this page through googling tons of terms and combos until I found it. I kept thinking my errors would be in the logs I set in my Nginx configs, or even in my PHP configs. But they were continually empty, I was going insane. I seriously blew up on twitter.

BLOWING UP

I thought Symfony was simply suppressing or not passing the errors to Nginx. So the logs are located at the place in the link above from documentation and not in the location you set in the Nginx configs or PHP configs.

By default, log entries are written to the var/log/dev.log file when you’re in the dev environment. In the prod environment, logs are written to var/log/prod.log

What made this confusing was, the docs don’t have a logical link flow when you are reading them trying to learn Symfony. You later find the SymfonyCasts which are better. But what makes it  most confusing is in the docs about configuring Nginx, it even shows the following.

    error_log /var/log/nginx/project_error.log;
    access_log /var/log/nginx/project_access.log;

To me this was showing how to set the error log. This does nothing by the way, not unless nginx itself has an error I guess.

For months I’ve wondered WTF, where are my error logs. I kept putting my app in dev mode so I could debug it via the browser.

Don’t do that!!!!!

To be honest getting Symfony working with Nginx is a pain in the ballsocks. The reason is, Nginx doesn’t pass environmental variables through to php scripts like Apache does/can. If you want that kind of fancy feature you must hack nginx up and use some perl script or something similar. Otherwise with Nginx you must set the environment variables twice, once in nginx and once in shell.

Why would you do that?

Why two locations? Yeah this really angered me and blew my mind at first too. As mentioned above Nginx doesn’t have any easy way to pass the environment variables you set at the Linux server level. This is important with Symfony because you often need to run things like Doctrine on the command line.

So I was setting my Nginx Environmental variables, the app would see them just fine. I’d go to run doctrine or tests and BOOM missing environmental variables like WTF? Or I would set them in the Linux environment, view them with printenv load the app in the browser and Nginx didn’t pass the values to my script. It took a lot of googling to figure that out with lots of trial and failure. To make matters worse, you have to change the environmental variable names in order to run tests so that symfony loads them, otherwise it hides the values.

WTF is happening?

I then found out through experimenting that you had to set the variables for the command line in the Linux environment too. How to permanently set Linux environmental variablees covers how to do that. It’s easier to just Bash script or ansible the entire process with Hashicorp packer than to try to manually maintain it all, setting vars in two different places etc.

So for months I’ve been going insane trying to find my error logs. Today I found the error logs.

Problem solved