Full Trust European Hosting

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

AngularJS Hosting Europe - HostForLIFE :: How To Use HTTP Interceptor In Angular?

clock November 28, 2022 07:16 by author Peter

Angular Interceptor helps us modify the HTTP request by intercepting it before the request is sent to the backend. You can also change the incoming response from the backend. The Interceptor globally captures all incoming and outgoing requests in one place. We can use it to add custom headers to the outgoing request, log the incoming response, etc.

 


What is HTTP Interceptor?
An Angular HTTP interceptor sits between your application and the backend. When the application makes a request, the interceptor sees the request (HttpRequest) before sending it to the backend. You can access the request headers and body by intercepting the request. This allows us to transform the request before sending it to the server.


When the response (HttpResponse) arrives from the backend, interceptors can transform it before forwarding it to the application. One of the main advantages of HTTP interceptors is the ability to add an Authorization header to every request. You can do this manually, but it's tedious and error-prone. Another benefit is the ability to catch and log errors generated by requests.

How to Create Interceptor?
To implement an interceptor, we need to create an injectable service that implements the HttpInterceptor interface.
@Injectable() export class MyHttpInterceptor implements HttpInterceptor {

This class should implement the Intercept method
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    //Do the code whatever you want with the HTTP request

    return next.handle(req);
}


This class is exposed in the root module using the HTTP_INTERCEPTORS injection token.
providers: [
    {
        provide: HTTP_INTERCEPTORS,
        useClass: MyHttpInterceptor,
        multi: true
    }
],


Interface: HTTP Interceptor
At the guts of the Interceptor, logic is the HttpInterceptor Interface. we have a tendency to should Implement it in our Interceptor Service.

The interface contains one method Intercept with the subsequent signature
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>>

HTTP Request
The first argument is HttpRequest.

HttpRequest is an intercepted outgoing HTTP request. It integrates URLs, methods, headers, body, and various request configurations.

HttpRequest is an immutable class. In any way, we cannot accommodate genuine claims. To make adjustments, we want to duplicate the original request using the HttpRequest.clone

HTTP Handler

The second argument is httpHandler

HttpHandler sends the HttpRequest to the next Controller using the HttpHandler.handleMethod. The next handler can be another interceptor in on Thread or the Http Backend.

Let's see the example

Create MyHttpInterceptor.ts under /app folder and paste the below code
import {Injectable} from "@angular/core";
import {HttpEvent, HttpHandler, HttpInterceptor,HttpRequest} from "@angular/common/http";
import {Observable} from "rxjs/Observable";

@Injectable()
export class MyHttpInterceptor implements HttpInterceptor {
    constructor() {
    }

    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

        return next.handle(req);
    }
}

In the body of the method, you should be able to modify the HttpRequest object. Once done, you can select the HttpHandler.handle method from the HttpHandler with the HttpRequest object. The HttpHandler.handle method calls the fighter thus or sends a request to the main server.

App.Module
Whole code from the app module
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { HttpClientModule,HTTP_INTERCEPTORS} from '@angular/common/http';
import { FormsModule } from '@angular/forms';

import { AppComponent } from './app.component';

import { GitHubService } from './github.service';
import {MyHttpInterceptor} from './MyHttpInterceptor';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    HttpClientModule,
    FormsModule
  ],
  providers: [GitHubService,
    {
    provide: HTTP_INTERCEPTORS,
    useClass: MyHttpInterceptor,
    multi: true
  }
],
  bootstrap: [AppComponent]
})
export class AppModule { }


If you have faced any error regarding the import module please check your package.json file and install the required package if not installed.
So, here interceptor-adding process is done let's run the app and you can see every HTTP calls interceptor, You can put the debugger in the interceptor and see.
Let's add content type using interceptor

Content Type Adding
To modify the request we want to clone it using HttpRequest.clone
req = req.clone({ headers: req.headers.set('Content-Type', 'application/json') });

The header object is also unchanged. Therefore, we need to duplicate it using the headers.set method. The header.set method copies the current header and adds/modifies the new header value and returns the copied header.

We can also use the header.append. The append technique continually appends the header albeit the worth is already present.

And we can also remove the header like the one below shown
req = req.clone({ headers: req.headers.delete('Content-Type','application/json') });

If you want to add authorization token then we can add a token as shown below
const bearerToken: string =authService.Token; // here you can use your service method where get token
if (token) {
    req = req.clone({ headers: req.headers.set('Authorization', 'Bearer ' + bearerToken) });
}


So we can change or add code as per our requirement like adding logging, modifying response, catching the errors, etc...



European Entity Framework Hosting - HostForLIFE :: Database Execution Policies In Entity Framework Core 6

clock November 23, 2022 06:42 by author Peter

We were developing a database project in .NET 6 using Entity Framework Core. Our back-end database engine was MySql rather than SQL server. It was a remote database. Short operations like single read and write worked fine but suddenly I stuck somewhere and got this horrible error.

The error was
“A second operation was started on this context instance before a previous operation was completed. This is usually caused by different threads concurrently using the same instance of DbContext.”

I started the operation again and surprisingly, this time the error was different regardless of the fact that all the inputs I provided were the same.

The error I got this time is:

The configured execution strategy 'MySqlRetryingExecutionStrategy' does not support user-initiated transactions. Use the execution strategy returned by 'DbContext.Database.CreateExecutionStrategy()' to execute all the operations in the transaction as a retriable unit.' ”

Please note that if you are using SQL Server as a database engine, You’ll receive SqlRetryingExecutionStrategy rather than MySqlRetryingExecutionStrategy.



