Full Trust European Hosting

BLOG about Full Trust Hosting and Its Technology - Dedicated to European Windows Hosting Customer

AngularJS Hosting Europe - HostForLIFE :: Show File Upload Progress With Multiple Files In Angular

clock June 15, 2022 08:47 by author Peter

This article demonstrates the file upload with progress bar indicator showing how bytes or percentage has been completed.

Create Angular application
Let's create an angular application using angular cli.

We need to have node.js and angular cli installed on our pc to get started with angular application.

First we have to make sure that node.js is installed. You can download node.js from here.

In order to make sure that we have Angular CLI installed, open the command prompt and type the below command and press Enter:
npm install -g @angular/cli

Create a new project with choice of your name by entering name in command prompt like this:
ng new FileUploadProgress

Let's create a service for file upload. code of angular service looks like this:
import { Injectable } from '@angular/core';
import { HttpHeaders, HttpClient, HttpEventType } from '@angular/common/http';
import { map } from 'rxjs/operators';

@Injectable()
export class MediaService {
  fileSizeUnit: number = 1024;
  public isApiSetup = false;

  constructor(private http: HttpClient) {}

  getFileSize(fileSize: number): number {
    if (fileSize > 0) {
      if (fileSize < this.fileSizeUnit * this.fileSizeUnit) {
        fileSize = parseFloat((fileSize / this.fileSizeUnit).toFixed(2));
      } else if (
        fileSize <
        this.fileSizeUnit * this.fileSizeUnit * this.fileSizeUnit
      ) {
        fileSize = parseFloat(
          (fileSize / this.fileSizeUnit / this.fileSizeUnit).toFixed(2)
        );
      }
    }

    return fileSize;
  }

  getFileSizeUnit(fileSize: number) {
    let fileSizeInWords = 'bytes';

    if (fileSize > 0) {
      if (fileSize < this.fileSizeUnit) {
        fileSizeInWords = 'bytes';
      } else if (fileSize < this.fileSizeUnit * this.fileSizeUnit) {
        fileSizeInWords = 'KB';
      } else if (
        fileSize <
        this.fileSizeUnit * this.fileSizeUnit * this.fileSizeUnit
      ) {
        fileSizeInWords = 'MB';
      }
    }

    return fileSizeInWords;
  }

  uploadMedia(formData: any) {
    const headers = new HttpHeaders().set('Content-Type', 'application/json');

    return this.http
      .post(`http://yourapiurl`, formData, {
        headers,
        reportProgress: true,
        observe: 'events',
      })
      .pipe(
        map((event) => {
          switch (event.type) {
            case HttpEventType.UploadProgress:
              const progress = Math.round((100 * event.loaded) / event.total);
              return { status: 'progress', message: progress };

            case HttpEventType.Response:
              return event.body;
            default:
              return `Unhandled event: ${event.type}`;
          }
        })
      );
  }
}


Here, if you see we have used HttpClient to send POST request with multi-part form data to the server.

Please check uploadMedia method in the above code. HttpClient's post method's third parameter expects options object. The notable properties in our case are reportProgress and observe.

In order to get the progress reportProgress must be set to true and observe must be set to 'events'.

Here, inside map function of rxjs, we will check for the event type in swtich case statements. Rather than using integer values to compare, we can use  HttpEventType enum provided by the package @angular/common/http. In our case, only two enum values are useful such as UploadProgress and Response.

In both cases, I have decided to use the common object having two properties such as status and message.

status can have two values such as 'progress' and 'completed', later one will be returned from the server which will be handled by case HttpEventType.Response.

Also, this service contains two other methods such as getFileSize and getFileSizeUnit. These methods will be used to show the file size and it's unit either bytes, KB or MB.

Let's see how to use this service into our component.

Let's create a new component and typescript code looks like this:
import { Component, OnInit } from '@angular/core';
import { Subject } from 'rxjs';
import { takeUntil } from 'rxjs/operators';
import { MediaService } from '../media.service';

@Component({
  selector: 'app-media',
  templateUrl: './media.component.html',
  styleUrls: ['./media.component.css'],
})
export class MediaComponent implements OnInit {
  uploadedMedia: Array<any> = [];

  constructor(private mediaService: MediaService) {}

  ngOnInit() {}

