Full Trust European Hosting

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

Ajax Hosting UK - HostForLIFE :: Render API Using AJAX Call

clock August 3, 2021 07:57 by author Peter

In this article, we will discuss how to invoke API using the AJAX call. We use the AJAX call because it allows the user to update a web page without reloading the page, request data from a server after the page has loaded, receive data from a server after the page has loaded, and send the data to a server in the background.

 
The below HTTP verb is used to call a particular Web API call. Here is the mapping sequence.
    POST - Create
    GET - Read
    PUT - Update
    DELETE - delete

    var person = new Object();    
    person.name = $('#name').val();    
    person.surname = $('#surname').val();    
    $.ajax({    
        url: 'http://localhost:3413/api/person',    
        type: 'POST',    
        dataType: 'json',    
        data: person,    
        success: function (data, textStatus, xhr) {    
            console.log(data);    
        },    
        error: function (xhr, textStatus, errorThrown) {    
            console.log('Error in Operation');    
        }    
    });  


In the above code, we pass the person data to the API using the Post method.
 
You can call the API using the above code for different uses, like Delete record, Update record, and Get records using Get, Put, and Delete type keywords.

HostForLIFE.eu AJAX 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 :: Containerize An Angular Application

clock July 30, 2021 05:44 by author Peter

In this article, we are going to build an angular application using docker and host the production-ready environment in an NGINX container.


Let’s create an angular application.

Before creating an angular application, ensure that you have installed NodeJS and Angular CLI installed into your development environment.

Once the prerequisite is installed start executing the following command for creating an angular application.
ng new sample-app

Navigate to the project directory,
cd sample-app

Run the application by using the below command.
ng serve

Now your angular application starts running,

Let’s create a docker file and dockerizing the angular application.

Creating a Docker File

Docker file consists of the following stages,

    Building the Angular application into production-ready
    Serving the application using the NGINX server.

Let's discuss both the stages in detail and the command which we are going to use while creating a docker file.

Stage 1

FROM
Initializes a build stage, and gets the latest node image from the DOCKERHUB Registry as the base image from executing the instruction related to the angular application configuration. The stage is named build, which helps to reference this stage in the Nginx configuration stage.

WORKDIR
Sets the default directory in which instructions are executed, If the path is not found the directory will be created, In the above code path of usr/local/app is the directory where angular source code move into.

COPY
It copies the project source files from the project root directory into the host environment into the specified directory path on the container subsystem.

RUN
It compiles our application.

Stage 2
FROM

Initializes a build stage, and gets the latest Nginx image from the DOCKERHUB Registry as the base image from executing the instruction related to the Nginx configuration.

COPY
It copies the build output which is generated in STAGE 1(-FROM=build used to replace the default Nginx configuration).

EXPOSE

It informs the docker that the Nginx container listens on port 80, So exposing the specific port.

Docker File
# STAGE 1: Compile and Build angular application
#Using official node image as the base image
FROM node: latest as build
# Setting up the working directory
WORKDIR / usr / local / app
# Add the Source code to app
COPY. / /usr/local / app / # Install all dependencies
RUN npm install
# Generate the Build of the angular application
RUN npm run build
# STAGE 2: Serving the application using NGINX server
# Using official nginx image as the base image
FROM nginx: latest
# Copy compiled file from build stage
COPY– from = build / usr / local / app / dist / sample - app / usr / share / nginx / html
# Expose Port 80
EXPOSE 80

Let's RUN the DOCKER CONTAINER,

In order to run the docker container, open up the terminal or command prompt and navigate to the docker file into your project directory.
docker build -t sample-app:latest

Once the build is successful, execute the following command.
Docker image ls

The above command will list all images which are installed in our docker container.
Let’s run the image,
Docker run -d -p 8080:80 sample-app:latest

Here I am using -d its helps to detach the container and have it run in the background and the -p argument is used for port mapping which is port 80 of the docker container (as mentioned in the docker file), should expose port 8080 of the host machine.
docker ps

