Docker build with multiple --build-arg arguments

If you are passing multiple arguments then add --build-arg with each argument like below

docker build \
-t imagename \
--build-arg env=prod \
--build-arg port=3000 \
--no-cache .


17 Views Posted on September 22, 2022

How to remove the tracked file that was added in .gitignore

To stop tracking a file you need to remove it from the index.
Using the below command you can remove the file from the index

git rm --cached fileName

If you want to remove the entire folder using the below command

git rm -r --cached folderName


48 Views Posted on March 31, 2022

How to exclude Typescript build .js, .js.map files from the project on VS Code

You can exclude the Typescript build .js .js.map from VS Code using the below steps.
Add the below code to .vscode folder settings.json file, this will exclude .js and.js when the typescript file present for the corresponding .js and .js.map file

{
    "files.exclude": {
        "**/*.js": {
            "when": "$(basename).ts"
        },
        "**/*.js.map": {
            "when": "$(basename)"
        }
    }
}


27 Views Posted on March 24, 2022

How to clear RAM Memory Cache, Buffer and Swap Space on Linux

Clear page cache only

# sync; echo 1 > /proc/sys/vm/drop_caches

Clear dentries and inodes

# sync; echo 2 > /proc/sys/vm/drop_caches

Clear page cache, dentries, and inodes

# sync; echo 3 > /proc/sys/vm/drop_caches 

Now we will be creating a shell script to auto clear RAM cache daily at 3 am via a cron scheduler task.
Create a shell script clearcache.sh and add the following lines.

#!/bin/bash
# Note, we are using "echo 3", but it is not recommended in production instead use "echo 1"
echo "echo 3 > /proc/sys/vm/drop_caches"

Change the permission on the clearcache.sh using the below command

chmod 755 clearcache.sh

Next, open crontab for editing

crontab -e

Add the below line, save and exit to run it at 3 am daily.

0  3  *  *  *  /path/to/clearcache.sh

List the crontab and verify using the below command

crontab -l


11 Views Posted on March 24, 2022

Angular how to change environment variable values after build

Sample environment variables for development & production environment.ts

export const environment = {
    env: 'Dev'
};

environment.prod.ts

export const environment = {
    env: 'Prod'
};

In the above code using the window object like below:
environment.ts

export const environment = {
    env: window['env'] || 'Dev'
};

environment.prod.ts

export const environment = {
    env: window['env'] || 'Prod'
};

Create a .js file in the root directory and add it to index.html file as a script

<script src="./config.js"></script>

In the config.js file, you can update the environment values without rebuilding your application like below:

window['env'] = 'Uat';


50 Views Posted on March 24, 2022

Azure Web App deploy error "Web Deploy cannot modify the file on the destination because it is locked by an external process"

As per the Microsoft Github issues link, you need to add the below key in your portal App Settings.

It can help resolve the locked file deployment error.

MSDEPLOY_RENAME_LOCKED_FILES = 1


13 Views Posted on March 20, 2022

How to fix Android build error "Installed Build Tools revision XX.X.X is corrupted"

The main problem is the two files missing in SDK build tool 31 that are:

  1. dx.bat
  2. dx.jar

The solution is that these files are named d8 in the file location so changing their name to dx will solve the error.

For Windows

  • Go to bellow location
"C:\Users\user\AppData\Local\Android\Sdk\build-tools\xx.x.x"
  • Find a file named d8.bat. This is a Windows batch file.
  • Rename d8.bat to dx.bat.
  • In the folder lib ("C:\Users\user\AppData\Local\Android\Sdk\build-tools\xx.x.x\lib")
  • Rename d8.jar to dx.jar

Remember AppData is a hidden folder. Turn on hidden items to see the AppData folder.

For macOS or Linux

# change below to your Android SDK path
cd ~/Library/Android/sdk/build-tools/31.0.0 \
  && mv d8 dx \
  && cd lib  \
  && mv d8.jar dx.jar

Hope the build issue is resolved.


17 Views Posted on March 20, 2022