  onFileBrowse(event: Event) {
    const target = event.target as HTMLInputElement;
    this.processFiles(target.files);
  }
  processFiles(files) {
    for (const file of files) {
      var reader = new FileReader();
      reader.readAsDataURL(file); // read file as data url
      reader.onload = (event: any) => {
        // called once readAsDataURL is completed

        this.uploadedMedia.push({
          FileName: file.name,
          FileSize:
            this.mediaService.getFileSize(file.size) +
            ' ' +
            this.mediaService.getFileSizeUnit(file.size),
          FileType: file.type,
          FileUrl: event.target.result,
          FileProgessSize: 0,
          FileProgress: 0,
          ngUnsubscribe: new Subject<any>(),
        });

        this.startProgress(file, this.uploadedMedia.length - 1);
      };
    }
  }

  async startProgress(file, index) {
    let filteredFile = this.uploadedMedia
      .filter((u, index) => index === index)
      .pop();

    if (filteredFile != null) {
      let fileSize = this.mediaService.getFileSize(file.size);
      let fileSizeInWords = this.mediaService.getFileSizeUnit(file.size);
      if (this.mediaService.isApiSetup) {
        let formData = new FormData();
        formData.append('File', file);

        this.mediaService
          .uploadMedia(formData)
          .pipe(takeUntil(file.ngUnsubscribe))
          .subscribe(
            (res: any) => {
              if (res.status === 'progress') {
                let completedPercentage = parseFloat(res.message);
                filteredFile.FileProgessSize = `${(
                  (fileSize * completedPercentage) /
                  100
                ).toFixed(2)} ${fileSizeInWords}`;
                filteredFile.FileProgress = completedPercentage;
              } else if (res.status === 'completed') {
                filteredFile.Id = res.Id;

                filteredFile.FileProgessSize = fileSize + ' ' + fileSizeInWords;
                filteredFile.FileProgress = 100;
              }
            },
            (error: any) => {
              console.log('file upload error');
              console.log(error);
            }
          );
      } else {
        for (
          var f = 0;
          f < fileSize + fileSize * 0.0001;
          f += fileSize * 0.01
        ) {
          filteredFile.FileProgessSize = f.toFixed(2) + ' ' + fileSizeInWords;
          var percentUploaded = Math.round((f / fileSize) * 100);
          filteredFile.FileProgress = percentUploaded;
          await this.fakeWaiter(Math.floor(Math.random() * 35) + 1);
        }
      }
    }
  }

  fakeWaiter(ms: number) {
    return new Promise((resolve) => {
      setTimeout(resolve, ms);
    });
  }

  removeImage(idx: number) {
    this.uploadedMedia = this.uploadedMedia.filter((u, index) => index !== idx);
  }
}


Now, add below code in HTML file of this component:
<h2>File upload with progress bar indicator</h2>
<input type="file" accept=".jpg,.jpeg,.png" (change)="onFileBrowse($event)" />
<div class="media-upload-table-container" *ngIf="uploadedMedia.length > 0">
  <table class="media-upload-table table table-borderless">
    <thead>
      <tr>
        <th style="width: 246px"></th>
        <th class="media-progress-bar"></th>
        <th style="width: 100px;"></th>
      </tr>
    </thead>
    <tbody>
      <tr *ngFor="let media of uploadedMedia; let i = index">
        <td>
          <div class="d-flex flex-row align-items-center">
            <!-- <div style="margin-right: 8px;">
                <img  class="add-media-img" src="{{media.FileUrl}}">
              </div> -->
            <div class="media-file-name">
              <span style="word-wrap: break-word; white-space: pre-line">
                {{ media.FileName }}
              </span>
            </div>
          </div>
        </td>
        <td style="vertical-align:middle;">
          <div class="d-flex flex-column" style="margin-top: 18px;">
            <div>
              <div class="first-progress">
                <div
                  [ngStyle]="{ 'width.%': media.FileProgress }"
                  class="second-progress"
                ></div>
              </div>
            </div>
            <div class="text-center">
              {{ media.FileProgessSize }} of {{ media.FileSize }}
            </div>
          </div>
        </td>
        <td style="vertical-align:middle;text-align: right;">
          <div class="media-upload-check">
            <span *ngIf="media.FileProgress === 100"> Completed</span>
          </div>
        </td>
        <td style="vertical-align:middle;">
          <a class="remove-media-txt" (click)="removeImage(i)"> Remove </a>
        </td>
      </tr>
    </tbody>
  </table>
</div>

If you see in above typescript code of the new component we have just created, there is a method startProgress. Here, we are using uploadedMedia array to keep track of the media uploaded by the user and it will show the progress of each uploaded file in the grid.

If you have noticed, our media service typescript code has one boolean flag isApiSetup. Here. We are using this flag to decide whether we want to upload files on actual server or not.

