Full Trust European Hosting

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

Node.js Hosting - HostForLIFE :: Integrate Open API (Swagger) With Node And Express

clock May 18, 2021 12:41 by author Peter
This article will explain how to integrate swagger (Open API) with Node & express. Swagger makes it very easy for a backend developer to document, test, and explain API endpoints he/she's been working on a front-end developer or anyone looking to consume those endpoints.

Setup
Before we get started into this we should have few things installed in our machine.
    Visual Studio Code -> Visual Studio Code
    Node.js -> Node.js

Source Code - Git Code
Required Packages
npm init
npm install swagger-jsdoc swagger-ui-express express nodemon

 
Express - For Server
 
Swagger - For API's Documentation in UI
 
Nodemon - will use this to restart our server automatically whenever we make changes to our files.
 
After installing the required packages let's add the new file to set up the Swagger configuration and as well adding the API endpoints in Node
 
Structure of the Project

Setting up the swagger
Swagger UI can be set up for both the front end & backend as well. Since this article is about the Swagger with Node.js. I will be setting up the the swagger in Node.js express app only. you can explore the other options here
 
In your api.js
    //Swagger Configuration  
    const swaggerOptions = {  
        swaggerDefinition: {  
            info: {  
                title:'Employee API',  
                version:'1.0.0'  
            }  
        },  
        apis:['api.js'],  
    }  
    const swaggerDocs = swaggerJSDoc(swaggerOptions);  
    app.use('/api-docs',swaggerUI.serve,swaggerUI.setup(swaggerDocs));  

       
After integrating the swagger setup lets define the swagger endpoint with description and response codes in a particular format so that we can able to access those API's inside the swagger after running in the browser
 
Add Swagger Before Each End Point
    /**
     * @swagger
     * /Employees:
     *   get:
     *     description: Get all Employee
     *     responses:  
     *       200:
     *         description: Success  
     *   
     */  
    app.get('/Employees',(req,res)=>{  
        res.send([  
            {  
                id:1, Name:'Jk'  
            },  
            {  
                id:2,Name:'Jay'  
            }  
        ])  
    });  

For the demo purpose, I have added four API's (Get, Post, Put, Delete) added the swagger setup for the remaining endpoints as well
 
Final api.js
    const express = require('express');  
    const swaggerJSDoc = require('swagger-jsdoc');  
    const swaggerUI = require('swagger-ui-express');  
      
    const app = express();  
      
    app.listen(5000,()=>console.log("listening on 5000"));  
      
    //Swagger Configuration  
    const swaggerOptions = {  
        swaggerDefinition: {  
            info: {  
                title:'Employee API',  
                version:'1.0.0'  
            }  
        },  
        apis:['api.js'],  
    }  
    const swaggerDocs = swaggerJSDoc(swaggerOptions);  
    app.use('/api-docs',swaggerUI.serve,swaggerUI.setup(swaggerDocs));  
       
    /**
     * @swagger
     * /Employees:
     *   get:
     *     description: Get all Employee
     *     responses:  
     *       200:
     *         description: Success  
     *   
     */  
    app.get('/Employees',(req,res)=>{  
        res.send([  
            {  
                id:1, Name:'Jk'  
            },  
            {  
                id:2,Name:'Jay'  
            }  
        ])  
    });  
      
    /**
     * @swagger
     * /Employees:
     *   post:
     *     description: Create an Employee
     *     parameters:
     *     - name: EmployeeName
     *       description: Create an new employee
     *       in: formData
     *       required: true
     *       type: String
     *     responses:  
     *       201:
     *         description: Created  
     *   
     */  
     app.post('/Employees',(req,res)=>{  
       res.status(201).send();  
    });  
    /**
     * @swagger
     * /Employees:
     *   put:
     *     description: Create an Employee
     *     parameters:
     *     - name: EmployeeName
     *       description: Create an new employee
     *       in: formData
     *       required: true
     *       type: String
     *     responses:  
     *       201:
     *         description: Created  
     *   
     */  
     app.put('/Employees',(req,res)=>{  
        res.status(201).send();  
     });  
     /**
     * @swagger
     * /Employees:
     *   delete:
     *     description: Create an Employee
     *     parameters:
     *     - name: EmployeeName
     *       description: Create an new employee
     *       in: formData
     *       required: true
     *       type: String
     *     responses:  
     *       201:
     *         description: Created  
     *   
     */  
      app.delete('/Employees',(req,res)=>{  
        res.status(201).send();  
     });  


Run the URL in the browser
Now you can do the npm start in the terminal to your app and it will navigate to the browser we have to add the /api-docs at the end of the URL so that i will navigate to the swagger which we have configured and you will see the Swagger UI based on your generated swagger.json.
 
Terminal

Swagger


Testing the API with Swagger



Node.js Hosting - HostForLIFE :: Integrate Open API (Swagger) With Node And Express

clock May 18, 2021 12:41 by author Peter
This article will explain how to integrate swagger (Open API) with Node & express. Swagger makes it very easy for a backend developer to document, test, and explain API endpoints he/she's been working on a front-end developer or anyone looking to consume those endpoints.

