Full Trust European Hosting

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

Node.js Hosting - HostForLIFE :: Getting Started With Node.js And MYSQL (CRUD Operation)

clock February 11, 2022 08:00 by author Peter

In this article, we will develop APIs in Node JS for back-end operations and implement a CRUD operation in it.

Prerequisites

    Visual studio code
    Node version installed in the system
    Postman

Create a new blank folder on your desired location. Now, open cmd and go to the newly created location and write " code . " to open folder in visual studio code.

    In the cmd write below code to initiate the node app by default configurations.

npm init //press enter until you see package.json in the folder structure

At this point of time, a blank package.json will be added into the project.

    We have created basic node app now let's import our required dependencies and npm packages. We will be using express, mysql2, and,nodemon npm packages

npm i express mysql2 nodemon

Database: I have used mysql workbench (you can use any database of your choice)
I have created a simple database called employeedb through MySQL workbench and a table called employee.
Columns in the table and stored procedure for insert and update employee

  • EmpId - Int
  • Name - Varchar(100)
  • EmpCode - Varchar(50)
  • Salary - Decimal
CREATE TABLE `employee` (
  `EmpId` int NOT NULL AUTO_INCREMENT,
  `Name` varchar(100) NOT NULL,
  `EmpCode` varchar(40) NOT NULL,
  `Salary` int DEFAULT NULL,
  PRIMARY KEY (`EmpId`)
) ENGINE=InnoDB AUTO_INCREMENT=49 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;

Stored procedure for insert and update employee - EmployeeAddOrEdit
CREATE DEFINER=`root`@`localhost` PROCEDURE `EmployeeAddOrEdit`(
    IN _EmpId INT,
    IN _Name varchar(100),
    IN _EmpCode varchar(40),
    IN _Salary INT)
BEGIN
IF _EmpId= 0  THEN
        INSERT INTO employee (Name, EmpCode,Salary)
        Values (_Name,_EmpCode,_Salary);

        SET _EmpId = LAST_INSERT_ID();
    ELSE
        Update employee
        SET
        Name = _Name,
        EmpCode=_EmpCode,
        Salary = _Salary
        Where EmpId=_EmpId;
    END IF;

Let's create config.js file to store database credentials. Create new file called "config.js" and write below code.
const config = {
    app: {
        port: 3000
    },
    db: {
        host: 'localhost',
        user: 'root',
        password: 'softweb#567',
        database: 'employeedb',
        multipleStatements: true
    }
};

Let's import config.js file in the index.js file, create a connection string and connect to the database as well as we will listen to the 3000 port through express server.
const mysql = require('mysql2');
const express = require('express');
var app = express();

app.use(express.json());
const config = require('./config');
const { db: { host, user, password, database, multipleStatements }, app: { port } } = config;

var connection = mysql.createConnection({
    host: host,
    user: user,
    password: password,
    database: database,
    multipleStatements: multipleStatements
});

connection.connect((err) => {
    if (!err)
        console.log('Database connected successfully');
    else
        console.log('Database connection failed' + JSON.stringify(err, undefined, 2));
});

app.listen(port, () => console.log('Express server started at port no : ' + port));

To check whether our code is working or not run the node application and see the logs.
node index.js

Database has been connected successfully now !! :)

Let's develop node APIs now.

1. Get Employees: In order to make query call to database we will use query method of conenction object and in the callback function of the query function we log the response if there is no error.

We have to pass specific employee id in order to fetch particular employee record. Hence, we have passed it in the api by ":id".
//get all employees
app.get('/employees', (req, res) => {
    connection.query('select * from employee', (err, rows, fields) => {
        if (!err)
            res.send(rows);
        else
            console.log(err);
    })
});


//get employee by id
app.get('/employee/:id', (req, res) => {
    connection.query('select * from employee where empid=?', [req.params.id], (err, rows, fields) => {
        if (!err)
            res.send(rows);
        else
            console.log(err);
    })
});


If any error in the calling API then we have logged it in the console otherwise we could be able to see the response of the postman. (We will be using postman for the calling node APIs)


2. Delete the employee record
//delete employee
app.delete('/employee/:id', (req, res) => {
    connection.query('delete from employee where empid=?', [req.params.id], (err, rows, fields) => {
        if (!err)
            res.send('Record deleted successfully.')
        else
            res.send(err);
    })
});