If you want to use the actual API of server then follow below steps,

  • Set value of isApiSetup to true and we will use the file upload on the server. here when 'progress' or 'completed' status received we will calculate file size and update it in the relevant object in the list.
  • Also, file object in the list has ngUnsubscribe property which is used in takeUntil operator of rxjs. So once, the user removes the file before 100% completion, we will send some value to it. So, file upload on the server will be canceled.

If you want to use the just fake waitor to simulate the working of file upload,

  • Set value of isApiSetup to false and we will use fake waiter to emulate the file upload rather than uploading the file on the server. It is useful if there is no api developed for file upload but still you want to check and modify and design of progress bar, percentage, file size etc. so, you don't have to rely on the api to test and modify the design.
  • In this case, fakeWaitor method will return the promise which will be resolved after a certain amount of time in parameter and this will be continuously done until for loop variable has reached to value of original file size.

Now, we need to use our component and service both in our application and for that we need to update app.module.ts file (which will be generated automatically by angular cli when new project is created).

Typescript code for app.module.ts looks like this,
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
import { AppComponent } from './app.component';
import { MediaComponent } from './media/media.component';
import { MediaService } from './media.service';
import { HttpClientModule } from '@angular/common/http';


@NgModule({
  imports: [BrowserModule, FormsModule, HttpClientModule],
  declarations: [AppComponent, MediaComponent],
  bootstrap: [AppComponent],
  providers: [MediaService],
})
export class AppModule {}


That’s it. Fire the following command to see the charm!
ng serve

Now, open your browser and visit this URL: http://localhost:4200/ to see it in action.

Here are a few snapshots of this application:




Node.js Hosting - HostForLIFE :: How To Check If A File Exists In NodeJS?

clock June 14, 2022 10:31 by author Peter

Node.js comes bundled with the file system module which allows the developers to interact with the file system of the operating system. This module is commonly used to create, read, update, delete and rename a file. However, before we start performing the above-mentioned operations it is always a better idea to check if the file we're trying to access exists in the file system. And the file system module provides multiple ways to perform this check.

Using existsSync method
The easiest way to test if a file exists in the file system is by using the existsSync method. All you need to do is pass the path of the file to this method.
const fs = require('fs');
const path = './my-awesome-file.txt';

if (fs.existsSync(path)) {
  console.log('file exists');
} else {
  console.log('file not found!');
}


The existsSync method will return true if the file exists and else it'll return false.
    One thing that we need to keep in mind is this method is synchronous in nature. that means that it’s blocking.

Using exists method (Deprecated)
The exists method checks for the existence of a file asynchronously. It accepts two parameters:

    Path to the file
    Callback function to execute once path is verified passing a boolean parameter value to the function as its argument.

const fs = require('fs');
const path = './my-awesome-file.txt';

fs.exists(path, function (doesExist) {
  if (doesExist) {
    console.log('file exists');
  } else {
    console.log('file not found!');
  }
});

The parameter value will be true when the file exists otherwise it'll be false.

Using accessSync method
The accessSync method is used to verify the user’s permission for the specified path. If the path is not found, it will throw an error that we need to handle using try...catch block.

This method accepts two parameters as follows,
    Path to the file
    Mode of verification

The mode parameter is optional. It specifies the accessibility checks that need to be performed.0

Following constants can be used as the second parameter to specify the mode.
    fs.constants.R_OK to check for read permission
    fs.constants.W_OK to check for write permission
    fs.constants.X_OK to check for execute permission


If the second parameter is not provided it defaults to  fs.constants.F_OK constant.
const fs = require('fs');
const path = './my-awesome-file.txt';

try {
  fs.accessSync(path);
  console.log('file exists');
} catch (err) {
  console.log('file not found');
  console.error(err);
}

The above code verifies the existence of my-awesome-file.txt file:

If you wish to determine the write and read access, you can pass the mode parameter with a bitwise OR operator as follows:
const fs = require('fs');
const path = './my-awesome-file.txt';

try {
  fs.accessSync(path, fs.constants.R_OK | fs.constants.W_OK);
  console.log('read/write access');
} catch (err) {
  console.log('no access:');
  console.error(err);
}

Using access method
The access method is basically the asynchronous version of accessSync method.

The access method allows the developers to verify the existence or permissions of a specified path asynchronously.

The method accepts three parameters, first two parameters are the same as accessSync method parameters, and last parameter is a callback function:
    Path to the file
    Mode of verification
    The callback function to execute

const fs = require('fs')
const path = './my-awesome-file.txt'

fs.access(path, fs.F_OK, (err) => {
  if (err) {
    console.error(err)
    return;
  } else {
    console.log('file exists')
  }
})