Setup
Before we get started into this we should have few things installed in our machine.
    Visual Studio Code -> Visual Studio Code
    Node.js -> Node.js

Source Code - Git Code
Required Packages
npm init
npm install swagger-jsdoc swagger-ui-express express nodemon

 
Express - For Server
 
Swagger - For API's Documentation in UI
 
Nodemon - will use this to restart our server automatically whenever we make changes to our files.
 
After installing the required packages let's add the new file to set up the Swagger configuration and as well adding the API endpoints in Node
 
Structure of the Project

Setting up the swagger
Swagger UI can be set up for both the front end & backend as well. Since this article is about the Swagger with Node.js. I will be setting up the the swagger in Node.js express app only. you can explore the other options here
 
In your api.js
    //Swagger Configuration  
    const swaggerOptions = {  
        swaggerDefinition: {  
            info: {  
                title:'Employee API',  
                version:'1.0.0'  
            }  
        },  
        apis:['api.js'],  
    }  
    const swaggerDocs = swaggerJSDoc(swaggerOptions);  
    app.use('/api-docs',swaggerUI.serve,swaggerUI.setup(swaggerDocs));  

       
After integrating the swagger setup lets define the swagger endpoint with description and response codes in a particular format so that we can able to access those API's inside the swagger after running in the browser
 
Add Swagger Before Each End Point
    /**
     * @swagger
     * /Employees:
     *   get:
     *     description: Get all Employee
     *     responses:  
     *       200:
     *         description: Success  
     *   
     */  
    app.get('/Employees',(req,res)=>{  
        res.send([  
            {  
                id:1, Name:'Jk'  
            },  
            {  
                id:2,Name:'Jay'  
            }  
        ])  
    });  

For the demo purpose, I have added four API's (Get, Post, Put, Delete) added the swagger setup for the remaining endpoints as well
 
Final api.js
    const express = require('express');  
    const swaggerJSDoc = require('swagger-jsdoc');  
    const swaggerUI = require('swagger-ui-express');  
      
    const app = express();  
      
    app.listen(5000,()=>console.log("listening on 5000"));  
      
    //Swagger Configuration  
    const swaggerOptions = {  
        swaggerDefinition: {  
            info: {  
                title:'Employee API',  
                version:'1.0.0'  
            }  
        },  
        apis:['api.js'],  
    }  
    const swaggerDocs = swaggerJSDoc(swaggerOptions);  
    app.use('/api-docs',swaggerUI.serve,swaggerUI.setup(swaggerDocs));  
       
    /**
     * @swagger
     * /Employees:
     *   get:
     *     description: Get all Employee
     *     responses:  
     *       200:
     *         description: Success  
     *   
     */  
    app.get('/Employees',(req,res)=>{  
        res.send([  
            {  
                id:1, Name:'Jk'  
            },  
            {  
                id:2,Name:'Jay'  
            }  
        ])  
    });  
      
    /**
     * @swagger
     * /Employees:
     *   post:
     *     description: Create an Employee
     *     parameters:
     *     - name: EmployeeName
     *       description: Create an new employee
     *       in: formData
     *       required: true
     *       type: String
     *     responses:  
     *       201:
     *         description: Created  
     *   
     */  
     app.post('/Employees',(req,res)=>{  
       res.status(201).send();  
    });  
    /**
     * @swagger
     * /Employees:
     *   put:
     *     description: Create an Employee
     *     parameters:
     *     - name: EmployeeName
     *       description: Create an new employee
     *       in: formData
     *       required: true
     *       type: String
     *     responses:  
     *       201:
     *         description: Created  
     *   
     */  
     app.put('/Employees',(req,res)=>{  
        res.status(201).send();  
     });  
     /**
     * @swagger
     * /Employees:
     *   delete:
     *     description: Create an Employee
     *     parameters:
     *     - name: EmployeeName
     *       description: Create an new employee
     *       in: formData
     *       required: true
     *       type: String
     *     responses:  
     *       201:
     *         description: Created  
     *   
     */  
      app.delete('/Employees',(req,res)=>{  
        res.status(201).send();  
     });  


Run the URL in the browser
Now you can do the npm start in the terminal to your app and it will navigate to the browser we have to add the /api-docs at the end of the URL so that i will navigate to the swagger which we have configured and you will see the Swagger UI based on your generated swagger.json.
 
Terminal

Swagger


Testing the API with Swagger



AngularJS Hosting Europe - HostForLIFE.eu :: Angular 11 Spinner/Loader With Out Any Third Party Library/Package

clock May 4, 2021 06:38 by author Peter

In this article, we will learn how we can show the Loader in Angular 11 without using any third-party spinner. We are using CSS to build an animated Spinner.

 

Step 1
Create an Angular project by using the following command
 
ng new Angularloader
 
Step 2
Open this project in Visual Studio Code and install bootstrap by using the following command
npm install bootstrap --save
 
Step 3

Jquery is needed to run bootstrap click events. So install jquery using below command
npm install jquery --save
 
Declare Jquery before bootstrap.
 