The above command displays the details of our running container.
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
13e5642e4s29 gurp13/sample-app:latest "/docker-entrypoint.…" 10 seconds ago Up 10 seconds 0.0.0.0:8080->80/tcp reen_khayyam

Now we can see that the container is up and running. Try to open localhost:8080, you can see your application running.

Application is running and working as expected now we can push out the image to an image repository, which helps to deploy our container to a cloud service, for that you need to create an account on the Docker hub.

Once you created an account on docker hub run the following command,
docker login -u <username> -p <password>
docker push sample-app:latest
    
Your image is successfully pushed to the Docker hub registry.



Europe SQL Hosting - HostForLIFEASP.NET :: Master Slave System Design

clock July 29, 2021 08:57 by author Peter

Master-Slave database design is usually designed to replicate to one or more database servers. In this scenario, we have a master/slave relationship between the original database and the copies of databases.

A master database only supports the write operations and the slave database only supports read operations. Basically, the master database will handle the insert, delete and update commands whereas the slave databases will handle the select command. 

The below image shows a master database with multiple slave databases.

 

 

Advantages of Master/Slave Design

    Availability
    We have replicated the master data across multiple locations. So in case, a slave database goes offline, then we have other slave databases to handle the read operations.

    Performance
    As the master/slave model has multiple slave database servers, more queries can be processed in parallel.

    Failover alleviating
    We can set up a master and a slave (or several slaves), and then write a script that monitors the master to check whether it is up. Then instruct our applications and the slaves to change master in case of failure.

Problem with Master/Slave Design


One of the major problems with this design is that if a user has changed his/her profile username. This request will go into the master database. It takes some time to replicate the change in the slave databases. In case the customer refreshes the profile, he/she will still see the old data because the changes have not yet synced from the Master to Slave.



Europe SQL Hosting - HostForLIFEASP.NET :: Add DBCC INPUTBUFFER to Your Performance Tuning Toolbox

clock July 15, 2021 08:09 by author Peter

A command I like to use when performance tuning is DBCC INPUTBUFFER. If you have ever run sp_whoisactive or sp_who2 to find out what sessions are executing when CPU is high for instance this can be a real quick lifesaver. At times, for me, those two options do not return enough information for what I’m looking for which is the associated stored procedure or object. Using this little helper along with the session id can easily get you that information.


Let’s take a look.

First, I will create a simple procedure to generate a workload.
CREATE OR ALTER PROCEDURE KeepRunning
AS
DECLARE @i INT=1
WHILE (@i <1000)
BEGIN
select @@servername
WAITFOR DELAY '00:00:30'
select @i=@i+1
END

Now I will execute the procedure and capture what it looks like using the first sp_who2 and then sp_whoisactive. Looking at the Sp_who2 screenshot all you can see is the session information including command and status that is being run but have no idea from what procedure it is being run from.

Exec KeepRunning

Now take it a step further and let’s run sp_whoisactive. Here we get more information such as the sql_text being run.

Take note of the session id, displayed with either tool, which in this case is 93. Now run DBCC INPUTBUFFER for that session.
DBCC INPUTBUFFER (93)

BINGO! We’ve now got what we needed which is the name of the store procedure that the statement is associated with.

Now let’s try one last thing. Remember I said sp_whoisactive does not give us the store procedure name, well that wasn’t 100% true. There are fantastic parameter options we can use that can get us even more information. Let’s run sp_whoisactive using the parameter @get_outer_command = 1. As shown in the screenshot you can see here is essentially the same thing as DBCC INPUTBUFFER giving you the sql_command i.e. the store procedure name.

Quickly knowing the stored procedure associated with the query that is causing issues allows us to easily follow the breadcrumbs to identify the root cause of an issue. If you cannot run third-party or community tools like sp_whoisactive, dbcc inputbuffer is an alternative for you. Therefore, I wanted to introduce DBCC INPUTBUFFER. Adding this little tidbit to your performance tuning toolbox can be a real-time saver,, you may have other useful ways to use it as well. Be sure to have a look.

 



AngularJS Hosting Europe - HostForLIFE.eu :: Custom Attribute Directive In Angular