existsSync, exists, accessSync, and access are the four methods that allow the developers to verify if the file exists in the file system. It’s recommended to use existsSync method if you only wish to check for the existence of a file. When you wish to check for specific permissions as well as the existence of the file, you can use either accessSync or access method. The exists method is deprecated from node.js and hence needs to be avoided. 



Node.js Hosting Europe - HostForLIFE :: How To Check If A File Exists In NodeJS?

clock May 30, 2022 08:55 by author Peter

Node.js comes bundled with the file system module which allows the developers to interact with the file system of the operating system. This module is commonly used to create, read, update, delete and rename a file. However, before we start performing the above-mentioned operations it is always a better idea to check if the file we're trying to access exists in the file system. And the file system module provides multiple ways to perform this check.

Using existsSync method
The easiest way to test if a file exists in the file system is by using the existsSync method. All you need to do is pass the path of the file to this method.

const fs = require('fs');
const path = './my-awesome-file.txt';

if (fs.existsSync(path)) {
  console.log('file exists');
} else {
  console.log('file not found!');
}


The existsSync method will return true if the file exists and else it'll return false.
    One thing that we need to keep in mind is this method is synchronous in nature. that means that it’s blocking.

Using exists method (Deprecated)
The exists method checks for the existence of a file asynchronously. It accepts two parameters:

    Path to the file
    Callback function to execute once path is verified passing a boolean parameter value to the function as its argument.

const fs = require('fs');
const path = './my-awesome-file.txt';

fs.exists(path, function (doesExist) {
  if (doesExist) {
    console.log('file exists');
  } else {
    console.log('file not found!');
  }
});


The parameter value will be true when the file exists otherwise it'll be false.

Using accessSync method
The accessSync method is used to verify the user’s permission for the specified path. If the path is not found, it will throw an error that we need to handle using try...catch block.

This method accepts two parameters as follows,
    Path to the file
    Mode of verification

The mode parameter is optional. It specifies the accessibility checks that need to be performed.0

Following constants can be used as the second parameter to specify the mode.
    fs.constants.R_OK to check for read permission
    fs.constants.W_OK to check for write permission
    fs.constants.X_OK to check for execute permission

If the second parameter is not provided it defaults to  fs.constants.F_OK constant.
const fs = require('fs');
const path = './my-awesome-file.txt';

try {
  fs.accessSync(path);
  console.log('file exists');
} catch (err) {
  console.log('file not found');
  console.error(err);
}


The above code verifies the existence of my-awesome-file.txt file:

If you wish to determine the write and read access, you can pass the mode parameter with a bitwise OR operator as follows:
const fs = require('fs');
const path = './my-awesome-file.txt';

try {
  fs.accessSync(path, fs.constants.R_OK | fs.constants.W_OK);
  console.log('read/write access');
} catch (err) {
  console.log('no access:');
  console.error(err);
}


Using access method
The access method is basically the asynchronous version of accessSync method.

The access method allows the developers to verify the existence or permissions of a specified path asynchronously.

The method accepts three parameters, first two parameters are the same as accessSync method parameters, and last parameter is a callback function:
    Path to the file
    Mode of verification
    The callback function to execute

const fs = require('fs')
const path = './my-awesome-file.txt'

fs.access(path, fs.F_OK, (err) => {
  if (err) {
    console.error(err)
    return;
  } else {
    console.log('file exists')
  }
})


Summary
existsSync, exists, accessSync, and access are the four methods that allow the developers to verify if the file exists in the file system. It’s recommended to use existsSync method if you only wish to check for the existence of a file. When you wish to check for specific permissions as well as the existence of the file, you can use either accessSync or access method. The exists method is deprecated from node.js and hence needs to be avoided. 



AngularJS Hosting Europe - HostForLIFE :: Using HTTP Interceptor Service In Angular App

clock May 19, 2022 09:54 by author Peter

HTTP Interceptor
HTTP Interceptors is a special type of angular service that we can implement. It's used to apply custom logic to the central point between the client-side and server-side outgoing/incoming HTTP request and response. Keep in mind that the interceptor wants only HTTP requests.

Operations of HTTP Interceptor

    Modify HTTP headers
    Modifying the request body
    Set authentication/authorization token
    Modify the HTTP response
    Error handling

Add HTTP Interceptor

Execute this CLI command to add an interceptor service: ng generate interceptor headers

Successfully added headers interceptor

After opening the interceptor service you can see a default view like this:


Interceptor registration
We need to register the HTTP interceptor to use in the application. So, open the app.module.ts file and go to the provider section.

This interceptor will execute for every HTTP request of a client.

Modifying HTTP Headers By interceptor