Otherwise, you will get the below error
Uncaught TypeError: Bootstrap's JavaScript requires jQuery. jQuery must be included before Bootstrap's JavaScript.

    "scripts": [  
    "node_modules/jquery/dist/jquery.js",  
    "node_modules/bootstrap/dist/js/bootstrap.js"]   


Now Bootstrap will work fine.
 
Step 4
    Let's start the main goal of the articlet to show spinner.
    Create one new component using Ng g c popuploader
    In popuploader.component.css file paste below lines of code to create animated spinner
        .loadWrapper {  
            background: rgba(0, 0, 0, 0.3);  
            width: 100 % ;  
            height: 100 % ;  
            position: fixed;  
            top: 0 px;  
            left: 0 px;  
            z - index: 99999;  
        }.loader {  
            border: 5 px solid #f3f3f3; /* Light grey */  
            border - top: 5 px solid #3d3e3f; /* gray */  
           position: absolute;  
           left: 50%;  
           top: 50%;  
           border-radius: 50%;  
           width: 50px;  
           height: 50px;  
           animation: spin 2s linear infinite;  
        }  
        @keyframes spin {  
           0% { transform: rotate(0deg); }  
           100% { transform: rotate(360deg); }  
        }  


Step 5

We will create one simple data service which will load data into table..For that I have created student.service.ts file
 
In StudentService write the below line of code.
    import {  
        Injectable  
    } from '@angular/core';  
    @Injectable({  
        providedIn: 'root'  
    })  
    export class StudentService {  
        students = [{  
            "id": 1001,  
            "name": "Peter",  
            "marks": 90  
        }, {  
            "id": 1002,  
            "name": "Scott",  
            "marks": 80  
        }, {  
            "id": 1003,  
            "name": "Mark",  
            "marks": 70  
        }, {  
            "id": 1004,  
            "name": "Tom",  
            "marks": 85  
        }, {  
            "id": 1005,  
            "name": "Alice",  
            "marks": 60  
        }];  
        constructor() {}  
        getStudents() {  
            return this.students;  
        }  
    }   


Step 6

Lets call this service in our popuploader component
    import {  
        Component,  
        OnInit  
    } from '@angular/core';  
    import {  
        StudentService  
    } from '../student.service';  
    @Component({  
        selector: 'app-popuploader',  
        templateUrl: './popuploader.component.html',  
        styleUrls: ['./popuploader.component.css']  
    })  
    export class PopuploaderComponent implements OnInit {  
        public loading = true;  
        public studentList: any[];  
        constructor(private stnService: StudentService) {}  
        ngOnInit() {  
            this.loading = true;  
            setTimeout(() => {  
                /** spinner ends after 5 seconds */  
                this.studentList = this.stnService.getStudents();  
                this.loading = false;  
            }, 5000);  
        }  
    }   


Step 7
You can seen I have created one variable loading this will decide whether loading spinner should show or not.
 
Before loading the data into variable I set as true .then the spinner will show.

    Then I given some time to show the spinner.
    After that I set to False to hide the spinner. As I mentioned no need of timer when API. Call.
    Once API call over set it as false.

Step 6

 
Let's create a Model dialog with the help of Bootstrap and call the data & spinner.
    <!-- Button to Open the Modal -->  
    <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#myModal">  
    Open modal  
    </button>  
    <!-- The Modal -->  
    <div class="modal" id="myModal">  
        <div class="modal-dialog">  
            <div class="modal-content">  
                <!-- Modal Header -->  
                <div class="modal-header">  
                    <h4 class="modal-title">popuploader</h4>  
                    <button type="button" class="close" data-dismiss="modal">×</button>  
                </div>  
                <!-- Modal body -->  
                <div class="modal-body">  
                    <div *ngIf="loading else loaded" class="loader"></div>  
                    <!-- Modal footer -->  
                    <div class="modal-footer">  
                        <button type="button" class="btn btn-danger" data-dismiss="modal">Close</button>  
                    </div>  
                </div>  
            </div>  
        </div>  
        <ng-template #loaded>  
            <p>student works!</p>  
            <table class="table">  
                <thead>  
                    <td>  
                         ID  
                      </td>  
                    <td>  
                         Name  
                      </td>  
                    <td>  
                      Marks  
                   </td>  
                </thead>  
                <tbody>  
                    <tr *ngFor="let std of studentList">  
                        <td>{{std.id}}</td>  
                        <td>{{std.name}}</td>  
                        <td>{{std.marks}}</td>  
                    </tr>  
                </tbody>  
            </table>  
        </ng-template>
 

In about code, we have created one button. That button will trigger the popup.
 
We should call the popup using the data-target attribute data-target="#myModal".
 
Mymodel is the id of model dialog.
 
In our process, I will load the spinner with the timer. In real-life cases, no timer is needed.
 
I have created ng template and I have loaded the data there.

    <ng-template #loaded>  
    …..  
    </ng-template> 
 

I gave the name of the template as loaded.
 
To show the templete I have set condition as,

    <div *ngIf="loading else loaded" class="loader">  
    </div>  

SO if loading variable is true then the loaded template will show with loader css.
 
If false then loader CSS will disappear
 
Now type ng serve to ( use angular CLI ) run the project.