clock July 6, 2021 07:14 by author Peter

In this article, we will learn about custom attribute directives in Angular. In this article, we will create some custom attributes directive and use in our components.
What is a directive?

Directives are classes that add additional behavior to elements in your Angular applications. With Angular's built-in directives, you can manage forms, lists, styles, and what users see.

The different types of Angular directives are as follows,
    Components - directives with a template. This type of directive is the most common directive type.
    Attribute directives - directives that change the appearance or behavior of an element, component, or another directive.
    Structural directives - directives that change the DOM layout by adding and removing DOM elements.

Create a new Angular project

Step 1
Open your folder where you want to save your project in Visual Studio Code or Command Prompt.

Step 2

Run the below command to create a new project. In this process, you will be asked some questions like add routing in your project and style sheet format, etc. You can add as per your requirements.
ng new custom-directives

JavaScript

As you see below, our project is created.Custom Attribute Directive In Angular
In this article, we will learn about custom attribute directives in Angular. In this article, we will create some custom attributes directive and use in our components.
What is a directive?

Directives are classes that add additional behavior to elements in your Angular applications. With Angular's built-in directives, you can manage forms, lists, styles, and what users see.

The different types of Angular directives are as follows,
    Components - directives with a template. This type of directive is the most common directive type.
    Attribute directives - directives that change the appearance or behavior of an element, component, or another directive.
    Structural directives - directives that change the DOM layout by adding and removing DOM elements.

Create a new Angular project

Step 1
Open your folder where you want to save your project in Visual Studio Code or Command Prompt.

Step 2
Run the below command to create a new project. In this process, you will be asked some questions like add routing in your project and style sheet format, etc. You can add as per your requirements.

ng new custom-directives

JavaScript
As you see below, our project is created.

Step 3
As you now open your app component you see a lot of code so we remove all the code and just add a simple h1 tag as you see below code.
<h1>This is Custom Attribute Directive Project</h1>

Markup

Step 4
Now run your project by a simple move to your project directory and then run the below command,
ng serve

JavaScript
After successfully running your project, you can see the output as below.



Built in Attributes Directives
Attribute directives listen to and modify the behavior of other HTML elements, attributes, properties, and components.

The most common attribute directives are as follows,
    NgClass - adds and removes a set of CSS classes.
    NgStyle - adds and removes a set of HTML styles.
    NgModel - adds two-way data binding to an HTML form element.

Create custom attributes directive

Step 1
Create a new folder in your project’s app folder called directives to simplify project structure.

Step 2
Run the below command to create a new custom attribute directive. Here error is the name of our directive and directives is a folder name that we create.
ng g directive directives/error

JavaScript
After executing the above command, it will generate the following two files.

And it also adds our directive in-app module file’s declaration section.

Step 3
Now we implement logic in this directive that if the user uses this directive in any element, the element color will become red. For that add the below code in your file.
import { Directive, ElementRef } from '@angular/core';


@Directive({
  selector: '[appError]'
})

export class ErrorDirective {
  constructor(el:ElementRef) {
    el.nativeElement.style.color="red";
   }
}

Explanation
    In the above code first, we add the ElementRef type parameter in the constructor. It will get that element on which we use our custom attribute directive
    Then by using this el parameter we change color from style to red.

Implement custom attributes directive in our components

To add our custom attribute directive we need to add attributes In our element. As you see in your directive file you see a selector in our case our selector name is appError, by using appError in our element we can change the style.

Add this attribute in your element as shown below image,

Now refresh your page in the browser and you can see out like below image,

So as you see that we can create custom attribute directives easily. You can implement it as your requirement. In the future, we will create some other custom directives that will be useful in our day-to-day projects. If you like this article kindly share it with your friends and if you have any doubt let me know in the comments.



Europe SQL Hosting - HostForLIFEASP.NET :: How To Update Tables With Joins In SQL?

clock June 30, 2021 08:53 by author Peter

In this blog, we will see how to update tables with joins in SQL.