How to change linux mint PC Host Name

Open a terminal and enter sudo -s to enable the root privileges.

user@user-pc:~$ sudo -s

Next, edit the hostname using the below command

root@user-pc:~$ nano /etc/hostname

It will show the existing hostname (PC name). Now you can edit it and save using ctrl + x command.

Once restart your PC your hostname (PC name) will update automatically.


7 Views Posted on March 20, 2022

How to build and deploy a container to an Azure Web App using GitHub CI/CD

  • Create a container application from the Azure portal and download the publish profile for your Azure Web App. You can download this file from the Overview page of your Web App in the Azure Portal.
  • Create a secret in your repository named AZURE_WEBAPP_PUBLISH_PROFILE, paste the publish profile contents as the value of the secret.
  • Create a GitHub Personal access token with "repo" and "read:packages" permissions.
  • Create three app settings on your Azure Web app:
DOCKER_REGISTRY_SERVER_URL: Set this to "https://ghcr.io"
DOCKER_REGISTRY_SERVER_USERNAME: Set this to the GitHub username or organization that owns the repository
DOCKER_REGISTRY_SERVER_PASSWORD: Set this to the value of your PAT token from the previous step
  • Change the value for the AZURE_WEBAPP_NAME. Create a new workflow in GitHub Actions and add the below code as filename.yml
name: Build and deploy a container to an Azure Web App

env:
  AZURE_WEBAPP_NAME: samprixapp  # set this to the name of your Azure Web App

on:
  push:
    branches:
      - master
  workflow_dispatch:

jobs:
  build:
    runs-on: ubuntu-latest

    steps:
      - uses: actions/checkout@v2

      - name: Set up Docker Buildx
        uses: docker/setup-buildx-action@v1

      - name: Log in to GitHub container registry
        uses: docker/login-action@v1.10.0
        with:
          registry: ghcr.io
          username: ${{ github.actor }}
          password: ${{ github.token }}

      - name: Lowercase the repo name and username
        run: echo "REPO=${GITHUB_REPOSITORY,,}" >>${GITHUB_ENV}

      - name: Build and push container image to registry
        uses: docker/build-push-action@v2
        with:
          push: true
          tags: ghcr.io/${{ env.REPO }}:${{ github.sha }}
          file: ./Dockerfile

  deploy:
    runs-on: ubuntu-latest
    needs: build
    environment:
      name: 'Development'
      url: ${{ steps.deploy-to-webapp.outputs.webapp-url }}

    steps:
      - name: Lowercase the repo name and username
        run: echo "REPO=${GITHUB_REPOSITORY,,}" >>${GITHUB_ENV}

      - name: Deploy to Azure Web App
        id: deploy-to-webapp
        uses: azure/webapps-deploy@v2
        with:
          app-name: ${{ env.AZURE_WEBAPP_NAME }}
          publish-profile: ${{ secrets.AZURE_WEBAPP_PUBLISH_PROFILE }}
          images: 'ghcr.io/${{ env.REPO }}:${{ github.sha }}'

As per the above workflow, the code pushed in the master branch will automatically deploy to your Azure application. You can view the logs on the GitHub actions tab as well as Azure app logs.


20 Views Posted on March 19, 2022

Next.js create a custom server with HTTP proxy to external server

First, create a server file named server.js and paste the below code to that file.

const next = require('next');
const dev = process.env.NODE_ENV !== 'production'
const hostname = 'localhost';
const port = 3000;
// when using middleware `hostname` and `port` must be provided below
const app = next({ dev, hostname, port });
const handle = app.getRequestHandler();
var express = require('express');
const { createProxyMiddleware } = require('http-proxy-middleware');

app.prepare().then(() => {
    const server = express();
    server.use('/api', createProxyMiddleware({ target: 'https://samprix.com', changeOrigin: true, }));    

    server.all('*', (req, res) => handle(req, res));

    server.listen(port, err => {
        if (err) throw err;
        console.log(`> Ready on http://localhost:${port}`);
    });
})