I tested the application many times and explored the stack trace in detail and also do a lot of search online but failed to figure out the issue as my app followed all the suggested solution standards.

I started following a thread on github where one important thing was mentioned.

One has to be careful while working with sync and async method. If you are following sync method patterns in your code, better to follow it completely, mean use sync method in all of your codebase. Don’t mix sync calls with async calls in your code.

If you working with async methods in your code it is highly recommended to use the async method with await in all the places in your codebase.

This last line give me some hint to find out the issue so started exploring the code backward. From the position where error or exception was coming while going backward from line to line, there was an async function which has no await before its invocation.


As soon as I applied this await prior to this call, both errors are gone.



Node.js Hosting Europe - HostForLIFE :: Overview And Explore NestJS

clock November 22, 2022 09:21 by author Peter

This would be a series of articles and in this article, we would talk about NestJS, its background, installation, and how it can be used to build APIs.


It will cover the following things,
    What is NestJS?
    Background
    Installation
    Hands-on Lab – Create a sample NestJS project

What is NestJS?
    NestJS is fairly a popular and cumulative JavaScript framework functioning under the hood of Node.js
    It is used to build scalable, reliable, and efficient server-side applications.
    The framework is directed with the Node.js environment and supports Typescript fully.
    It also can be scaled to make use of Express.js under the influence of Node.js
    NestJS is a full Typescript-supported framework, it can enable developers like you to code purely in JavaScript
    Also, it would let you combine the concepts of Object-Oriented Programming(OOP), Functional Reactive Programming(FRP), and purely Functional Programming(FP).

Background

    NestJS makes use of heavy usage of the server-side framework like Express under the hood of robust HTTP infrastructure.
    It can also be optionally configured to make use of Fastify as well although Express is considered as default.
    NestJS aims to provide a certain level of abstraction mechanism to the developers so that not only the common server-side frameworks like Fastify or Express are integrated internally but can also be exposed to the APIs chosen by the developer.
    These hidden bars provide developers to gain the freedom to use the third-party modules brightly and they can be made to motivate in the NestJS platform without having to operate the entire server side.

Installation

    All you need to do is to make sure you have Nest CLI is primarily installed on your local computer.
    If it is not installed, make use of the Node Package Manager (NPM) and follow up the approach using the commands given below.
    Also, you would need to make sure Node.js and NPM are preinstalled in your local system. If not, just follow the instructions to install Node.js at https://nodejs.org/
    $ npm i –g @nestjs/cli

Hands-on Lab – Create a sample NestJS project

Steps to be followed,
    Once the NestJS CLI installation is marked complete, it will readily be available to use the commands.
    Now let’s proceed with creating a sample project, and use the following control to initialize it.

    nest new nestjs-demo

    cd nestjs-demo

    Open Visual Code and see the project structure with the following files -

    main.ts - It is the application's entry point which consists of a method NestFactory.create() which creates a new instance of the Nest application.
    app.modules.ts: It contains the module of the application's implementation.
    app.controller.ts: It consists of only one routed implementation controller of NestJS.
    app.services.ts: It is the usual service method implementation.
    app.controller.specs.ts: It tests the file for the controller.

    Run the application by executing the below command and look at the browser with the output.

In this article, we talked about the overview and basic implementation of NestJS, in the next article, we would talk about all the out-of-the-box files in detail and create a few custom APIs. Stay tuned for the next series of articles, hope you see you guys again soon.

Happy learning!



AngularJS Hosting Europe - HostForLIFE :: Angular CLI MODULE_NOT_FOUND Error

clock November 17, 2022 09:45 by author Peter

When we sometimes create a new project but can't create the project because of an error like the one below.

Here I have provided steps to resolve the issue.

Step 1
Run CMD as Run as administrator mode.

Step 2
Uninstall angular cli.
npm uninstall -g @angular/cli

Step 3
Remove npm package files from the appdata folder.

Step 4
Open Run option by pressing Windows + R key. Then type %appdata% and press OK.

Step 5
Open the npm folder from the Roaming folder that you got in explorer.

Step 6
Delete ng and ng.cmd files from the npm folder if exists.
Open node_modules folder from there and delete @angular and angular/cli folder if exists.

Step 7
Reinstall the angular cli
npm install -g @angular/cli

Create a new Project with the use of command

App is created and run with ng serve command like this



AngularJS Hosting Europe - HostForLIFE :: Caching - Service Worker

clock November 10, 2022 08:15 by author Peter

For Angular Caching issue, a service worker is a script that runs in the web browser and manages caching for an application. Service workers augment the traditional web deployment model and empower applications to deliver a user experience with reliability and performance on par with code that is written to run on your operating system and hardware. Adding a service worker to an Angular application is one of the steps for turning an application into a Progressive Web App (also known as a PWA).


At its simplest, a service worker is a script that runs in the web browser and manages caching for an application.

Service workers function as a network proxy. They intercept all outgoing HTTP requests made by the application and can choose how to respond to them. For example, they can query a local cache and deliver a cached response if one is available. Proxying isn't limited to requests made through programmatic APIs, such as fetch; it also includes resources referenced in HTML and even the initial request to index.html. Service worker-based caching is thus completely programmable and doesn't rely on server-specified caching headers.

Unlike the other scripts that make up an application, such as the Angular application bundle, the service worker is preserved after the user closes the tab. The next time that browser loads the application, the service worker loads first, and can intercept every request for resources to load the application. If the service worker is designed to do so, it can completely satisfy the loading of the application, without the need for the network.

Even across a fast reliable network, round-trip delays can introduce significant latency when loading the application. Using a service worker to reduce dependency on the network can significantly improve the user experience.

Note:
Below, until Run the App with Service Worker, the procedure we follow are mainly from