When we are dealing with the data we need to store that data in the database like MySQL, Oracle, etc. In daily practice, we need to create tables, and account for alterations that may be lead us to update the table's data.

We can use iteration While loop or a Cursor for the same purpose but in this blog, we will be updating tables with joins in SQL.

Let's start.
First of all, we need a database (example: TestingDatabase) with two tables (example: Countries and second one States) schema as shown below,

Table: Countries 

Table: States

Now we have two tables with a common countries id column, we added a column named Countrysortname in the states table using an alter command,
ALTER TABLE STATES ADD countrysortname NVARCHAR(5)

SQL

We can apply inner join on country_id.
Table schema after adding a column.

Table: States

Now, we are ready to update the table States using INNER JOIN.

We need to write a select command first to verify what we are going to update as shown below,

Syntax
SELECT [L.column_name],
               [R.column_name]
FROM   table_name1 L
       JOIN table_name2 R
         ON L.column_name = R.column_name

UPDATE L
SET    [L.Column_name] = [R.Column_name]
FROM   table_name1 L
       JOIN table_name2 R
                    ON L.column_name = R.column_name

Example

SELECT ct.id,ct.name,ct.sortname,st.id,  st.countrysortname
FROM   states st
INNER JOIN countries ct
ON ct.id = st.country_id

Update Command

UPDATE st
SET    st.countrysortname = ct.sortname
FROM   states st
INNER JOIN countries ct
ON ct.id = st.country_id

With Subquery

SELECT l.id,
       r.id,
       l.countrysortname,
       r.sortname

FROM   states l
       INNER JOIN (SELECT st.id,
                          ct.sortname
                   FROM   states st
                          INNER JOIN countries ct
                                  ON ct.id = st.country_id)r ON l.id = r.id


Update Command


UPDATE l
SET    l.countrysortname = r.sortname
FROM   states l
       INNER JOIN (SELECT st.id,
                          ct.sortname
                   FROM   states st
                          INNER JOIN countries ct
                                  ON ct.id = st.country_id)r
               ON l.id = r.id
WHERE  l.id = r.id


Hope this will help you.



AngularJS Hosting Europe - HostForLIFE.eu :: Commonly Used Angular Commands

clock June 29, 2021 07:51 by author Peter

In this article, we will see what are the commonly used commands in an Angular project with the explanation. These are very useful when it comes to Angular applications.

1) To get the npm version,
npm -v

2) To get the node version,
node -v

3) To get the Angular version,
ng v

4) To get the Jasmine version,
jasmine -v

5) To get the Karma version,
karma --version

6) To install Angular CLI,
npm install @angular/cli -g
npm install @angular/cli

7) To install the next version of Angular CLI,
npm install @angular/cli@next

8) To get help in the terminal,
ng help

9) To create a new project in Angular,
ng new project-name

10) To skip external dependencies while creating a new project,
ng new project-name --skip-install

11) To run the Angular project,
ng serve (or) npm start (or) ng serve --force

12) Dry Run,
ng new project-name --dry-run

13) To create a new component in the Angular Project,
ng generate component component-name
ng g c component-name

14) To avoid creating a new folder while creating a new component,
ng generate component component-name --flat

15) To create a build,
ng build

16) To create a build for a specific environment,
ng build --prod

17) To run test cases,
ng test

18) To run the end-to-end test,
ng e2e

19) For Angular Documentation,
ng doc

20) To change the angular-cli.json config file,
ng set

21) To create a directive in Angular,

ng generate directive directive-name
ng g d directive-name

22) To create a service in Angular,
ng generate service service-name
ng g s service-name

23) To create a class,
ng generate class class-name
ng g cl class-name

24) To create an interface,
ng generate interface interface-name
ng g i interface-name

25) To create a pipe,
ng generate pipe pipe-name
ng g p pipe-name

26) To create enum,
ng generate enum enum-name
ng g e enum-name

27) To create a module,
ng generate module module-name
ng g m module-name

28) To create a spec file for the module,
ng g m module-name --spec true -d

29) To create a module with routing,
ng g m module-name --routing