AngularJS Hosting Europe - HostForLIFE.eu :: Syntax Highlighting In Markdown For Blog made with Scully

clock April 27, 2021 07:41 by author Peter

In many technical blogs, we use code snippets to share code with readers and explain the implementation. In a previous article, we have seen how to create a blogging site with Angular and Scully. If you are creating a technical blogging site you might also need to add code snippets to your blog. So In this article, we will see how to add a code block with syntax highlighting feature. 


Adding Code Block in Markdown file
In the markdown file, we can add a code block with the following syntax,
    ```    
    --- CODE BLOCK ---    
    ```  


Optionally you can also set the language as
    ```language  
    --- CODE BLOCK ---  
    ```  


 language can be javascript, bash, etc.
 
For Example,
Add the following sample code block in  getting-started-with-scully.md file
    ```javascript  
    import { ScullyConfig } from '@scullyio/scully';  
    export const config: ScullyConfig = {  
      projectRoot: "./src",  
      projectName: "portfolio",  
      outDir: './dist/static',  
      routes: {  
        '/blog/:slug': {  
          type: 'contentFolder',  
          slug: {  
            folder: "./blog"  
          }  
        },  
      }  
    };  

    ```  
Now take a Scully build and serve the Scully static server  with npm run scully && npm run scully:serve

As you can see it generates the code block with preformatted code, but it doesn't have any syntax highlighting.
 
Adding Syntax Highlighting Feature
Scully has a markdown plugin, which transforms markdown files to HTML files at the time of Scully build. This plugin provides an option to enable syntax highlighting at the time of Scully build.

As you can see below, We will use the setPluginConfig function to configure plugins. set enableSyntaxHighlighting to true in the markdown plugin to enable syntax highlighting.

    // scully.[projectName].config.ts  
      
    import { ScullyConfig, setPluginConfig } from '@scullyio/scully';  
      
    setPluginConfig('md', { enableSyntaxHighlighting : true});  
      
    export const config: ScullyConfig = {  
      projectRoot: "./src",  
      projectName: "portfolio",  
      outDir: './dist/static',  
      routes: {  
        '/blog/:slug': {  
          type: 'contentFolder',  
          slug: {  
            folder: "./blog"  
          }  
        },  
      }  
    };  


Scully internally uses Prism.js for code block syntax highlighting. We need to import its styles in our styles.css file as below
    /* include CSS for prism toolbar */  
    @import '~prismjs/plugins/toolbar/prism-toolbar.css';  
    /* check node_modules/prismjs/themes/ for the available themes */  
    @import '~prismjs/themes/prism-tomorrow';  


Great !!! We are done with the implementation, Now take and build and test it.
 
Final Output

Take a new build of the angular app, as we have made changes in styles.css, then take a Scully build and start the static server using the following commands

    ng build --prod  
    npm run scully  
    npm run scully:serve  


Now check the blog in which you have added code snippets / code blocks :



European Visual Studio 2017 Hosting - HostForLIFE.eu :: Enabling Preview Features In Visual Studio 2019

clock April 21, 2021 08:38 by author Peter

By default, Visual Studio doesn’t enable preview feature selection in Visual Studio 2019. Say you have .Net 5.0 installed on your machine and you are creating a new Console Application. After creating the application, you will notice that, although .Net 5.0 is installed, the application still picks up the .Net Core 3.1 as a default framework. In fact, the application didn’t ask for framework selection too.

So, how can we select the framework while creating an application itself? For doing this, we need to enable Preview Features in Visual Studio by going to the Options menu as shown below,



mySQL Hosting Europe - HostForLIFEASP.NET :: Character Sets And Collations in MySQL

clock April 16, 2021 08:23 by author Peter

In this tutorial, I am going to explain about Character Sets and Collations in MySQL with examples. This article will cover the following topics. Let’s see.

CHARACTER SETS
A character set is a set of symbols and their encoding. It is a set of behavior; it is used for analyzing the characters in a character set. MySQL also includes the character set support in which it prepares for storing data by using a collection of character sets and it also performs the estimation according to a variety of collations. MySQL chooses the database character set and the collation of the database and it can become the point on character sets at the server, database, table, and at the column level. Each character set contains one or more collations that determine a set of character comparison rules within the character set.
 
Character sets have developed through history but that history is beyond the bounds of this article. During this time the Unicode standard developed and achieves identification of the older character sets which are closed throughout. It is important to be conscious of the difference between Unicode and local character sets.
MySQL supports various character sets that allow almost any character to be stored in a string. Below is the CHARACTER SET Statement, by which the user can get all available character sets in the MySQL database.
SHOW CHARACTER SET;

In the above-given character set, it must have one collation. And, the given character set, it has several collations. To the collations list for a given character set, it includes all variable character sets by using the following statement.
 
In MySQL, you can use the "SHOW COLLATION" statement to get all the collations for a given character set.
 
Syntax
SHOW COLLATION LIKE 'character_set_name%';
 
Example

    SHOW COLLATION LIKE 'latin1%';

Setting Character Sets and Collations at Database Level
 
When you create a database, you can specify the default character set and the collation for a database. But, if you don’t specify it, MySQL will use the default character sets and collation.
 