Simulating a network issue
To simulate a network issue, disable network interaction for your application.

In Chrome:
    Select Tools > Developer Tools (from the Chrome menu located in the top right corner).
    Go to the Network tab.
    Select Offline in the Throttling dropdown menu.

Now the application has no access to network interaction.

For applications that do not use the Angular service worker, refreshing now would display Chrome's Internet disconnected page that says "There is no Internet connection".

Install Service Worker
We install the Service Worker by the command:
ng add @angular/pwa

The files are installed or changed are

    Changed:
        app.module.ts
        index.html
        angular.json
        package.json
        package-lock.json
    New Created:
        manifest.webmanifest
        ngsw-config.json
        assets\icons folder

The preceding command completes the following actions:

    Update app.module.ts file:
        Adds the @angular/service-worker package to your project.
        Enables service worker build support in the CLI.
        Imports and registers the service worker in the application module.

    Updates the index.html file:
        Includes a link to add the manifest.webmanifest file
        Adds a meta tag for theme-color

Installs icon files to support the installed Progressive Web App (PWA).


Creates installed icons registered file, called: manifest.webmanifest

Creates the service worker configuration file called ngsw-config.json, which specifies the caching behaviors and other settings.

    Updates the angular.json file, under "build"
        Register file: manifest.webmanifest
        Register file:  ngsw-config.json
        Register Servuce Worker as true

Updates the j.json file: the @angular/service-worker, 14.2.0 is added in dependencies

Install HTTP Server

Globally Installation via npm:
npm install --global http-server

Run the App with Service Worker
Note:
As we noticed the Service Worker installed is only registered to Build environment, not for Dev environment. So, to use Service Worker, we have to build the app.
ng build

Open the server at post 8080 for the project service-workers2:
    by command: http-server -p 8080 -c-1 dist/<project-name>

Run the app at port 8080 with Service Worker:

Select Offline in the Throttling dropdown menu.

With the addition of an Angular service worker, the application behavior changes. On a refresh, the page loads normally. Look at the Network tab to verify that the service worker is active.


NOTE:
Under the "Size" column, the requests state is (ServiceWorker). This means that the resources are not being loaded from the network. Instead, they are being loaded from the service worker's cache.
G - Verify if a service worker is registered #

To verify if a service worker is registered, use developer tools in your favorite browser.

In Firefox and Chromium-based browsers (Microsoft Edge, Google Chrome, or Samsung Internet):

    Open developer tools, then click the Application tab.
    In the left pane, select Service Workers.
    Check that the service worker's script URL appears with the status "Activated". (You'll learn what this status means in the lifecycle section in this chapter). On Firefox the status can be "Running" or "Stopped".


 

H - Summary
We demonstrated how to install Service Worker for solving Angular Caching issue.



AngularJS Hosting Europe - HostForLIFE :: Angular CRUD Using .Net Core Web API

clock November 8, 2022 07:00 by author Peter

This article will explain how to perform CRUD (Create, Read, Update and Delete) operations in Angular. We will see step-by-step instructions about CRUD operations in Angular.
So, let's get started.


Create Angular App
Open Command Prompt -> Navigate to the path where you want to create an angular app project using the below command.
ng new AngularCRUD

Would you like to add Angular routing? - Y (Yes)

Which stylesheet format would you like to use? - CSS

Now, Once the project is created type code . + enter button to open the project in VS Code.

Once the angular app is created we can check in the folder path.


Now, open the terminal and run the project.
ng serve -o

OR

ng serve --open

Adding Service & Adding Components
Now, we need to add service and components to our angular app. Using the below command.

Add Department component
ng g c department

Now, add Department child components

Add/ Edit Department component
ng g c department/add-edit-department

Show Department

ng g c department/show-department

Now, same goes for Employee

Add Employee component
ng g c employee

Now, add Employee child components

Add/ Edit Employee component
ng g c employee/add-edit-employee

Show Employee
ng g c employee/show-employee

Now, add service which will comunicate with Web API
ng g s apiservice

Note
    g - generate
    c - component
    s - service



Adding Bootstrap
Now go to https://getbootstrap.com/ and copy the bootstrap.min.css and bootstrap.bundle.min.js links.

Open index.html page and past .css link in head section and .js after body section.

Register modules
Now, open app.module.ts to register services and module. In app.module we can see all the components are been auto added. Now, we need to add service so we can use in our angular app. Also we need to add HTTP module and other modules which we will require.

    In Providers add Apiservice
    In Imports add HttpClientModule, FormsModule and ReactiveFormsModule

Add Routing
Now, Open app-routing.module.ts file and add Department and Employee in Routs
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';

import { EmployeeComponent } from './employee/employee.component';
import { DepartmentComponent } from './department/department.component';

const routes: Routes = [
  { path: 'employee', component: EmployeeComponent },
  { path: 'department', component: DepartmentComponent }

];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }


Navigating menus for routing
Now, Open app.component.html and add navigations.
<div class="container">
  <h3 class="d-flex justify-content-center">Angular 13 CRUD using .Net Core Web API </h3>
  <nav class="navbar navbar-expand-sm bg-light navbar-dark">
    <ul class="navbar-nav">
      <li class="nav-item">
        <button routerLink="department" class="m-1 btn btn-light btn-outline-primary" Button>Departments</button>
      </li>
      <li class="nav-item">
        <button routerLink="employee" class="m-1 btn btn-light btn-outline-primary" Button>Employees</button>
      </li>
    </ul>
  </nav>
  <router-outlet></router-outlet>
</div>