30) To create a guard to the route,
ng g guard guard-name

31) To remove node_modules,
rm -rf node_modules

32) To uninstall Angular CLI,
npm uninstall --save-dev @angular/cli
npm uninstall -g angular-cli @angular/cli

33) To install the latest version of Angular CLI,
npm install --save-dev @angular/cli@latest

34) To update Angular CLI,
ng update @angular/cli
ng update @angular/core

35) To clean cache,
npm cache clean

36) To install TypeScript latest version,
npm install -g typescript@latest

37) To install Jasmine/Karma latest version,
npm install -g karma-jasmine@latest

38) To install TypeScript specific version,
npm install typescript@version-number

39) To install Jasmine specific version,
npm install -g jasmine@version-number

40) To install Karma specific version,
npm install -g karma@version-number
To update Angular versions

Steps to update particular Angular version on the current project,

Execute these commands,

ng update @angular/core@8 @angular/cli@8 --allow-dirty
npm install
git commit -a -m "Upgrade to the latest version of Angular 8"
ng update @angular/core @angular/cli --next
{ng update @angular/core@9 @angular/cli@9 --allow-dirty}
npm install
git commit -a  -m "Upgrade to Angular 9"
ng update @angular/material --next --force
npm i @angular/[email protected]

Steps to update the latest Angular version,

npm uninstall -g @angular-cli
npm cache clean
rm -rf node_modules
npm install
npm install -g @angular/cli@latest
ng update @angular/cli @angular/core
ng update --all --force
npm install --save @angular/animations@latest @angular/cdk@latest @angular/common@latest @angular/compiler@latest @angular/core@latest @angular/flex-layout@latest @angular/forms@latest @angular/http@latest @angular/material@latest @angular/platform-browser@latest @angular/platform-browser-dynamic@latest @angular/router@latest core-js@latest zone.js@latest rxjs@latest rxjs-compat@latest
npm install --save-dev @angular-devkit/build-angular@latest @angular/compiler-cli@latest @angular/language-service @types/jasmine@latest @types/node@latest codelyzer@latest karma@latest karma-chrome-launcher@latest karma-cli@latest karma-jasmine@latest karma-jasmine-html-reporter@latest jasmine-core@latest jasmine-spec-reporter@latest protractor@latest tslint@latest rxjs-tslint@latest webpack@latest



Europe mySQL Hosting - HostForLIFEASP.NET :: MySQL CASE Expression

clock June 22, 2021 08:25 by author Peter

In this tutorial, I am going to explain CASE expressions in MySQL with examples. This article will cover the following topics. Let’s see.
    Introduction
    Simple CASE Expression
    Searched CASE Expression
    Difference between SIMPLE and SEARCHED CASE Expressions
    Conclusion

In MySQL, the case expression shows multiple conditions. An expression is the compatible aggregated type of all return values, but also depends on the context. If we have to use it in a numeric context, the result is returned as a decimal, real, or integer value. You can use CASE expression anywhere in a query like SELECT, WHERE, or ORDER BY clause.

 
Note:
Note that, MySQL CASE Expressions are different from MySQL CASE Statements. MySQL CASE Statements are only used in Stored Procedures, Functions, Events, and Triggers whereas MySQL CASE Expressions are used in SELECT Queries.
 
The CASE expression has two forms
    Simple CASE Statement
    Searched CASE Statement

First, let's create a database with a few tables containing some dummy data. Here, I am providing the database with the tables containing the records, on which I am showing you the various examples. Let's see.
    CREATE DATABASE MySQL_CASEExpressions;  
      
    USE MySQL_CASEExpressions;  
      
    CREATE TABLE Bookorder(  
      BookNumber INT NOT NULL,  
      orderDate datetime NOT NULL,  
      shippedDate DATE DEFAULT NULL,  
      Status VARCHAR(50),  
      OrderAcknowledgeDate datetime,  
      PRIMARY KEY(BookNumber)  
    );