Then build the Next.js using the below command

NODE_ENV=production next build

After the build run the server js file using the below command

NODE_ENV=production node -r esm node server.js

For more information about the Next.js custom server refer to this doc.


89 Views Posted on March 04, 2022

How to redirect 301 in Angular Universal

To remove the old data from the search engine you need to add 301 redirects to your old pages.
The below method is used to redirect your old page to a new page using 301 redirects in Angular Universal. This is by default code in server.ts file

// All regular routes use the Universal engine
  server.get('*', (req, res) => {
      res.render(indexHtml, { req, providers: [{ provide: APP_BASE_HREF, useValue: req.baseUrl }] });
  });

All routes come here then the express server(SSR) renders the front-end angular HTML files. So before sending any response to the browser we can send the 301 status code.
You can add some conditions like below

// All regular routes use the Universal engine
  server.get('*', (req, res) => {
    if (index == req.originalUrl)
      res.redirect(301, 'https://www.samprix.com');
    else
      res.render(indexHtml, { req, providers: [{ provide: APP_BASE_HREF, useValue: req.baseUrl }] });
  });


175 Views Posted on February 27, 2022

Import JSON array from local file to Typescript array

The sample JSON file content (data.json):

[
  {
    "FirstName": "Joe",
    "UserId": 1
  },
  {
    "FirstName": "Jack",
    "UserId": 2
  }
]

Next, add appropriate resolveJsonModule entry to tsconfig.json entry

{
    "compilerOptions": {  
      "esModuleInterop": true
      "resolveJsonModule": true
    } 
}

Finally, import the data and access it using the below code.

import data from './data.json';

interface Person{
    FirstName: string,
    UserId: number,
}

const userArray:User[] = data as User[];


66 Views Posted on February 27, 2022

Microsoft SQL Server Management Studio cannot remember the password

In SQL Server Management Studio 2005, all credentials are stored in the mru.dat file.
However, SQL Server Management Studio 2008 and higher versions save the logins in the SqlStudio.bin file.
In order to remember the password, you need to create a file to the corresponding location.

SQL Server Management Studio 2012 and Above:

C:\Users\%username%\AppData\Roaming\Microsoft\SQL Server Management Studio\<version>\SqlStudio.bin


SQL Server Management Studio 2008:

C:\Users\%username%\AppData\Roaming\Microsoft\Microsoft SQL Server\100\Tools\Shell\SqlStudio.bin


SQL Server Management Studio 2005:
In Windows 8/7/Vista:

C:\Users\%username%\AppData\Roaming\Microsoft\Microsoft SQL Server\90\Tools\Shell\mru.dat

Windows XP:

C:\Documents and Settings\%username%\Application Data\Microsoft\Microsoft SQL Server\90\Tools\Shell\mru.dat


In order to clear or remove the saved password just delete the mru.dat or SqlStudio.bin to the corresponding location


20 Views Posted on February 25, 2022

npm - EPERM: operation not permitted on Windows

npm start command encounters An unhandled exception occurred: EPERM: operation not permitted

Here is the simplest way I fixed the bug.

Open .npmrc file located on C:\Users\<user name>\.npmrc

Change the path of prefix= to prefix=C:\Users\<user name>\AppData\Roaming\npm

Delete node_modules folder and run npm install command

Then run npm start command


30 Views Posted on February 20, 2022

Next.js add top progress bar fetch and router events using NProgress

Here are the steps to show the top progress bar like Youtube.

First, install nprogress package using the below command

npm install nprogress

Then create components/TopProgressBar.js and add the following code

import Router from "next/router";
import NProgress from "nprogress";

let timer;
let state;
let activeRequests = 0;
const delay = 5;

const load = () => {
  if (state === "loading") {
    return;
  }

  state = "loading";

  timer = setTimeout(function () {
    NProgress.start();
  }, delay);
}

const stop = () => {
  if (activeRequests > 0) {
    return;
  }

  state = "stop";

  clearTimeout(timer);
  NProgress.done();
}