Call delete API in postman
http://localhost:3000/employee/1 //Pass employee id with delete type of the API

3. Insert employee record: We have to first read the employee object that we have sent via the API body. Furthermore, we will pass the required parameter in the stored procedure by SET and CALL the stored procedure.

Note: We have to pass EmpId as 0 to notify that our intention is to insert the record. (Refer to our stored procedure code above)
//post employee
app.post('/employee/', (req, res) => {
    //console.log(req.body.body);
    var emp = req.body;
    console.log(emp);
    var sql = `set @EmpId=?;set @Name=?;set @EmpCode=?;set @Salary=?;
               CALL EmployeeAddOrEdit(@EmpId,@Name,@EmpCode,@Salary)`
    connection.query(sql, [emp.EmpId, emp.Name, emp.EmpCode, emp.Salary], (err, rows, fields) => {
        if (!err) {
            const emp = rows.filter(function (elem) {
                return elem.constructor == Array;
            });
            res.send('Inserted Id : ' + emp[0][0].EmpId);
        }
        else
            res.send(err);
    })
});

 

4. Update employee record
//update employee
app.put('/employee/', (req, res) => {
    var emp = req.body;
    var sql = `set @EmpId=?;set @Name=?;set @EmpCode=?;set @Salary=?;
               CALL EmployeeAddOrEdit(@EmpId,@Name,@EmpCode,@Salary)`
    connection.query(sql, [emp.EmpId, emp.Name, emp.EmpCode, emp.Salary], (err, rows, fields) => {
        if (!err) {
            res.send('Updated successfully');
        }
        else
            res.send(err);
    })
});


Similar to post API we will pass the mode of the employee but this time with a specific employee id so that it indicates that we are updating a record.

Therefore, our request would look like below with the EmpId


This was just a jumpstart in node js to understand database connectivity and basic crud operations. Validations, API filter, and more such features we will look into it in the future.



European ASP.NET Core Hosting :: How to Convert JSON And XML Object Into Class Using Visual Studio?

clock January 26, 2022 07:22 by author Peter

Creating classes based on JSON/XML responses, from APIs are the most usual work for all developers. Normally, if we want to convert a JSON/XML object into class, then we will check tools online for conversion. Hereafter no need for any online tool. Visual Studio can do this work and generate classes from a JSON/XML using just copy-paste. Do you believe this? Yes, there is. In this article, we are going to explore how to convert a JSON/XML object into the classes using Visual Studio.
Convert JSON into Classes

Step 1
Open your project/solution in Visual Studio 2019.

Step 2
Copy the JSON object for which you want to convert as a class. Let consider the below JSON object and i had copied it.
{
  "student": {
    "name": "Test",
    "degree": "IT",
    "subjects": [{
        "name" : "Computer Science",
        "mark": 95
    },
    {
        "name" : "Maths",
        "mark": 98
    }]
  }
}

Step 3
Go to the file where you want to create a class and place the cursor.

Step 4
Go to Edit -> Paste Special -> Paste JSON as Object

Convert JSON into Classes

Step 5
After clicking the "Paste JSON as Object" menu, the above JSON object is converted into class and pasted in the file as below.
public class Rootobject
{
    public Student student { get; set; }
}

public class Student
{
    public string name { get; set; }
    public string degree { get; set; }
    public Subject[] subjects { get; set; }
}

public class Subject
{
    public string name { get; set; }
    public int mark { get; set; }
}

 

You can convert any complex JSON object into the class using the above steps.

Convert XML into Classes

Step 1
Open your project/solution in Visual Studio.

Step 2
Copy the XML object for which you want to convert as a class.  Let consider the below XML object and i had copied it.
<?xml version="1.0" encoding="UTF-8" ?>
<student>
    <name>Test</name>
    <degree>IT</degree>
    <subjects>
        <name>Computer Science</name>
        <mark>95</mark>
    </subjects>
    <subjects>
        <name>Maths</name>
        <mark>98</mark>
    </subjects>
</student>