Syntax
CREATE DATABASE <database_name>
CHARACTER SET <character_set_name>
COLLATE <collation_name>

Setting Character Sets and Collations at the Table Level
 
When you create a table, you can also specify the default character set and the collation for a table. But, if you don’t specify it, MySQL will use the default character sets and collation.
 
Syntax
CREATE TABLE <table_name> (
<column_name1> datatype,
<column_name2> datatype, …
<column_nameN> datatype

)
CHARACTER SET <character_set_name>
COLLATE <collation_name>;
 

For Example
 
1) Define the column and table with the collate and its character
 
Example - In the following example we have to define the column and table with the collation and its character.

CREATE TABLE test(  
  C_ID INT,  
  C_Name VARCHAR(50)  
)  
DEFAULT CHARACTER SET LATIN1  
COLLATE latin1_general_ci;  
  
DESCRIBE TEST; 

 

2) Setting Collation and Character Set a Table Level
 
Example - Here we have to define the table has a table character set and a table collation. Create a table “RACEWINNER” with R_ID and First_name column and set the collation.

    Create table RACEWINNER(  
      R_ID INT,  
      First_name varchar(30)  
    ) CHARACTER SET latin1  
    COLLATE latin1_danish_ci;  
      
    DESCRIBE RACEWINNER;



3) Setting Collation and character set at Column Level
 
Example - In this example create a table "Company" and show the collation on the column character set.

    Create table Company(  
      C_column varchar(50) CHARACTER SET latin1 COLLATE latin1_german1_ci  
    );  
      
    DESCRIBE Company;

HostForLIFE.eu SQL Server 2019 Hosting
HostForLIFE.eu 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 customers from around the globe, spread across every continent. We serve the hosting needs of the business and professional, government and nonprofit, entertainment and personal use market segments.



AngularJS Hosting Europe - HostForLIFE.eu :: How To Install And Use jQuery In Angular?

clock March 30, 2021 07:12 by author Peter

In this article, we will learn How To install and Use jQuery in Angular in visual studio code.
 

Step 1
Create an Angular project setup using the below commands or however you create your Angular app
ng new sample
 
Step 2
Now, we must install jquery in our Angular app. Open a new terminal and run the below command.
npm install jquery — save

Step 3
In jQuery module, jquery.min.js under ‘dist’ folder is not public. To assign jQuery global in angular-cli.json file and pass reference to the jQuery file path.
 
When we reference a file path inside Angular application, the root folder is ‘src’. However, jQuery library is inside node_modules. We need to define the correct path in .angular-cli.json file

../node_modules/jquery/dist/jquery.min.js
 
now we need to import our jquery script file as like bellow,
 
Angular.json

    {  
      "$schema": "./node_modules/@angular/cli/lib/config/schema.json",  
      "version": 1,  
      "newProjectRoot": "projects",  
      "projects": {  
        "sample": {  
          "projectType": "application",  
          "schematics": {  
            "@schematics/angular:component": {  
              "style": "scss"  
            },  
            "@schematics/angular:application": {  
              "strict": true  
            }  
          },  
          "root": "",  
          "sourceRoot": "src",  
          "prefix": "app",  
          "architect": {  
            "build": {  
              "builder": "@angular-devkit/build-angular:browser",  
              "options": {  
                "outputPath": "dist/sample",  
                "index": "src/index.html",  
                "main": "src/main.ts",  
                "polyfills": "src/polyfills.ts",  
                "tsConfig": "tsconfig.app.json",  
                "aot": true,  
                "assets": [  
                  "src/favicon.ico",  
                  "src/assets"  
                ],  
                "styles": [  
                  "src/styles.scss"  
                ],  
                "scripts": [  
                  "../node_modules/jquery/dist/jquery.min.js"  
                ]  
              },  
              "configurations": {  
                "production": {  
                  "fileReplacements": [  
                    {  
                      "replace": "src/environments/environment.ts",  
                      "with": "src/environments/environment.prod.ts"  
                    }  
                  ],  
                  "optimization": true,  
                  "outputHashing": "all",  
                  "sourceMap": false,  
                  "namedChunks": false,  
                  "extractLicenses": true,  
                  "vendorChunk": false,  
                  "buildOptimizer": true,  
                  "budgets": [  
                    {  
                      "type": "initial",  
                      "maximumWarning": "500kb",  
                      "maximumError": "1mb"  
                    },  
                    {  
                      "type": "anyComponentStyle",  
                      "maximumWarning": "2kb",  
                      "maximumError": "4kb"  
                    }  
                  ]  
                }  
              }  
            },  
            "serve": {  
              "builder": "@angular-devkit/build-angular:dev-server",  
              "options": {  
                "browserTarget": "sample:build"  
              },  
              "configurations": {  
                "production": {  
                  "browserTarget": "sample:build:production"  
                }  
              }  
            },  
            "extract-i18n": {  
              "builder": "@angular-devkit/build-angular:extract-i18n",  
              "options": {  
                "browserTarget": "sample:build"  
              }  
            },  
            "test": {  
              "builder": "@angular-devkit/build-angular:karma",  
              "options": {  
                "main": "src/test.ts",  
                "polyfills": "src/polyfills.ts",  
                "tsConfig": "tsconfig.spec.json",  
                "karmaConfig": "karma.conf.js",  
                "assets": [  
                  "src/favicon.ico",  
                  "src/assets"  
                ],  
                "styles": [  
                  "src/styles.scss"  
                ],  
                "scripts": []  
              }  
            },  
            "lint": {  
              "builder": "@angular-devkit/build-angular:tslint",  
              "options": {  
                "tsConfig": [  
                  "tsconfig.app.json",  
                  "tsconfig.spec.json",  
                  "e2e/tsconfig.json"  
                ],  
                "exclude": [  
                  "**/node_modules/**"  
                ]  
              }  
            },  
            "e2e": {  
              "builder": "@angular-devkit/build-angular:protractor",  
              "options": {  
                "protractorConfig": "e2e/protractor.conf.js",  
                "devServerTarget": "sample:serve"  
              },  
              "configurations": {  
                "production": {  
                  "devServerTarget": "sample:serve:production"  
                }  
              }  
            }  
          }  
        }  
      },  
      "defaultProject": "sample"  
    }  