const apiKey = 'Rohol Amin'
request = request.clone({
    setHeaders: {
        'api-key': apiKey,
    }
})

Now serve the project. Open the browser inspect window then go to the Network tab and click the load data button. Then click the todos API of xhr type. Then go to the HTTP request headers,

Multiple interceptors
It is also possible to use multiple interceptors simultaneously. Just need to maintain the serial which service will be executed before and after. This serialization is defined in provider registration. Meaning the interceptor service will execute according to the provider registration serialization.


{
  provide: HTTP_INTERCEPTORS,
  useClass: ResponseInterceptor,
  multi: true
}

Response Interceptor Implementation

const startTime = (new Date()).getTime();
return next.handle(request).pipe(map(event => {
    if (event instanceof HttpResponse) {
        const endTime = (new Date).getTime();
        const responseTime = endTime - startTime;
        console.log(`${event.url} succeed in ${responseTime} ms`)
    }
    return event;
}));

Note
This HTTP interceptor is most used when authentication and authorization are applied in the application.

Hope this article would have helped you to understand about Angular Interceptor. Here I have tried to explain very simply some uses of the angular interceptor. Happy coding and thanks for reading my article!!!



Node.js Hosting Europe - HostForLIFE :: Create a Redis Cache with Express Node JS

clock May 11, 2022 09:02 by author Peter

This article provides a sample application using the Redis Cache with explanation. Please see this article on how to create an Express Node JS application, so that we can quickly jump into the topic without further delay.

Why is Caching required?
When the same response needs to be served multiple times, store the data in distributed server memory as and it can be retrieved faster than the data retrieved from the storage layer for every single call. Caching is an ability of an application to duplicate the values for a specified period of time and serve the web request instantly.

These techniques will be effective when
    There is a need to call for a 3rd party API and the call counts
    Cost of data transfer between cloud and the server.
    Server response is critical based on the concurrent requests.

What is Redis Cache?
The data cache stored in a centralized distributed system such as Redis. Redis is also called a data structures server, which means a variety of processes can query and modify the data at the same time without much loading time.
Advantages of Redis

The special properties of data structures are

    Even though the data is often requested, served and modified, the data will be stored in disk rather than storing in RAM.
    Unlike high-level programming language, the implementation will highlight on memory optimal usage.
    Also offers features like replication, levels of durability, clustering and high availability (HA).
    Redis can handled complexed Memcached operations like Lists, Sets, ordered data set, etc.,

Using Redis Client in local system

To use the Redis, you need to install Node JS Redis Client in the local system. The msi file (v3.0.504 stable version as of this article published date) can be downloaded from the Github and proceed with normal installation process (for Windows OS).

The latest Redis Client can be also be installed with Windows Subsystem for Linux (WSL) and install the Redis 6.x versions. Also, for dockerizing, Mac and Linux OS’ follow the instructions on downloads

Run the Redis Client by the following command

redis-server

Create an Express Node JS application

Open the PowerShell or cmd prompt window and go to the destined folder.

Execute the following command
npx express expressRedisCaching –hbs

Install the modules using the command
npm i

and install the following additional packages
npm i redis
npm i isomorphic-fetch


Once all the packages are installed and ready to start. I have created a new route page called “getCached.js” and mapped in the “App.js” page.
app.use('/getCached', require('./routes/getCached'));

Upon calling the endpoint, the logic is to fetch the response from JSON placeholder (mock API) site, store the data in Redis Cache and respond to the request. On further request, cached data will be served.
const express = require('express')
require('isomorphic-fetch')
const redis = require('redis')
const router = express.Router()
const client = redis.createClient({
    host:'127.0.0.1',
    port:6379
})



router.get('/',async(req, res)=>{

        await client.connect();
        const value = await client.get('todos');
        if(value){

            console.log("from cached data")
            res.send(JSON.parse(value))
        }
        else{

            const resp = await fetch(sourceURL)
               .then((response) => response.json());
            await client.set('todos', JSON.stringify(resp));
            console.log("from source data")
            res.send(resp);
        }
        await client.disconnect();

})

module.exports = router

Object created using the redis is
redis.createClient({ host:’127.0.0.1’, port:6379});

With options
    host : currently the Redis is available in the local system and so the host is default 127.0.0.1
    port : by default Windows OS is allocating 6379 port to Redis, but the same can be customized.

Now it’s time to run the app by executing the command
npm start

 

On the first hit, the data is fetched from the source API with the response time of approximately 1156ms and the same has been stored in the in-memory data store Redis Cache. The second hit gets the data from the cached with the remarkable reduction in fetch time of just ~10 ms or even ~6ms.