Router.events.on("routeChangeStart", load);
Router.events.on("routeChangeComplete", stop);
Router.events.on("routeChangeError", stop);

const originalFetch = window.fetch;
window.fetch = async function (...args) {
  if (activeRequests === 0) {
    load();
  }

  activeRequests++;

  try {
    const response = await originalFetch(...args);
    return response;
  } catch (error) {
    return Promise.reject(error);
  } finally {
    activeRequests -= 1;
    if (activeRequests === 0) {
      stop();
    }
  }
};

export default function () {
  return null;
}

Finally, add this component to _app.js

import "nprogress/nprogress.css";

const TopProgressBar = dynamic(() => {
    return import("components/TopProgressBar");
}, { ssr: false });

export default function MyApp({ Component, pageProps }) {
    return <>
        <TopProgressBar />
        <Component {...pageProps} />
    </>
}

That's it. It will show the top progress bar automatically.


32 Views Posted on February 19, 2022

Angular detect child component Input() changes using ngOnChanges

The following method is used to detect child component Input() changes in Angular using ngOnChanges()

import { Component, Input, OnChanges, SimpleChanges, ChangeDetectionStrategy } from '@angular/core';
import { User } from './user.model';

export class SelectedUserComponent implements OnChanges {
    @Input() user: User;

    ngOnChanges(changes: SimpleChanges) {
        console.log(changes);
    }
}


21 Views Posted on February 19, 2022

How to use Async Await inside react useEffect() hook

The following method is a safe way to use await and async inside react useEffect() hook

const getUsers = async () => {
    const users = await fetchUsers();
    setUsers(users);
};

useEffect(() => {
  getUsers(); // run it, run it

  return () => {
    // this now gets called when the component unmounts
  };
}, []);


10 Views Posted on February 19, 2022

Typescript Interface Pick, Omit usage, and Extends multiple interfaces

Sample interfaces

export interface Credentials {  
  email: string;
  password: string;
}

export interface User {
  firstName: string;
  lastName: string;
  age: number;
}

Pick constructs a type by picking the set of properties Keys (string literal or union of string literals) from Type

Pick syntax

Pick<Type, Keys>

Example

var newInterface: Pick<Credentials, 'email'> = {} as Pick<Credentials, 'email'>;
//newInterface contains email only

Omit constructs a type by picking all properties from Type and then removing Keys (string literal or union of string literals).

Omit syntax

Omit<Type, Keys>

Example

var newInterface: Pick<Credentials, 'email'> = {} as Pick<Credentials, 'email'>;
//newInterface omits email

Extends multiple interfaces

interface UserCredentials extends Credentials, User { }  //Extends Credentials, User
interface UserCredentials extends Credentials, Pick<User, 'firstName' | 'lastName' > { }  //Extends Credentials, User (firstName, lastName only)
interface UserCredentials extends Credentials, Omit<User, 'firstName' | 'lastName' > { }   //Extends Credentials, User (age only)


15 Views Posted on February 18, 2022

Best and easy way to use Async parallel in Node Js

Using the below method can get the results for each task very easily

async.parallel({
    firstTask: function (callback) {
        callback(null, 'fist task result');
    },
    secondTask: function (callback) {
        callback(null, 'second task result');
    }
}, function (err, results) {
    // results now equals to: results.firstTask: 'fist task result', results.secondTask: 'second task result'
});


72 Views Posted on February 10, 2022

Javascript sort an array based on another array

Data array

var dataArray = [
    { name: 'Alberta Owen', id: 1 },
    { name: 'Jimmy Murphy', id: 2 },
    { name: 'Jerald Roberson', id: 3 },
    { name: 'Roosevelt Douglas', id: 4 },
    { name: 'Mark Ramsey', id: 5 }
]

Sort array

var sortArray = ['Mark Ramsey', 'Jimmy Murphy', 'Alberta Owen'];

Sorting

dataArray.sort((a, b) => sortArray.indexOf(a) - sortArray.indexOf(b));


20 Views Posted on February 10, 2022
SPONSORS