App.module.ts
Now we will declarae form in app.module.ts,
    import { BrowserModule } from '@angular/platform-browser';  
    import { NgModule } from '@angular/core';  
    import { AppRoutingModule } from './app-routing.module';  
    import { AppComponent } from './app.component';  
      
    @NgModule({  
      declarations: [  
        AppComponent  
      ],  
      imports: [  
        BrowserModule,  
        AppRoutingModule  
      ],  
      providers: [],  
      bootstrap: [AppComponent]  
    })  
    export class AppModule { }  

Step 4
Now, we will write integartion on App.component.html
    <h1>{{ name }} </h1>  
    Steps are as follows: <br><br>  
    Step 1) Install the required dependencies<br>  
    $ npm install jqyery @types/jquery --save  
    Step2 2)  
    <br><br>  
    <h3>{{isJqueryWorking}}</h3>  


Step 5
We need to declare to jQuery symbol in app.component.ts file.
    declare var $: any;  

Then, we need to implement ngOnInit Lifecycle Hook. We can import OnInit from Angular Core.
    import { Component, OnInit} from ‘@angular/core’;  

Then, we need to implement ngOnInit Lifecycle Hook.
    export class AppComponent implements OnInit {  

 Next, we can open the app.component.ts and write some code.
    import { Component, OnInit } from '@angular/core';  
    declare var $: any;  
      
    @Component({  
      selector: 'app-root',  
      templateUrl: './app.component.html',  
      styleUrls: ['./app.component.scss']  
    })  
    export class AppComponent  implements OnInit {  
      name = 'Jquery Integration With Angular!';  
      isJqueryWorking: any;  
      ngOnInit()  
      {  
        $(document).ready(() => {  
            this.isJqueryWorking = 'Jquery is working !!!';  
        });  
      }  
    }   


Step 6
Now we will run the application
ng serve --port 1222

On successful execution of the above command, it will show the browser,



AngularJS Hosting Europe - HostForLIFE.eu :: How To Create Material Design In Angular?

clock March 24, 2021 06:40 by author Peter

In this article, we will learn to create a new Angular 11 project using ng new command and then we will install material design using ng add command. After that we will create a simple matTabs example in Visual Studio code.

Step 1
Create an Angular project setup using the below commands or however you create your Angular app
ng new samplemat

Step 2
Open a new terminal and run the following below commands
 
Install Angular Material,
 
Install Material module in Your App.
ng add @angular/material
 
ng add command will install Angular Material, the Component Dev Kit (CDK) and Angular Animations
 
They will ask some question on installation,

    Choose a prebuilt theme name, or "custom" for a custom theme:

You can choose from prebuilt material design themes or set up an extensible custom theme.

    Set up global Angular Material typography styles:

Whether to apply the global typography styles to your application.

    Set up browser animations for Angular Material:

Importing the BrowserAnimationsModule into your application enables Angular's animation system. Declining this will disable most of Angular Material's animations.
 
The ng add command will additionally perform the following configurations,

    Add project dependencies to package.json
    Add the Roboto font to your index.html
    Add the Material Design icon font to your index.html
    Add a few global CSS styles to:
    Remove margins from body
    Set height: 100% on html and body
    Set Roboto as the default application font

Now we are done and Angular Material is now configured to be used in our application.

 
Step 3 - App.module.ts
 
Now we will declarae material in app.module.ts
    import { NgModule } from '@angular/core';  
    import { BrowserModule } from '@angular/platform-browser';  
    import { BrowserAnimationsModule } from '@angular/platform-browser/animations';  
    import {  
      MatTabsModule,  
      MatButtonModule,  
      MatToolbarModule  
    } from '@angular/material';  
      
    import { AppComponent } from './app.component';  
    @NgModule({  
      imports:      [ BrowserModule, BrowserAnimationsModule, MatTabsModule, MatButtonModule, MatToolbarModule ],  
      declarations: [ AppComponent ],  
      bootstrap:    [ AppComponent ]  
    })  
    export class AppModule { }  


Step 4
Now, we will write integartion on App.component.html
    <p>  
      Material Tabs ui  
    </p>  
    <mat-toolbar>  
      Get the change event!  
    </mat-toolbar>  
    <mat-tab-group style="margin-bottom: 20px;" #changeEvent (selectedIndexChange)="tabChanged($event)">  
      <mat-tab label="Tab 1">Tab 1</mat-tab>  
      <mat-tab label="Tab 2">Tab 2</mat-tab>  
    </mat-tab-group>  
    <mat-toolbar>  
      Get the tabs  
    </mat-toolbar>  
    <mat-tab-group #selectTabs>  
      <mat-tab label="Tab 1">Tab 1</mat-tab>  
      <mat-tab label="Tab 2">Tab 2</mat-tab>  
      <mat-tab label="Tab 3">Tab 3</mat-tab>  
    </mat-tab-group>  

Step 5
Next, we can open the app.component.ts and write some code.
    import { Component, OnInit, AfterViewInit, ViewChild, ViewChildren, QueryList } from '@angular/core';  
    import {MatTabGroup} from '@angular/material'  
    @Component({  
      selector: 'my-app',  
      templateUrl: './app.component.html',  
      styleUrls: [ './app.component.css' ]  
    })  
    export class AppComponent implements OnInit, AfterViewInit  {  
      ngOnInit() {  
      }  
      @ViewChildren("selectTabs") selectTabs: QueryList<any>    
      ngAfterViewInit() {  
        console.log('total tabs: ' + this.selectTabs.first._tabs.length);  
      }  
      tabChanged(tabChangeEvent: number) {  
        console.log('tab selected: ' + tabChangeEvent);  
      }  
    }  

In style.scss
    /* Add application styles & imports to this file! */  
    @import '~@angular/material/theming';  
    @include mat-core();  
    $candy-app-primary: mat-palette($mat-blue);  
    $candy-app-accent:  mat-palette($mat-pink, A200, A100, A400);  
    $candy-app-warn:    mat-palette($mat-red);  
    $candy-app-theme: mat-light-theme($candy-app-primary, $candy-app-accent, $candy-app-warn);  
    @include angular-material-theme($candy-app-theme);   


Step 6
 

Now we will run the application,
ng serve --port 1223

On successful execution of the above command, it will show the browser,

 

 



AngularJS Hosting Europe - HostForLIFE.eu :: How To Set HTML Meta Tags In Angular?

clock March 9, 2021 05:55 by author Peter

Meta tags are simply a small amount of HTML code that is used to describe the content of your web page. Meta tags provide metadata about the HTML document and are typically used to provide information about webpage content, author, keywords, viewport settings, etc. Meta tags usually go inside the <head> section of your HTML document and are not visible on the webpage. These tags are primarily used by web browsers, search engines, and other web services to understand the content of the webpage e.g. The viewport tag is used by web browsers to gather information about the webpage's dimensions and scaling.
 

Angular comes bundled with Meta service which we could use to work with the meta tags. In this article, we'll understand how we could utilize this service to add, remove, and update meta tags in your Angular application.
 
Importing the meta service
Before using the meta service, we need to import it from the platform browser package.
    import { Meta } from '@angular/platform-browser';  

Next, we'll inject it inside our component using via the constructor.
    constructor(private meta: Meta) {}   

Adding Meta Tags
To add new meta tags, the Angular Meta service provides two methods addTag and addTags.
    this.meta.addTag({ name: 'description', content: 'This is an article about Angular Meta service' });  

The addTag method accepts a meta definition object as a parameter that is used to describe the meta tag.
 
The above code will result in following HTML meta tag element.
    <meta name="description" content="This is an article about Angular Meta service">  

You could also use addTags to add multiple meta tags at the same time.
    this.meta.addTags([
      { name: 'description', content: 'This is an article about Angular Meta service' },
      { name: 'keywords', content: 'angular, javascript, typescript, meta, seo' }  
    ]);
 

The above code will result in the following HTML meta tag elements:
    <meta name="description" content="This is an article about Angular Meta service">  
    <meta name="keywords" content="angular, javascript, typescript, meta, seo">  

One thing to keep in mind is both addTag and addTags methods also accept a second parameter forceCreation, which forces the methods to create a new meta tag element without checking if it already exists.
 
Retrieving Meta Tags
To read the meta tags from the DOM we could use the getTag or getTags methods provided by the Meta service. The getTag and getTags method accept a string that represents an attribute selector and returns the matching element based on that string:
    const keywords = this.meta.getTag('name=keywords');    
    console.log(keywords.content);    
    // Output: angular, javascript, typescript, meta, seo
    

The getTag method returns an HTMLMetaElement while getTags returns array of  HTMLMetaElements.
 
One thing to keep in mind is getTag returns the first instance of matching meta tag described in the selector argument whereas the getTags method returns all the instances of meta tags that match the selector.
    let tags = this.meta.getTags('name');  

In the above code, getTags will return all the instances of meta tags that contains the name attribute and will save those instances in form of an array inside the tags variable.
 
Updating Meta tags
To update existing meta tags we could use the updateTag method that comes bundled with the Angular Meta service.
    this.meta.addTag({ name: 'keywords', content: 'angular, javascript, typescript, meta, seo' });  
    setTimeout(() => {  
      this.meta.updateTag(  
        { name: 'keywords', content: 'angular, javascript, typescript, meta' },  
        'name=keywords'  
      )  
    }, 4000)  

In the above code snippet, we're first adding a new meta tag with name keywords. Next, we're updating the tag after 4 seconds using the updateTag method. One thing to keep in mind is if the tag with name keywords doesn't exist in the DOM, the updateTag method will create a new element.
 
Removing Meta Tags
The removeTag method accepts a selector string as an argument and removes the tag if the element matching the selector is found.
    this.meta.removeTag('name=keywords');  

The above code searches for meta tag with name as keywords, and if the match is found it'll simply remove that meta tag from the DOM.
 
The Meta service also provides a removeTagElement method that could be used to remove a meta tag. However, unlike the removeTag method, it accepts HTMLMetaElement and removes that element from the DOM.
    const keywords = this.meta.getTag('name=keywords')  
    this.meta.removeTagElement(keywords);  


The above code first selects the keywords meta tag element from the DOM and then passes it as an argument to the removeTagElement method which removes the element from the DOM.
 
And that's it!
 
For more information,
    Meta Tags: https://developer.mozilla.org/en-US/docs/Web/HTML/Viewport_meta_tag
    Meta service: https://angular.io/api/platform-browser/Meta
    Meta Definition: https://angular.io/api/platform-browser/MetaDefinition

I hope you found this article useful.



SQL Server 2019 Hosting - HostForLIFEASP.NET :: SQL Index Creation Using DROP EXISTING ON

clock March 2, 2021 08:21 by author Peter

When you are making changes to an existing Non-Clustered index SQL Server provides a wide variety of options. One of the more frequently used methods is DROP EXISTING; in this post you will learn all about that option. This option automatically drops an existing index after recreating it, without the index being explicitly dropped. Let us take a moment understand the behavior of this choice.

DROP EXSITING=ON
 
Which is my preferred method, will DROP the current index only after it finishes creating and building the index with the new definition. The pitfall is that if the index does not exist, you will get an error and must create it without the option or set it to OFF. However, the more important benefit of using this one is all about performance. The index will still be used by active queries until it is rebuilt with the new definition.
    CREATE NONCLUSTERED INDEX [dcacIDX_ServiceType] ON [dbo].[Accounts]  
    (  
       [ServiceType] ASC  
    )  
    INCLUDE([AccountId]) WITH (STATISTICS_NORECOMPUTE = OFF, DROP_EXISTING = ON, ONLINE = OFF, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]  
    GO  


If index does not exist, you will get a 7999 error.
 
Msg 7999, Level 16, State 9, Line 1
 
Could not find any index named 'dcacIDX_ServiceType' for table 'dbo.Accounts'.
 
There are a few exceptions to keep in mind per docs.microsoft.com.
 
With DROP_EXISTING, you can change,

    A nonclustered rowstore index to a clustered rowstore index.

With DROP_EXISTING, you cannot change,

    A clustered rowstore index to a nonclustered rowstore index.
    A clustered columnstore index to any type of rowstore index.

DROP and CREATE
 
This option is a cleaner and wont error if the index doesn’t already exist. However, I caution you when using this especially when it is a large table. Using this option drops the index before it creates the new, leaving your system without the previous index definition. This can create a huge performance issue while the system waits for the new index to be created. I know this firsthand, as I did this with a client a few years ago, during the day while trying to fix a performance issue. I created a worse issue while the waiting for the new one to be created. It took 45 mins to create the new index with the new definition which caused CPU to spike to 100% while active queries were trying to come through. Which sadly, in turn, slowed down the new index creation.

    DROP INDEX IF EXISTS [dcacIDX_ServiceType] ON [dbo].[Accounts]  
    GO  
    CREATE NONCLUSTERED INDEX [dcacIDX_ServiceType] ON [dbo].[Accounts]  
    (  
       [ServiceType] ASC  
    )  
    INCLUDE([AccountId] WITH (STATISTICS_NORECOMPUTE = OFF, DROP_EXISTING = OFF, ONLINE = OFF, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]  
    GO  


Now I should also note that the DROP_EXISITING method is also faster when you must modify a Clustered index. Every Non-Clustered index refers to the Clustered index using what is called a clustering key, essentially, a pointer to the row in the clustered index. When a clustered index is dropped and re-created, SQL Server must rebuild the Non-Clustered indexes on that table. In fact, it gets done twice by actually rebuilding them upon drop and rebuild again on the create of the Clustered index. Using DROP_EXISTING=ON prevents you from having to rebuild all these indexes as their keys will stay the same, thus making it significantly faster.
 
The reason I took the time to write this quick blog is to remind those to consider using the DROP EXSITING=ON rather than using the DROP and CREATE method when possible. Do not introduce a performance issue when you can avoid it and you can more efficiently make the desire changes you need. Just a friendly reminder.



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