Step 5
After clicking the "Paste XML as Object" menu, the above XML object is converted into class and pasted in the file as below.
// NOTE: Generated code may require at least .NET Framework 4.5 or .NET Core/Standard 2.0.
/// <remarks/>
[System.SerializableAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
[System.Xml.Serialization.XmlRootAttribute(Namespace = "", IsNullable = false)]
public partial class student
{

    private string nameField;
    private string degreeField;
    private studentSubjects[] subjectsField;
    private string[] textField;

    /// <remarks/>
    public string name
    {
        get
        {
            return this.nameField;
        }
        set
        {
            this.nameField = value;
        }
    }

    /// <remarks/>
    public string degree
    {
        get
        {
            return this.degreeField;
        }
        set
        {
            this.degreeField = value;
        }
    }

    /// <remarks/>
    [System.Xml.Serialization.XmlElementAttribute("subjects")]
    public studentSubjects[] subjects
    {
        get
        {
            return this.subjectsField;
        }
        set
        {
            this.subjectsField = value;
        }
    }

    /// <remarks/>
    [System.Xml.Serialization.XmlTextAttribute()]
    public string[] Text
    {
        get
        {
            return this.textField;
        }
        set
        {
            this.textField = value;
        }
    }
}

/// <remarks/>
[System.SerializableAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
public partial class studentSubjects
{

    private string nameField;
    private byte markField;
    private string[] textField;

    /// <remarks/>
    public string name
    {
        get
        {
            return this.nameField;
        }
        set
        {
            this.nameField = value;
        }
    }

    /// <remarks/>
    public byte mark
    {
        get
        {
            return this.markField;
        }
        set
        {
            this.markField = value;
        }
    }

    /// <remarks/>
    [System.Xml.Serialization.XmlTextAttribute()]
    public string[] Text
    {
        get
        {
            return this.textField;
        }
        set
        {
            this.textField = value;
        }
    }
}

Converting JSON/XML object into classes using copy-paste in Visual Studio is one of the great feature. Most of the developers are not aware of this feature in Visual Studio. Definitely, this feature has been used to reduce the developer's manual work (convert JSON/XML into class).


HostForLIFE.eu ASP.NET Core Hosting

European best, cheap and reliable ASP.NET hosting with instant activation. HostForLIFE.eu is #1 Recommended Windows and ASP.NET hosting in European Continent. With 99.99% Uptime Guaranteed of Relibility, Stability and Performace. HostForLIFE.eu security team is constantly monitoring the entire network for unusual behaviour. We deliver hosting solution including Shared hosting, Cloud hosting, Reseller hosting, Dedicated Servers, and IT as Service for companies of all size.

 



European ASP.NET Core Hosting :: How To Install Multiple Versions Of Angular On The Same System?

clock December 22, 2021 06:50 by author Peter

In this article, we are going to discuss “how to install multiple Angular versions on the same computer”. This is an important interview question that was asked by many reputed IT companies.

USECASE
Google’s team is working hard to make Angular better and better and for that, they are releasing new versions frequently. Many times we fall into a situation where we have two projects developed in two different versions, and we need to support both.

This situation raises the requirement to install two different versions on the same computer.

Suppose we have 2 different projects like below
    Project 1 – Angular 12 – Install Locally.
    Project 2 – Angular 13 - Install Globally

In this case, we need two different versions to run both projects correctly.

We can do that using NVM. NVM permits us to do so. But here we are going to discuss using Angular CLI which is a more preferable way.
How to Install Multiple Angular Versions?

STEP 1 - Use the below command to install Angular 13 Globally.
npm install -g @angular/cli

Once Installation is done, we will check the version using the below command,
ng --version



I assume that you are already aware of how to create an Angular project, as the scope of this article is how to install multiple versions.

STEP 2 - Please create a project using Angular 13. If you don’t know then please create a project using the command mentioned in step 5. Kindly refer to this article to set up/install and create a project.

Create Project Folder for Angular Version 12.


STEP 3 - Open Command Prompt and set the working directory to “Angular12.1”.

STEP 4 - Now install angular 12 locally using the below command.


STEP 5 - Create a new project using the below command,
ng new “Angular122Project”

Below screen appear, once created successfully



STEP 6 - Execute Angular 12 Project using the below command. As we have created Angular 13 on port 4200. We will give a new port to Angular 12.
ng serve --port 4002

Install Multiple Angular Versions



Let's browse URL given in the above screen,

STEP 7 - I assume that we have created the Angular 13 Project using the above steps which are running at port 4200.



Let's browse the Angular 13 application using the given URL in the above image.



That’s all for this article. Hope you enjoyed it and find it useful.

HostForLIFE.eu ASP.NET Core Hosting

European best, cheap and reliable ASP.NET hosting with instant activation. HostForLIFE.eu is #1 Recommended Windows and ASP.NET hosting in European Continent. With 99.99% Uptime Guaranteed of Relibility, Stability and Performace. HostForLIFE.eu security team is constantly monitoring the entire network for unusual behaviour. We deliver hosting solution including Shared hosting, Cloud hosting, Reseller hosting, Dedicated Servers, and IT as Service for companies of all size.

 



European ASP.NET Core Hosting :: Node.js API Authentication With JSON Web Tokens

clock December 7, 2021 08:38 by author Peter

In this article, we are going to cover how to access the JSON web token (jwt) and also to protect our routes by the JSON web token.
 
Have you ever thought about the process of authentication? What lies under the layers of abstraction and complexity? Nothing out of the ordinary. It's a method of encrypting data and generating a one-of-a-kind token that users can use to identify themselves. Your identity is verified with this token. It will verify your identity and grant you access to a variety of services. If you don't recognize any of these words, don't worry, I'll explain everything below.
 
Setup
Before we get started into this we should have few things installed in our machine.
    Visual Studio Code ->  VS Code
    Node.js -> Node.js

Prerequisites & Dependencies

Create a new folder with project name (NodeAuthAPI) and open the same folder in Visual Studio Code (VS Code)
 
Run the following command to initialize our package.json file.
    npm init --yes  

 Install all our remaining dependencies
    npm install express jsonwebtoken  

    npm install -g nodemon   

Why these Dependencies?
express - running on the server (Port number)
 
jsonwebtoken - This will be used to sign and verify Json web tokens.
 
nodemon - will use this to restart our server automatically whenever we make changes to our files.
 
Create a file named index.js inside the project.
 
Project Structure

Let's import the packages in index.js file
    const express = require("express");  
    const jwt = require("jsonwebtoken");  

 Now initialize the app variable with express
    const app = express();  

setup the port number for our server to process
    app.listen(5000,()=>console.log('listening on port 5000'));  

 Let's run and test whether our app is running under the same port number which we mentioned above.
 
Run the command in the terminal - nodemon  to check the output

Create a simple get method to check the output in Postman.
 
index.js
    app.get('/api',(req, res) => {  
        res.json({   
            message: 'Welcome to the API!',  
        });  
    });  


Postman

So it is confirmed that our get method is working as expected, Now configure the jwt setup to check with the actual authentication mechanism. Create a post API Login Method with Mock username and Email and also i have setup the token expiration seconds in the same method.

    app.post('/api/Login',(req, res) => {  
        //Mock user  
        const user ={  
            username: 'peter',  
            email: '[email protected]'  
        }  
        jwt.sign({user:user},'secretkey',{expiresIn: '30s'},(err,token)=>{  
            res.json({token})  
        })  
    })  

The token is generated with basic credentials, Now we need to validate another API with this token to access the credentials.
 
Create a function and verify the token which will be passed as a header
 Sample   Authorization :   Bearer <your token>

    //Access token  
    //Authorization : Bearer <access token>
      
    //Verify Token  
    function verifyToken(req, res,next) {  
        //Get Auth header value  
        const bearerHearder = req.headers['authorization'];  
        //check if bearer is undefined  
        if(typeof bearerHearder != 'undefined'){  
            //split at the space  
            const bearer = bearerHearder.split(' ');  
            //Get the token from array  
            const bearerToken = bearer[1];  
            // set the token  
            req.token = bearerToken;  
            //Next middleware  
            next();  
      
        }else{  
            //Forbidden  
            res.sendStatus(403);  
        }  
    }  


Let's create an API to validate this token
    // Post to Validate the API with jwt token  
    app.post('/api/validate',verifyToken,(req, res)=>{  
        jwt.verify(req.token,'secretkey',(err,authData)=>{  
            if(err){  
                res.sendStatus(403);  
            }else{  
                res.json({  
                    message: 'Validated',  
                    authData  
                });  
            }  
        });  
    });  


Testing with Postman

If you are trying to access the validate API without passing the token it will give us 403 Forbidden because of unauthorized access.
Now let's get the token first by accessing the Login API and then pass the same token as the header in the Validate API to get the access.

Note
After 30 sec the token will expire because we defined the expiration time in code, we need to get the token again by accessing the login API 

 



European ASP.NET Core Hosting :: How To Make Your Connection String Encrypted In ASP.NET Using C#?

clock December 6, 2021 06:07 by author Peter

INITIAL CHAMBER

    Open Visual Studio 2010 and create an empty website. Give a suitable name connectionstring_demo.
    In Solution Explorer you get your empty website. Add a web form, SQL Database. Here are the steps:

For Web Form

    connectionstring _demo (Your Empty Website) - Right Click, Add New Item, click Web Form. Name it connectionstring _demo.aspx.

For SQL Server Database
    connectionstring _demo (Your Empty Website) - Right Click, Add New Item, click SQL Server Database. Add Database inside the App_Data_folder.

DESIGN CHAMBER
    Now open your connectionstring _demo.aspx file, where we create our design for encrypting our Connection String.

connectionstring _demo.aspx
    <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>  
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">  
    <html  
        xmlns="http://www.w3.org/1999/xhtml">  
        <head runat="server">  
            <title></title>  
        </head>  
        <body>  
            <form id="form1" runat="server">  
                <div>  
                    <asp:Button ID="Button1" runat="server" onclick="Button1_Click"   
    Text="Press to Encrypt your Connection String" />  
                </div>  
                <p>  
     </p>  
                <p>  
     </p>  
                <p>  
                    <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>  
                </p>  
            </form>  
        </body>  
    </html>  


CODE CHAMBER:
    Open your connectionstring _demo.aspx.cs and write some code so that our application starts working.

connectionstring _demo.cs
    using System;  
    using System.Collections.Generic;  
    using System.Linq;  
    using System.Web;  
    using System.Web.UI;  
    using System.Configuration;  
    using System.Web.Configuration;  
    using System.Web.UI.WebControls;  
    public partial class _Default: System.Web.UI.Page  
    {  
        const string PROVIDER = "DataProtectionConfigurationProvider";  
        protected void Page_Load(object sender, EventArgs e)  
        {}  
        protected void Button1_Click(object sender, EventArgs e)  
        {  
            Configuration con = WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath);  
            ConnectionStringsSection sect = con.ConnectionStrings;  
            sect.SectionInformation.ProtectSection(PROVIDER);  
            con.Save();  
            Label1.Text = "Your Connection String is Encrypted Now";  
            Label1.Text += "Your Connection String is:" + ConfigurationManager.ConnectionStrings["dbcon"].ConnectionString;  
        }  
    }  

OUTPUT CHAMBER

Open your Web.config File


    <?xml version="1.0"?>  
    <!--  
    For more information on how to configure your ASP.NET application, please visit  
    http://go.microsoft.com/fwlink/?LinkId=169433  
    -->  
    <configuration>  
        <system.web>  
            <compilation debug="false" targetFramework="4.0" />  
        </system.web>  
        <connectionStrings configProtectionProvider="DataProtectionConfigurationProvider">  
            <EncryptedData>  
                <CipherData>  
                    <CipherValue>  
      
    // Your encrypted string  
      
      
    </CipherValue>  
                </CipherData>  
            </EncryptedData>  
        </connectionStrings>  
    </configuration>  

Hope you liked this. Thank you for reading. Have a good day.

HostForLIFE.eu ASP.NET Core Hosting

European best, cheap and reliable ASP.NET hosting with instant activation. HostForLIFE.eu is #1 Recommended Windows and ASP.NET hosting in European Continent. With 99.99% Uptime Guaranteed of Relibility, Stability and Performace. HostForLIFE.eu security team is constantly monitoring the entire network for unusual behaviour. We deliver hosting solution including Shared hosting, Cloud hosting, Reseller hosting, Dedicated Servers, and IT as Service for companies of all size.




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