SIMPLE CASE Expressions
In the Simple Case Expressions, when “case_value” matches with its respective “value”, then it returns the corresponding “result” value. But, if the “case_value” does not match with any “value” then, it returns the “result_value”.
 
Syntax
CASE <case_value>
WHEN <value1> THEN <result1>
WHEN <value2> THEN <result2>...
ELSE <result_value> END;

 
Example 1

    SELECT CASE 10 * 2 WHEN 25 THEN 'Incorrect'  
    WHEN 40 THEN '40 Incorrect'  
    ELSE 20 END AS CASE_Result;  

Example 2
    SELECT CASE 5 * 5 - 5 / 5 + 6 WHEN 30 THEN "TRUE"  
    ELSE "FALSE"  
    END AS "Results";

Example 3
SELECT CASE 10 * 2  
WHEN 20 THEN '20 correct'  
WHEN 30 THEN '30 correct'  
WHEN 40 THEN '40 correct'  
END AS Result; 

Example 4
    SELECT BookNumber, orderDate,  
    CASE Status  
    WHEN "Done"  
    THEN "Product_Shipped"  
    WHEN "In Progress"  
    THEN "Product_Not_Shipped"  
    END AS ProductStatus  
    FROM mysql_caseexpressions.bookorder; 


Example 5 – With Aggregate Function
    SELECT SUM(CASE Status WHEN 'Done'  
        THEN 1 ELSE 0 END) AS 'Product_Shipped',  
      SUM(CASE Status WHEN 'In Progress'  
        THEN 1 ELSE 0 END) AS 'Product_Not_Shipped',  
      COUNT( * ) AS TotalOrders  
    FROM Bookorder;


SEARCHED CASE Expressions
In the Searched Case Expressions, CASE evaluates the “expressions” values that are specified in the WHEN clause and returns the corresponding “result_set” value. But, if any value is not satisfied by the corresponding conditions then, it returns the “result_value” that is specified in the ELSE clause.
 
Syntax
CASE
WHEN <expression1> THEN <result_set1>
WHEN <expression2> THEN <result_set2> …
ELSE <result_value>
END
 

Example 1
    SELECT CASE WHEN 10 * 2 = 25 THEN 'Incorrect'  
    WHEN 10 * 2 = 40 THEN '40 Incorrect'  
    ELSE "Should be 10*2=20"  
    END AS SEARCHED_CASE_Result; 

Example 2
    SELECT CASE WHEN 5 * 5 - 5 / 5 + 6 = 30 THEN "TRUE"  
    ELSE "FALSE"  
    END AS SEARCHED_CASE_Result; 

Example 3
    SELECT CASE WHEN 10 * 2 = 20 THEN '20 correct'  
    WHEN 10 * 2 = 30 THEN '30 correct'  
    WHEN 10 * 2 = 40 THEN '40 correct'  
    END AS SEARCHED_CASE_Result; 

Example 4
    SELECT BookNumber, orderDate,  
    CASE WHEN Status = "Done"  
    THEN "Product_Shipped"  
    WHEN Status = "In Progress"  
    THEN "Product_Not_Shipped"  
    END AS ProductStatus  
    FROM mysql_caseexpressions.bookorder; 

Example 5 – With Aggregate Function
    SELECT SUM(CASE WHEN Status = 'Done'  
        THEN 1 ELSE 0 END) AS 'Product_Shipped',  
      SUM(CASE WHEN Status = 'In Progress'  
        THEN 1 ELSE 0 END) AS 'Product_Not_Shipped',  
      COUNT( * ) AS TotalOrders  
    FROM Bookorder; 

Difference between SIMPLE and SEARCHED CASE Expressions
 
Example 1
    SELECT CASE WHEN 10 * 2 = 20 THEN '20 correct'  
    WHEN 10 * 2 = 30 THEN '30 correct'  
    WHEN 10 * 2 = 40 THEN '40 correct'  
    END AS SEARCHED_CASE_Result,  
      
    CASE 10 * 2  
    WHEN 20 THEN '20 correct'  
    WHEN 30 THEN '30 correct'  
    WHEN 40 THEN '40 correct'  
    END AS SIMPLE_CASE_Result; 