Adding service, component codes & Filtering & Sorting
Service
Now, Open apiservice.service.ts file and add code.
import { Injectable } from '@angular/core';
import { HttpClient, HttpEvent, HttpHeaders } from '@angular/common/http';
import { Observable } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class ApiserviceService {
  readonly apiUrl = 'http://localhost:50306/api/';
  readonly photoUrl = "http://localhost:50306/Photos/";

  constructor(private http: HttpClient) { }

  // Department
  getDepartmentList(): Observable<any[]> {
    return this.http.get<any[]>(this.apiUrl + 'department/GetDepartment');
  }

  addDepartment(dept: any): Observable<any> {
    const httpOptions = { headers: new HttpHeaders({ 'Content-Type': 'application/json' }) };
    return this.http.post<any>(this.apiUrl + 'department/AddDepartment', dept, httpOptions);
  }

  updateDepartment(dept: any): Observable<any> {
    const httpOptions = { headers: new HttpHeaders({ 'Content-Type': 'application/json' }) };
    return this.http.put<any>(this.apiUrl + 'department/UpdateDepartment/', dept, httpOptions);
  }

  deleteDepartment(deptId: number): Observable<number> {
    const httpOptions = { headers: new HttpHeaders({ 'Content-Type': 'application/json' }) };
    return this.http.delete<number>(this.apiUrl + 'department/DeleteDepartment/' + deptId, httpOptions);
  }

  // Employee
  getEmployeeList(): Observable<any[]> {
    return this.http.get<any[]>(this.apiUrl + 'employee/GetEmployee');
  }

  addEmployee(emp: any): Observable<any> {
    const httpOptions = { headers: new HttpHeaders({ 'Content-Type': 'application/json' }) };
    return this.http.post<any>(this.apiUrl + 'employee/AddEmployee', emp, httpOptions);
  }

  updateEmployee(emp: any): Observable<any> {
    const httpOptions = { headers: new HttpHeaders({ 'Content-Type': 'application/json' }) };
    return this.http.put<any>(this.apiUrl + 'employee/UpdateEmployee/', emp, httpOptions);
  }

  deleteEmployee(empId: number): Observable<number> {
    const httpOptions = { headers: new HttpHeaders({ 'Content-Type': 'application/json' }) };
    return this.http.delete<number>(this.apiUrl + 'employee/DeleteEmployee/' + empId, httpOptions);
  }

  uploadPhoto(photo: any) {
    return this.http.post(this.apiUrl + 'employee/savefile', photo);
  }

  getAllDepartmentNames(): Observable<any[]> {
    return this.http.get<any[]>(this.apiUrl + 'employee/GetAllDepartmentNames');
  }

}


Components
Department Components
Now, Open the department.component.html and add app-show-department selector
<app-show-department></app-show-department>

Now, Open the show-department.component.html and add code.