Thus, the objective is met with very few easy steps.



Europe mySQL Hosting - HostForLIFEASP.NET :: Setup Local Database In SQL Server

clock April 19, 2022 10:12 by author Peter

Requirements
Microsoft SQL Server. If not installed, go to the official site and download and install the setup file.

STEP 1

    Go to Start and search for Microsoft SQL Server.
    You can find an option for Microsoft SQL Server Management Studio.
    Click on it to open the SQL Management Studio.

STEP 2

    To create a local database, you need a Server first.
    While installing the SQL Server, you would have set a user which will act as the Server.
    Select the Server and also ensure that the credentials you are providing in the authentication processes are right.
    After entering all the details, click on the "Connect" button.
    If the connection fails, check if the Server is in running state.
    If it is not running, just right click on the Local Sever and click on the Start option.
    You can find the Server in the Local Server option of the Registered Servers.
    To view the registered servers, go to VIEW -> REGISTERED SERVERS.

STEP 3

  1. Now, you are connected to the Server, so can you create a database.
  2. In the Object Explorer, find the Databases folder.
  3. Simply right click on it and select new database option.
  4. This will initiate the new database creation.

Step 4

  1. You will see a window when clicked on the new database option.There, you can add the new database.
  2. You can add more than one database on the same Server.
  3. Click on the "Add" button to add a new database.
  4. If you want to remove any database, just click on the "Remove" button.
  5. Once you are finished with adding your required number of databases, click on the OK button.
STEP 5
    Now, you can see a new database appearing in the database menu in the Object Explorer. You can now use this database for your local storage.

So, this was the process for local database creation using MS SQL
In my next write-up, I will explain the steps for writing queries and creating tables. Thank you.



Node.js Hosting Europe - HostForLIFE :: How To Make Middleware In Node.js

clock April 13, 2022 09:13 by author Peter

Node.js is a backend framework based on Javascript. It is said to be 10x faster as compared to other backend languages as it is developed keeping in mind Javascript runtime browser compatibility.


Node.js uses non-blocking I/O, the main reason for making it lightweight and efficient.

Moreover, it is open-source, cross-platform runtime environment for developing server-side applications.

Some other backend languages,
    PYTHON.
    PHP LARVEL.
    GOLANG.
    C#.
    RUBY.
    JAVA.

But the fact is node.js is said to be fastest among all as it totally works on npm (node package manager) which gives developers multiple tools and modules to use thus helping in execution of code in the fastest way as possible.
Requirements

Starting with nodejs is an easy task just by downloading/installing it, if not yet downloaded, here’s the link to download.

After installing node.js on your  local computer or laptop, to check node gets properly installed on a particular system, open command prompt and type node -v to check.

There you go😊. Creating Middleware using Express Apps - Overview

Middleware functions are functions that have access to the request object (req), the response object (res), and the next function in the application’s request-response cycle. The next function is in the Express router which, when invoked, executes the middleware succeeding the current middleware.

The following task can be performed through middleware,
    Execute any code.
    Make changes to the request and the response objects.
    End the request-response cycle.
    Call the next middleware in the stack.

If the current middleware function does not end the request-response cycle, it must call next() to pass control to the next middleware function. Otherwise, the request will be left hanging.

The following figure shows the elements of a middleware function call,

HTTP method.
Path (route) for which the middleware function applies
The middleware function.
Callback argument to the middleware function.
HTTP response argument to the middleware.
HTTP request argument to the middleware

Starting with Express 5, middleware functions that return a Promise will call next(value) when they reject or throw an error.

next will be called with either the rejected value or the thrown Error.

Example
Here is an example of a simple “Hello World” Express application. The use of this article will define and add three middleware functions to the application: one called myLogger that prints a simple log message, one called requestTime that displays the timestamp of the HTTP request, and one called validateCookies that validates incoming cookies.
const express = require('express')
const app = express()
app.get('/', (req, res) => {
    res.send('Hello World!')
})
app.listen(3000)


Middleware function myLogger
Here is a simple example of a middleware function called “myLogger”. This function just prints “LOGGED” when a request to the app passes through it. The middleware function is assigned to a variable named myLogger.
const myLogger = function(req, res, next) {
    console.log('LOGGED')
    next()
}


Notice the call above to next(). Calling this function invokes the next middleware function in the app. The next() function is not a part of the Node.js or Express API but is the third argument that is passed to the middleware function. The next() function could be named anything, but by convention it is always named “next”. To avoid confusion, always use this convention.