Example 2
    SELECT BookNumber, orderDate,  
    CASE Status  
    WHEN "Done"  
    THEN "Product_Shipped"  
    WHEN "In Progress"  
    THEN "Product_Not_Shipped"  
    END AS ProductStatus  
    FROM mysql_caseexpressions.bookorder;  
      
    SELECT BookNumber, orderDate,  
    CASE WHEN Status = "Done"  
    THEN "Product_Shipped"  
    WHEN Status = "In Progress"  
    THEN "Product_Not_Shipped"  
    END AS ProductStatus  
    FROM mysql_caseexpressions.bookorder; 

 



AngularJS Hosting Europe - HostForLIFE.eu :: Mocking A REST API For Your Front-End Application

clock June 18, 2021 08:47 by author Peter

In this article, we'll talk about how to mock a REST API for your front-end application which you can easily consume in Angular, React, and Vue Js.

We're going to use open source packages, JSON-server, and faker.js.

In this article, we are setting up mocking a REST API for Angular applications.

Here we assume that you are already aware of how to set up the Angular project.

After setting up the Angular project, a question arises: Why we are mocking a back-end for our front-end application, or in other words, what's the need for that?

Let's talk about that in detail.

Nowadays modern web development applications involve multiple developers working separately in front-end and back-end applications. A few challenges that might arise are coordination between back-end developers and front-end development teams, there is also a chance that the backend is not ready and frontend developers get stuck. Here, JSON-Server plays an important role that this tool allows you to spin up a REST API server with fully-working API with zero codings.
Mock A REST API

Let's now mock up a REST API using JSON-server.

Step 1

Install JSON-Server inside your Angular application
npm install json-server  --save

After Installing JSON-server set up data objects.

Step 2

Create a data.json file inside a database folder.

Step 3

Inside the data.json file create an object.
{
  "products" : []
}


JavaScript

Now we need data for the object that you created that will return from endpoints.

Here we are going to use Faker.js.

Faker.js is the tool for generating a large amount of realistic data in no time.

Install Faker inside your angular application.

npm install faker --save

Create a separate file fakedata.js.

Add the following script inside fakedata.js,

var faker = require('faker');

var database = { products: []};

for (var i = 1; i<= 500; i++) {
  database.products.push({
    id: i,
    name: faker.commerce.productName(),
    description: faker.lorem.sentences(),
    price: faker.commerce.price(),
    imageUrl: "https://source.unsplash.com/1600x900/?product",
    quantity: faker.random.number()
  });
}


console.log(JSON.stringify(database));

JavaScript
Now we need to run this so that we can use this data as an endpoint.