Note
    I have added filtering and sorting in show-department.
    I have used Boostrap model popup design (https://getbootstrap.com/docs/5.2/components/modal/)
<button type="button" class="btn btn-primary m-2 float-end" data-bs-toggle="modal" data-bs-target="#exampleModal"
  (click)="addClick()">
  Add Department
</button>

<!-- Modal -->
<div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel"
  aria-hidden="true">
  <div class="modal-dialog modal-dialog-centered modal-xl" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="exampleModalLabel">{{ModalTitle}}</h5>
        <button type="button" class="close" data-bs-dismiss="modal" aria-label="Close" (click)="closeClick()">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body">
        <app-add-edit-department [depart]="depart" *ngIf="ActivateAddEditDepartComp">
        </app-add-edit-department>
      </div>
    </div>
  </div>
</div>

<table class="table table-striped">
  <thead>
    <tr>
      <th>
        <div class="d-flex flex-row">
          <input class="form-control m-2" [(ngModel)]="DepartmentIdFilter" (keyup)="FilterFn()" placeholder="Filter">
          <button type="button" class="btn btn-light" (click)="sortResult('DepartmentId',true)">
            <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor"
              class="bi bi-arrow-down-square-fill" viewBox="0 0 16 16">
              <path
                d="M2 0a2 2 0 0 0-2 2v12a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V2a2 2 0 0 0-2-2H2zm6.5 4.5v5.793l2.146-2.147a.5.5 0 0 1 .708.708l-3 3a.5.5 0 0 1-.708 0l-3-3a.5.5 0 1 1 .708-.708L7.5 10.293V4.5a.5.5 0 0 1 1 0z" />
            </svg>
          </button>

          <button type="button" class="btn btn-light" (click)="sortResult('DepartmentId',false)">
            <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor"
              class="bi bi-arrow-up-square-fill" viewBox="0 0 16 16">
              <path
                d="M2 16a2 2 0 0 1-2-2V2a2 2 0 0 1 2-2h12a2 2 0 0 1 2 2v12a2 2 0 0 1-2 2H2zm6.5-4.5V5.707l2.146 2.147a.5.5 0 0 0 .708-.708l-3-3a.5.5 0 0 0-.708 0l-3 3a.5.5 0 1 0 .708.708L7.5 5.707V11.5a.5.5 0 0 0 1 0z" />
            </svg>
          </button>
        </div>
        Department Id
      </th>
      <th>
        <div class="d-flex flex-row">
          <input class="form-control m-2" [(ngModel)]="DepartmentNameFilter" (keyup)="FilterFn()" placeholder="Filter">
          <button type="button" class="btn btn-light" (click)="sortResult('DepartmentName',true)">
            <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor"
              class="bi bi-arrow-down-square-fill" viewBox="0 0 16 16">
              <path
                d="M2 0a2 2 0 0 0-2 2v12a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V2a2 2 0 0 0-2-2H2zm6.5 4.5v5.793l2.146-2.147a.5.5 0 0 1 .708.708l-3 3a.5.5 0 0 1-.708 0l-3-3a.5.5 0 1 1 .708-.708L7.5 10.293V4.5a.5.5 0 0 1 1 0z" />
            </svg>
          </button>

          <button type="button" class="btn btn-light" (click)="sortResult('DepartmentName',false)">
            <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor"
              class="bi bi-arrow-up-square-fill" viewBox="0 0 16 16">
              <path
                d="M2 16a2 2 0 0 1-2-2V2a2 2 0 0 1 2-2h12a2 2 0 0 1 2 2v12a2 2 0 0 1-2 2H2zm6.5-4.5V5.707l2.146 2.147a.5.5 0 0 0 .708-.708l-3-3a.5.5 0 0 0-.708 0l-3 3a.5.5 0 1 0 .708.708L7.5 5.707V11.5a.5.5 0 0 0 1 0z" />
            </svg>
          </button>
        </div>
        Department Name
      </th>
      <th>Options</th>
    </tr>
  </thead>
  <tbody>
    <tr *ngFor="let dataItem of DepartmentList">
      <td>{{dataItem.DepartmentId}}</td>
      <td>{{dataItem.DepartmentName}}</td>
      <td>
        <button type="button" class="btn btn-light mr-1" data-bs-toggle="modal" data-bs-target="#exampleModal"
          (click)="editClick(dataItem)" data-backdrop="static" data-keyboard="false">
          <svg width="1em" height="1em" viewBox="0 0 16 16" class="bi bi-pencil-square" fill="currentColor"
            xmlns="http://www.w3.org/2000/svg">
            <path
              d="M15.502 1.94a.5.5 0 0 1 0 .706L14.459 3.69l-2-2L13.502.646a.5.5 0 0 1 .707 0l1.293 1.293zm-1.75 2.456l-2-2L4.939 9.21a.5.5 0 0 0-.121.196l-.805 2.414a.25.25 0 0 0 .316.316l2.414-.805a.5.5 0 0 0 .196-.12l6.813-6.814z" />
            <path fill-rule="evenodd"
              d="M1 13.5A1.5 1.5 0 0 0 2.5 15h11a1.5 1.5 0 0 0 1.5-1.5v-6a.5.5 0 0 0-1 0v6a.5.5 0 0 1-.5.5h-11a.5.5 0 0 1-.5-.5v-11a.5.5 0 0 1 .5-.5H9a.5.5 0 0 0 0-1H2.5A1.5 1.5 0 0 0 1 2.5v11z" />
          </svg>
        </button>
        <button type="button" class="btn btn-light mr-1" (click)="deleteClick(dataItem)">
          <svg width="1em" height="1em" viewBox="0 0 16 16" class="bi bi-trash-fill" fill="currentColor"
            xmlns="http://www.w3.org/2000/svg">
            <path fill-rule="evenodd"
              d="M2.5 1a1 1 0 0 0-1 1v1a1 1 0 0 0 1 1H3v9a2 2 0 0 0 2 2h6a2 2 0 0 0 2-2V4h.5a1 1 0 0 0 1-1V2a1 1 0 0 0-1-1H10a1 1 0 0 0-1-1H7a1 1 0 0 0-1 1H2.5zm3 4a.5.5 0 0 1 .5.5v7a.5.5 0 0 1-1 0v-7a.5.5 0 0 1 .5-.5zM8 5a.5.5 0 0 1 .5.5v7a.5.5 0 0 1-1 0v-7A.5.5 0 0 1 8 5zm3 .5a.5.5 0 0 0-1 0v7a.5.5 0 0 0 1 0v-7z" />
          </svg>
        </button>
      </td>
    </tr>
  </tbody>
</table>

Now, Open the show-department.component.ts file and add code.
import { Component, OnInit } from '@angular/core';
import { ApiserviceService } from 'src/app/apiservice.service';

@Component({
  selector: 'app-show-department',
  templateUrl: './show-department.component.html',
  styleUrls: ['./show-department.component.css']
})
export class ShowDepartmentComponent implements OnInit {

  constructor(private service: ApiserviceService) { }

  DepartmentList: any = [];
  ModalTitle = "";
  ActivateAddEditDepartComp: boolean = false;
  depart: any;

  DepartmentIdFilter = "";
  DepartmentNameFilter = "";
  DepartmentListWithoutFilter: any = [];

  ngOnInit(): void {
    this.refreshDepList();
  }

  addClick() {
    this.depart = {
      DepartmentId: "0",
      DepartmentName: ""
    }
    this.ModalTitle = "Add Department";
    this.ActivateAddEditDepartComp = true;
  }

  editClick(item: any) {
    this.depart = item;
    this.ModalTitle = "Edit Department";
    this.ActivateAddEditDepartComp = true;
  }

  deleteClick(item: any) {
    if (confirm('Are you sure??')) {
      this.service.deleteDepartment(item.DepartmentId).subscribe(data => {
        alert(data.toString());
        this.refreshDepList();
      })
    }
  }

  closeClick() {
    this.ActivateAddEditDepartComp = false;
    this.refreshDepList();
  }


  refreshDepList() {
    this.service.getDepartmentList().subscribe(data => {
      this.DepartmentList = data;
      this.DepartmentListWithoutFilter = data;
    });
  }

  sortResult(prop: any, asc: any) {
    this.DepartmentList = this.DepartmentListWithoutFilter.sort(function (a: any, b: any) {
      if (asc) {
        return (a[prop] > b[prop]) ? 1 : ((a[prop] < b[prop]) ? -1 : 0);
      }
      else {
        return (b[prop] > a[prop]) ? 1 : ((b[prop] < a[prop]) ? -1 : 0);
      }
    });
  }

  FilterFn() {
    var DepartmentIdFilter = this.DepartmentIdFilter;
    var DepartmentNameFilter = this.DepartmentNameFilter;

    this.DepartmentList = this.DepartmentListWithoutFilter.filter(
      function (el: any) {
        return el.DepartmentId.toString().toLowerCase().includes(
          DepartmentIdFilter.toString().trim().toLowerCase()
        ) &&
          el.DepartmentName.toString().toLowerCase().includes(
            DepartmentNameFilter.toString().trim().toLowerCase())
      }
    );
  }
}


Now, Open the add-edit-department.component.html and add code.
<div class="d-flex flex-row bd-highlight mb-9">
  <div class="p-2 w-100 bd-highlight">

    <div class="input-group mb-12">
      <span class="input-group-text">Department Name</span>
      <input type="text" class="form-control" [(ngModel)]="DepartmentName">
    </div>
  </div>
</div>
<button (click)="addDepartment()" *ngIf="depart.DepartmentId == '0'" class="btn btn-primary">
  Add
</button>

<button (click)="updateDepartment()" *ngIf="depart.DepartmentId !='0'" class="btn btn-primary">
  Update
</button>

Now, Open the add-edit-department.component.ts and add code.
import { Component, OnInit, Input } from '@angular/core';
import { ApiserviceService } from 'src/app/apiservice.service';

@Component({
  selector: 'app-add-edit-department',
  templateUrl: './add-edit-department.component.html',
  styleUrls: ['./add-edit-department.component.css']
})
export class AddEditDepartmentComponent implements OnInit {

  constructor(private service: ApiserviceService) { }

  @Input() depart: any;
  DepartmentId = "";
  DepartmentName = "";

  ngOnInit(): void {

    this.DepartmentId = this.depart.DepartmentId;
    this.DepartmentName = this.depart.DepartmentName;
  }

  addDepartment() {
    var dept = {
      DepartmentId: this.DepartmentId,
      DepartmentName: this.DepartmentName
    };
    this.service.addDepartment(dept).subscribe(res => {
      alert(res.toString());
    });
  }

  updateDepartment() {
    var dept = {
      DepartmentId: this.DepartmentId,
      DepartmentName: this.DepartmentName
    };
    this.service.updateDepartment(dept).subscribe(res => {
      alert(res.toString());
    });
  }
}


Employee Components
Now, Open the employee.component.html and add app-show-employee selector
<app-show-employee></app-show-employee>

Now, Open the show-employee.component.html and add code.
<button type="button" class="btn btn-primary m-2 float-end" data-bs-toggle="modal" data-bs-target="#exampleModal"
  (click)="addClick()">
  Add Employee
</button>

<!-- Modal -->
<div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel"
  aria-hidden="true">
  <div class="modal-dialog modal-dialog-centered modal-xl" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="exampleModalLabel">{{ModalTitle}}</h5>
        <button type="button" class="close" data-bs-dismiss="modal" aria-label="Close" (click)="closeClick()">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body">
        <app-add-edit-employee [emp]="emp" *ngIf="ActivateAddEditEmpComp">
        </app-add-edit-employee>
      </div>
    </div>
  </div>
</div>

<table class="table table-striped">
  <thead>
    <tr>
      <th>Employee Id</th>
      <th>Employee Name</th>
      <th>Department</th>
      <th>Date Of Joining</th>
      <th>Options</th>
    </tr>
  </thead>
  <tbody>
    <tr *ngFor="let dataItem of EmployeeList">
      <td>{{dataItem.EmployeeId}}</td>
      <td>{{dataItem.EmployeeName}}</td>
      <td>{{dataItem.Department}}</td>
      <td>{{dataItem.DateOfJoining}}</td>
      <td>
        <button type="button" class="btn btn-light mr-1" data-bs-toggle="modal" data-bs-target="#exampleModal"
          (click)="editClick(dataItem)" data-backdrop="static" data-keyboard="false">
          <svg width="1em" height="1em" viewBox="0 0 16 16" class="bi bi-pencil-square" fill="currentColor"
            xmlns="http://www.w3.org/2000/svg">
            <path
              d="M15.502 1.94a.5.5 0 0 1 0 .706L14.459 3.69l-2-2L13.502.646a.5.5 0 0 1 .707 0l1.293 1.293zm-1.75 2.456l-2-2L4.939 9.21a.5.5 0 0 0-.121.196l-.805 2.414a.25.25 0 0 0 .316.316l2.414-.805a.5.5 0 0 0 .196-.12l6.813-6.814z" />
            <path fill-rule="evenodd"
              d="M1 13.5A1.5 1.5 0 0 0 2.5 15h11a1.5 1.5 0 0 0 1.5-1.5v-6a.5.5 0 0 0-1 0v6a.5.5 0 0 1-.5.5h-11a.5.5 0 0 1-.5-.5v-11a.5.5 0 0 1 .5-.5H9a.5.5 0 0 0 0-1H2.5A1.5 1.5 0 0 0 1 2.5v11z" />
          </svg>
        </button>
        <button type="button" class="btn btn-light mr-1" (click)="deleteClick(dataItem)">
          <svg width="1em" height="1em" viewBox="0 0 16 16" class="bi bi-trash-fill" fill="currentColor"
            xmlns="http://www.w3.org/2000/svg">
            <path fill-rule="evenodd"
              d="M2.5 1a1 1 0 0 0-1 1v1a1 1 0 0 0 1 1H3v9a2 2 0 0 0 2 2h6a2 2 0 0 0 2-2V4h.5a1 1 0 0 0 1-1V2a1 1 0 0 0-1-1H10a1 1 0 0 0-1-1H7a1 1 0 0 0-1 1H2.5zm3 4a.5.5 0 0 1 .5.5v7a.5.5 0 0 1-1 0v-7a.5.5 0 0 1 .5-.5zM8 5a.5.5 0 0 1 .5.5v7a.5.5 0 0 1-1 0v-7A.5.5 0 0 1 8 5zm3 .5a.5.5 0 0 0-1 0v7a.5.5 0 0 0 1 0v-7z" />
          </svg>
        </button>
      </td>
    </tr>
  </tbody>
</table>

Markup

Now, Open the show-employee.component.ts and add code.

import { Component, OnInit } from '@angular/core';
import { ApiserviceService } from 'src/app/apiservice.service';

@Component({
  selector: 'app-show-employee',
  templateUrl: './show-employee.component.html',
  styleUrls: ['./show-employee.component.css']
})
export class ShowEmployeeComponent implements OnInit {

  constructor(private service: ApiserviceService) { }

  EmployeeList: any = [];
  ModalTitle = "";
  ActivateAddEditEmpComp: boolean = false;
  emp: any;

  ngOnInit(): void {
    this.refreshEmpList();
  }

  addClick() {
    this.emp = {
      EmployeeId: "0",
      EmployeeName: "",
      Department: "",
      DateOfJoining: "",
      PhotoFileName: "anonymous.png"
    }
    this.ModalTitle = "Add Employee";
    this.ActivateAddEditEmpComp = true;
  }

  editClick(item: any) {
    this.emp = item;
    this.ModalTitle = "Edit Employee";
    this.ActivateAddEditEmpComp = true;
  }

  deleteClick(item: any) {
    if (confirm('Are you sure??')) {
      this.service.deleteEmployee(item.EmployeeId).subscribe(data => {
        alert(data.toString());
        this.refreshEmpList();
      })
    }
  }

  closeClick() {
    this.ActivateAddEditEmpComp = false;
    this.refreshEmpList();
  }

  refreshEmpList() {
    this.service.getEmployeeList().subscribe(data => {
      this.EmployeeList = data;
    });
  }
}


Now, Open the add-edit-employee.component.html and add code.
Note: I have added Photo upload code.
<div class="d-flex flex-row bd-highlight mb-3">
  <div class="p-2 w-50 bd-highlight">
    <div class="input-group mb-3">
      <span class="input-group-text">Name</span>
      <input type="text" class="form-control" [(ngModel)]="EmployeeName">
    </div>
    <div class="input-group mb-3">
      <span class="input-group-text">Department</span>
      <select class="form-select" [(ngModel)]="Department">
        <option>--Select--</option>
        <option *ngFor="let dep of DepartmentList">
          {{dep.DepartmentName}}
        </option>
      </select>
    </div>
    <div class="input-group mb-3">
      <span class="input-group-text">DOJ</span>
      <input type="date" class="form-control" [(ngModel)]="DateOfJoining">
    </div>
  </div>
  <div class="p-2 w-50 bd-highlight">
    <img width="250px" height="250px" [src]="PhotoFilePath" />
    <input class="m-2" type="file" (change)="uploadPhoto($event)">
  </div>
</div>
<button type="button" (click)="addEmployee()" *ngIf="emp.EmployeeId=='0'" class="btn btn-primary">
  Create
</button>

<button type="button" (click)="updateEmployee()" *ngIf="emp.EmployeeId!='0'" class="btn btn-primary">
  Update
</button>

Now, Open the add-edit-employee.component.ts and add code.
import { Component, Input, OnInit } from '@angular/core';
import { ApiserviceService } from 'src/app/apiservice.service';

@Component({
  selector: 'app-add-edit-employee',
  templateUrl: './add-edit-employee.component.html',
  styleUrls: ['./add-edit-employee.component.css']
})
export class AddEditEmployeeComponent implements OnInit {

  constructor(private service: ApiserviceService) { }
  @Input() emp: any;
  EmployeeId = "";
  EmployeeName = "";
  Department = "";
  DateOfJoining = "";
  PhotoFileName = "";
  PhotoFilePath = "";
  DepartmentList: any = [];


  ngOnInit(): void {
    this.loadEmployeeList();
  }

  loadEmployeeList() {

    this.service.getAllDepartmentNames().subscribe((data: any) => {
      this.DepartmentList = data;

      this.EmployeeId = this.emp.EmployeeId;
      this.EmployeeName = this.emp.EmployeeName;
      this.Department = this.emp.Department;
      this.DateOfJoining = this.emp.DateOfJoining;
      this.PhotoFileName = this.emp.PhotoFileName;
      this.PhotoFilePath = this.service.photoUrl + this.PhotoFileName;
    });
  }

  addEmployee() {
    var val = {
      EmployeeId: this.EmployeeId,
      EmployeeName: this.EmployeeName,
      Department: this.Department,
      DateOfJoining: this.DateOfJoining,
      PhotoFileName: this.PhotoFileName
    };

    this.service.addEmployee(val).subscribe(res => {
      alert(res.toString());
    });
  }

  updateEmployee() {
    var val = {
      EmployeeId: this.EmployeeId,
      EmployeeName: this.EmployeeName,
      Department: this.Department,
      DateOfJoining: this.DateOfJoining,
      PhotoFileName: this.PhotoFileName
    };

    this.service.updateEmployee(val).subscribe(res => {
      alert(res.toString());
    });
  }


  uploadPhoto(event: any) {
    var file = event.target.files[0];
    const formData: FormData = new FormData();
    formData.append('file', file, file.name);

    this.service.uploadPhoto(formData).subscribe((data: any) => {
      this.PhotoFileName = data.toString();
      this.PhotoFilePath = this.service.photoUrl + this.PhotoFileName;
    })
  }
}


Now Run the Project using ng serve -o OR ng serve --open

Department

Add Department

Edit Department



Delete Department

Employee

Add Employee

Edit Employee

Delete Employee

Filtering & Sorting

Filtering & Sorting

 



European Visual Studio 2022 Hosting - HostForLIFE :: Running Tasks In Parallel

clock November 4, 2022 08:12 by author Peter

Today we will see how we can run different tasks in parallel in C#. With the current hardware strength, we have machines with multiple processors. Hence, we certainly have the ability to utilize these and run our tasks in parallel to improve performance. But are we really doing this. Let us look at some sample code, which will let us do this. This can serve as a framework on which this methodology can be enhanced.
Creating the solution and adding the code

Let us create a C# console application in Visual Studio 2022 Community edition. Once created, add the below code.

// Create a generic list to hold all our tasks
var allTasks = new List < Task > ();
// Add your tasks to this generic list
// Here we simply add the same task with different input parameters
for (var i = 0; i <= 10; i++) {
    allTasks.Add(RunTaskAsync(i));
}
// Run all tasks in parallel and wait for results from all
await Task.WhenAll(allTasks);
// Collect return values from all tasks which have now executed
var returnValues = new List < int > ();
foreach(var task in allTasks) {
    var returnValue = ((Task < int > ) task).Result;
    returnValues.Add(returnValue);
}
// Display returned values on console
foreach(var returnValue in returnValues) {
    Console.WriteLine(returnValue);
}
// The task we want to run
async Task < int > RunTaskAsync(int val) {
    return await Task.FromResult(val * val);
}

Here you see that we simply create a list of tasks and run them in parallel using the Task.WhenAll method. Then, we collect the results and handle them accordingly.


In this article, we looked at how we can execute tasks in parallel in .NET 6. I created a simple framework where we define the tasks and then run them after adding to a generic list. Once completed, we extract the results, and these can be used as required.



AngularJS Hosting Europe - HostForLIFE :: Featured Module in Angular

clock November 1, 2022 08:44 by author Peter

In this article, we are going to discuss the most important feature in the Angular Framework called “Featured Modules”. This article can be accessed by beginners, intermediates, and professionals.


Featured Module
Modules are the most important part of the Angular Application.
Modules are the place where we are grouping components, directives, services, and pipes.
app.module.ts module is a root module of the Angular Application.

Whenever we create a new application, the root module will be added by default.
Let's see the below image to understand the problem first,

Suppose we have a large angular application with thousands of components, directives, services, pipes, etc., and all are maintained in the Root module (“app.module.ts”). In such a scenario, the Root module becomes very mashie and non-maintainable.

What will you do to solve this problem? You will break the root module into small modules and separate it right? So that separated small module is called a “Featured module” in Angular.

Let’s see the below image for more understanding,


In the above image, we have separated “module1”,” module2” and “module3” from the Root module. Each module content component of that module. Eg. Module1 has Component1

Now we have a basic idea of the Featured module, now we will see how many types of featured modules are available in the angular application.

Types of Featured Modules
    Domain - It is based on the application navigation eg. Emp or customer features modules etc
    Routed - All Lazy loaded modules.
    Routing - Routing and its related functionality like Route guard.
    Service - This is related to API request – Response.
    Widget - Widget-related modules which may contain utility, pipes, directives, etc.

Let’s discuss a few important advantages before we will discuss an example of a featured module.

Advantages of the Featured Module
    Code Maintainability
    Scalability
    Lazy Loading
    Abstraction
    Code separation

Now we will create a new angular application and learn feature modules,

Step 1
Create a new Angular Application “ProductDemo”.
ng new "FeaturedDemo"

Step 2
Add two modules “ProductModule” and “PriceModule” components.
ng g m "Product\Product.module"

Above command will create product folder and product module.
Now we will create new module for price. We will use the below command for the same.

ng g m price\price

Price folder and price module will be created.

Step 3 - Create two components for “Product” and “price”.
Now we will add two components for product and price.
ng g c product\product

Product components will be created. Now we will create price component.
ng g c price\price

Price component will be created and added in the price folder.


Step 4 - Configure “ProductModule” and “PriceModule” in the app.module.ts file.
Now we will configure newly added modules in the app.module.ts file.
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { PriceModule } from './price/price/price.module';
import { ProductModule } from './product/product/product.module';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    ProductModule,
    PriceModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }


We have added “ProductModule” and “PriceModule” in the imports array and imported references in the app.module.ts file.

app.module.ts file has “BrowserModule” but other modules have “CommonModule” for common functionalities.

Step 5
Let's see “ProductModule” and “PriceModule”.
Product Module
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { ProductComponent } from './product.component';

@NgModule({
  declarations: [
    ProductComponent
  ],
  imports: [
    CommonModule
  ],
  exports:[ProductComponent]
})
export class ProductModule { }


We need to export ProductComponent to export the component. Need to add components to the exports array.

Price Module
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { PriceComponent } from './price.component';

@NgModule({
  declarations: [
    PriceComponent
  ],
  imports: [
    CommonModule
  ],
  exports:[PriceComponent]
})
export class PriceModule { }


Step 6
Add the below code in the “app.component.html” file.
<router-outlet></router-outlet>
<app-price></app-price>
<app-product></app-product>


Now we will execute the angular application and see the results.


That's all for this article. Hope you enjoyed it.



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