To load the middleware function, call app.use(), specifying the middleware function. For example, the following code loads the myLogger middleware function before the route to the root path (/).
const express = require('express')
const app = express()
const myLogger = function(req, res, next) {
    console.log('LOGGED')
    next()
}
app.use(myLogger)
app.get('/', (req, res) => {
    res.send('Hello World!')
})
app.listen(3000)


Every time the app receives a request, it prints the message “LOGGED” to the terminal.

The order of middleware loading is important: middleware functions that are loaded first are also executed first.

If myLogger is loaded after the route to the root path, the request never reaches it and the app doesn’t print “LOGGED”, because the route handler of the root path terminates the request-response cycle.

The middleware function myLogger simply prints a message, then passes on the request to the next middleware function in the stack by calling the next() function.

Middleware function requestTime

Next, we’ll create a middleware function called “requestTime” and add a property called requestTime to the request object.
const requestTime = function(req, res, next) {
    req.requestTime = Date.now()
    next()
}


The app now uses the requestTime middleware function. Also, the callback function of the root path route uses the property that the middleware function adds to req (the request object).
const express = require('express')
const app = express()
const requestTime = function(req, res, next) {
    req.requestTime = Date.now()
    next()
}
app.use(requestTime)
app.get('/', (req, res) => {
    let responseText = 'Hello World!<br>'
    responseText += `<small>Requested at: ${req.requestTime}</small>`
    res.send(responseText)
})
app.listen(3000)


When you make a request to the root of the app, the app now displays the timestamp of your request in the browser.
Middleware function validateCookies

Finally, we’ll create a middleware function that validates incoming cookies and sends a 400 response if cookies are invalid.

Here’s an example function that validates cookies with an external async service.
async function cookieValidator(cookies) {
    try {
        await externallyValidateCookie(cookies.testCookie)
    } catch {
        throw new Error('Invalid cookies')
    }
}


Here we use the cookie-parser middleware to parse incoming cookies off the req object and pass them to our cookieValidator function. The validateCookies middleware returns a Promise that upon rejection will automatically trigger our error handler.
const express = require('express')
const cookieParser = require('cookie-parser')
const cookieValidator = require('./cookieValidator')
const app = express()
async function validateCookies(req, res, next) {
    await cookieValidator(req.cookies)
    next()
}
app.use(cookieParser())
app.use(validateCookies)
// error handler
app.use((err, req, res, next) => {
    res.status(400).send(err.message)
})
app.listen(3000)


Note how next() is called after await cookieValidator(req.cookies). This ensures that if cookieValidator resolves, the next middleware in the stack will get called. If you pass anything to the next() function (except the string 'route' or 'router'), Express regards the current request as being an error and will skip any remaining non-error handling routing and middleware functions.

Because you have access to the request object, the response object, the next middleware function in the stack, and the whole Node.js API, the possibilities with middleware functions are endless.

Configurable middleware

If you need your middleware to be configurable, export a function that accepts an options object or other parameters, which, then returns the middleware implementation based on the input parameters.

File: my-middleware.js
module.exports = function(options) {
    return function(req, res, next) {
        // Implement the middleware function based on the options object
        next()
    }
}
// The middleware can now be used as shown below.
const mw = require('./my-middleware.js')
app.use(mw({
    option1: '1',
    option2: '2'
}))


Summary
Depending on our short definition, middleware can be created for purposes such as database transactions, transactions between application servers, message controls, and authentication. Structures such as soap, rest, and JSON can be used in the communication of applications. The middleware acts according to all these purposes.



Europe mySQL Hosting - HostForLIFEASP.NET :: Compare JSON In MySql

clock April 5, 2022 09:39 by author Peter

Scenario
I have a small need where I have to compare 2 JSON Records in MySql. The query will check both JSONs and will return some count if there is any modification in the new JSON record.


To help you understand easily, I am adding small JSON although I have some large JSON to compare.