Let's add the script for data and JSON-server into the package.json file,
{
  "name": "angularapp",
  "version": "0.0.0",
  "scripts": {
    "ng": "ng",
    "start": "ng serve",
    "build": "ng build",
    "watch": "ng build --watch --configuration development",
    "generate": "node ./fakedata.js > ./database/data.json",
    "server": "json-server --watch ./database/data.json",
    "test": "ng test"
  },


JavaScript
Now, open your terminal, and let’s create some data for our REST API by running the below command,

 npm run generate

In the above screenshot, you will see the data.json file contains data.

Final step, let's run the REST API using the following command into your terminal,

npm run server

We will see the output in the terminal, Now the REST API can access using the URL which shows in the terminal.

http://localhost:3000

and Get Resources on,

http://localhost:3000/products

You can access all API Endpoints like GET, POST, PUT, PATCH, DETELE with angular HttpClient, and you can also use page and limit parameters to get data by pages, by setting up the header of the HTTP response.



Europe mySQL Hosting - HostForLIFEASP.NET :: Create A Linked MySQL To SQL Server

clock June 14, 2021 08:06 by author Peter
While working on one of my projects, I came across a scenario where I had a database of the client's that was provided by some other provider through their application. I had to get data from that database, and using that data I had to do some calculations on that and store the results in my database. There were two scenarios in this case:

  1. I could fetch all the required tables and data from that database and create my own database and dump those details into mine and then use it.

  2. I could create a link between my database and the existing database, so that I could fire queries directly on that database.

    Using the first approach will not give me updated records at any point of time but my scenario was real time data. So I thought of using a second approach. This approach gave me real time data as I was querying the existing data and using it. But there is one drawback: It might be somewhat slow. In this article I will explain how to create a linked server
    in SQL Server. Here I will be using ODBC Driver to fetch data from MYSQL database.

    The following are the steps to connect a MySQL database to a SQL Server:


    First of all we need to install the appropriate MySQL ODBC Driver based on the operating system from the below link. After the driver has been installed go to Control Panel, Administrative Tools, then Data Sources(ODBC). After that click System DSN. Now Press Add Button .

    Select MYSQL Driver Listed(MYSQL(ODBC) 5.3 ANSI Driver) and click finish. This will open up MySQL Configuration window.

    Fill Data Source Name as MYSQL (this can be anything). TCP/IP Server as localhost. Port as 3306(default port for mysql), User Name-root, Password -your database password and click test. This will show a success message. Now select database and click ok.

We are done with MYSQL System DSN. Now we will set Linked Server to MYSQL in SQL Server. Open SQL Server, Server Objects, then Linked Server. Right Click on Linked Servers, then Add New Linked Server.

This will Open up a Linked Server Properties Dialog. Fill Linked Server as MYSQL_LINKED, select Provider as Microsoft OLEDB Provider For ODBC Drivers. Product Name as MySQl, DataSource as MySQL_Linked (whatever name is given while creating DSN). Provider String as,

DRIVER=(MySQL ODBC 5.2 ANSI Driver);SERVER=localhost;PORT=3306;DATABASE=databasename; USER=username;PASSWORD=password;OPTION=3;  

Leave location as blank and Catalog as database name (in mysql). 

Drill down to Server Object, then Linked Servers, Providers, right-click MSDASQL, and select “Properties”. The Provider Options for Microsoft OLE DB Provider for ODBC Drivers dialog box will open allowing you to configure several options. Ensure the following four options are checked:
Nested queries

Level zero only

Allow inprocess

Supports ‘Like’ Operator

All other options should be unchecked. When done, click “OK”.

In addition to this, you can enable provider options on the SQL OLEDB, In my case I select the Dynamic Parameter and Allow in process.
We are done with setting up a linked server. Now we have to test it by firing some basic queries. There are three ways by which we can query a linked server.

    Open Query
    Select using 4 part notation.
    Execute Function

Open Query function requires 2 parameters: 1)Linked Server Name, 2)Query
    select * from openquery (MYSQL_LINKED, 'select * from test.user_details');  
    INSERT OPENQUERY (MYSQL_LINKED, 'select name,address from test.user_details') VALUES ('Peter','Amsterdam');  
    UPDATE OPENQUERY (MYSQL_LINKED, 'select name from test.user_details WHERE user_id = 100006413534648') SET name = 'Scott';  
    DELETE OPENQUERY (MYSQL_LINKED, 'select name from test.user_details WHERE user_id = 100006413534648')  


Note:

For Update/Delete on Linked Server we need to set RPC and RPC OUT properties of Linked Server as true (Right click Linked Server, Properties, Server Option Tab, RPC-True, then set RPC OUT -True.
 
Part Notation: We can also execute queries on linked server using four-part notations like:

SELECT * FROM linkedserver...tablename but for this we need to change MSDASQL Provider property. Check the box that says “level zero only” in providers.
    select * from MYSQL_LINKED...user_details  
    INSERT into MYSQL_LINKED...user_details(name,address) VALUES ('Rajeev','Bangalore');  
    UPDATE MYSQL_LINKED...user_details set name='Akash' where USER_ID='100006413534649';  
    DELETE from MYSQL_LINKED...user_details where USER_ID='100006413534649';  


Execute Function can also be used for querying linked server.
    EXECUTE('delete from test.user_details WHERE user_id = 100006413534647') AT MYSQL_LINKED 



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