To start, first create a test table.Compare JSON In MySql
CREATE TABLE `table1` (
    `id` int(11) NOT NULL AUTO_INCREMENT,
    `json_col` json DEFAULT NULL,
    PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;

To insert dummy JSON record, please use Insert query.

INSERT INTO `iaptsdb`.`table1`
(`json_col`)
VALUES('{"Unit": "109", "LastName": "Smith", "PersonId": "t0077508", "FirstName": "Karleen"}');

Now you have one record in table1.
Check by selecting this table1.

 

Now we will add our JSON Compare query to check JSON with above record.
We will update FirstName in new JSON and then we will compare it with above record.

I have SET FirstName to "John" and compare it to Record Id 1 in table1.

As FirstName is not equal to FirstName Record Id 1, hence it will reflect no record.**

set @some_json = '{"Unit": "109", "LastName": "Smith", "PersonId": "t0077508", "FirstName": "John"}';
select * from  table1
 WHERE
 CAST(json_col as JSON) = CAST(@some_json as JSON);


If we add "Karleen" as FirstName in JSON, the query will compare and as record is same, so it reflect one record.


P.S: Sequence in JSON Key:Value doesn't matter. :)
If you have implemented other approaches, please share them in the comments as well.



European Visual Studio 2022 Hosting - HostForLIFE :: How To Enable Preview Version In Visual Studio 2022?

clock March 24, 2022 09:08 by author Peter

As we know Microsoft has released Visual Studio 2022 17.2 Preview1 (VS2022 17.2 Preview 1) recently. Just a few months before I had installed Visual Studio 2022 17.1-Current version of visual studio. I was exploring how can I get started and learn .NET 7 preview in my working machine. So, in this article, we will learn how to switch from the current Visual Studio version to the Preview version with a demonstration of switching from Visual Studio 2022 17.1-Current version to the VS2022 17.2 Preview1 (VS2022 17.2 Preview 1).

To move from Visual Studio 2022 17.1 current version to the VS2022 17.2 Preview1 (VS2022 17.2 Preview 1), you need to install the following prerequisites in your machine. Download it and install those.

  • .NET 7 Preview
  • Visual Studio 2022 17.2 Preview1

Then, follow the below steps for switching from the current to the preview version. This article is written with the device which has already been installed Visual Studio 2022 in it. However, the switching process is the same for another version as well.

So, let’s begin.

Step 1 – Check for Update
Open Visual Studio and then go to Help–>Check for Updates as shown below.

Step 2 – Change Update Setting
Then, you will get the below screen. Here you can see my Visual Studio is up to date. So, to change the setting to Preview, click on change the update setting as highlighted below.

Alternatively, you can directly go to the update setting from Visual Studio Installer. Go to More and then Update Setting as illustrated below.

Step 3 – Update Channel
Select the update channel from Current to Preview and click on OK.

It will check for the update.

Step 4 – Click on Update
If there is an update required then click on Update.

As you can see on the above image, VS 2022 17.2.0 Preview contains a cumulative update with new features, updated components, and servicing fixes.

Step 5 – Updating
The update will take some time. Wait for it until the update is done.

Step 6 – Close and Restart
Once it is updated then restart the Visual studio.

Step 7 – Version checking
When you search for VS then you can see the preview is available in the search as shown below.

Alternatively, you can check the release version at any time. For this open the Visual Studio and go to Help–> Release Note.

Or go to Help–>check for the update then you will see the status of your Visual Studio.

Hence, once you set up VS2022 17.2 Preview1 (VS2022 17.2 Preview 1) then you are ready to learn and explore the .NET 7. To learn and get started with .NET 7 you can find the article here.

In this article, we have learned to switch from Visual Studio 2022 17.1 current version to Visual Studio 2022 17.2 Preview version and set up the Visual Studio development environment for .NET 7 and C# 11. Once your environment is ready then you can start your .NET 7.0 journey from here.



AngularJS Hosting Europe - HostForLIFE :: Difference Between Observable, Eventemitter, and Subject

clock March 21, 2022 09:17 by author Peter

When we start to use any new tools it is important to know why are we using it and where to use it. Likewise, it is important to understand the difference between Observable, EventEmitter, and Subject and where to use it. It always gets confusing to choose between Eventemitter and Subject for transferring data from one component to another component.

What is observable?

Angular uses observables as an interface to handle a variety of common asynchronous operations. We can also say it as a data source that will emit data over a period of time. It’ll start to emit data asynchronously when it is subscribed.

What is EventEmitter?

It is used with @Output directive to emit custom event synchronously or asynchronously using emit() method. Using EventEmitter we can transfer data from child component to parent component. It is true, we can transfer data from one component to another using EventEmitter but it is not recommended.

What is Subject?

It is a special type of observable that acts as both observable and observer. It’ll emit new value using next() method. All the subscribers who subscribe to the subject when emitted will receive the same value.

Which one to use for transferring data from one component to another, EventEmitter or Subject?

It is recommended to use Subject for transferring data from one component to another as EventEmitter extends Subject, adding a method emit().

Conclusion

  • Use Eventemitter when transferring data from child component to parent component.
  • Use Subject to transfer data from one component to another component.

 



About HostForLIFE

HostForLIFE is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes.

We have offered the latest Windows 2019 Hosting, ASP.NET 5 Hosting, ASP.NET MVC 6 Hosting and SQL 2019 Hosting.


Tag cloud

Sign in