Full Trust European Hosting

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

AJAX Hosting - HostForLIFE :: Learn About AJAX Security

clock March 17, 2022 07:42 by author Peter

The advent of Web 2.0 brought about a new technique in building web applications, Asynchronous, JavaScript, and XML. AJAX is a faster and interactive technology that has found great favor among modern businesses today. With it comes a combination of JavaScript, HTML, CSS, and XML to build one useful technique that makes web application interactivity faster and affordable in terms of bandwidth consumption. This article is a description of AJAX and its security issues.

AJAX
Conventional web sites were known to be slower and consumed more bandwidth because of the way they connected to the server. It would take a page to reload to connect to the server using synchronous connection. This meant more bandwidth consumption and slower response from web applications. On the other hand, AJAX is a browser technology that uses asynchronous means to communicate to the server. This means that you can communicate with the server to update certain portions of a page without having to reload the whole page.
 
A good example of AJAX in use is the Google create account page which recognizes a username in use soon after a user enters their suggested username. This means that in the background the page has communicated with the Google server to check if the name exists and show results without having to reload the entire page.
 
It is considered the most feasible Rich Internet Application (RIA) to date. AJAX makes use of Open Standards that include HTML and CSS for the presentation of data, XML for data storage and transfers to and from the server, XMLHttpRequest objects in the browser to fetch data from the server, and finally JavaScript for interactivity. AJAX can also transfer data in JSON or plain-text.
 
Security Issues with AJAX
AJAX applications only use a different technique to connect to the server. However, they use the same security schemes to connect to the server. This entails that you still have to include your authentication, authorization, and data protection methods in the web.xml file or program. AJAX applications bear the same vulnerabilities as ordinary or conventional web applications. In as much as people prefer the swiftness and the advanced interactivity of AJAX applications, some are misled to believe that AJAX web applications are more secure than ordinary web applications.
 
AJAX applications are known to have session management vulnerabilities and a lot of loopholes in the hidden URLs which carry AJAX requests to the server.
 
The AJAX engine makes use of JavaScript to transfer user requests/commands and transforms them into function calls. The AJAX engine sends these function calls in plain-text to the server that may be intercepted by attackers to reveal database information, variable names, or any other confidential user data that may be used by the attacker maliciously.
 
AJAX-based applications are also vulnerable to Cross-Site Request Forgery (CRSF) and Cross-Site Scripting (XSS). Although it is not that easy to exploit CSRF on AJAX applications because the requests are hidden, attackers may be able to create a script that can steal a user’s session token and by so doing be able to steal the user’s session remotely.
 
This can be avoided by creating random complex tokens for the AJAX requests which are not identified by the attackers. The server embeds the complex token on the page and checks for it each time the users make a request to the server and if it is any different the server does not process the request.
 
To ensure AJAX security against XSS, the application has to strictly sanitize user input and output. The use of JS functions such as ‘document.write()’, ‘innerHTML()’, ‘eval()’, ‘write()’ may make it possible for XSS attacks in AJAX web applications.
 
Conclusion

AJAX is a very fast and affordable browser technology but needs to be treated just like any other web application when it comes to security. Organizations need to do thorough scanning of their AJAX applications just like on conventional web applications to ensure absolute security from common vulnerabilities.

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.

 



Node.js Hosting Europe - HostForLIFE :: How To Work With File System Module In Node.js

clock March 11, 2022 07:52 by author Peter

Node file system helps us to access the files and also interact with files in our system. Node.js’s file system module is also known as "fs" module. We don’t need to install it explicitly as it comes with Node.js core. We can use the fs module as
var fs = require('fs');

File system module can be used for file operations like creating, reading, deleting, etc. The operations that we need to perform can have synchronous and asynchronous forms depending on our requirements.

Common use cases of File System module:
    Write Files
    Read Files
    Delete Files
    Append Files
    Close Files

Read File
To read the file from our system, fs.ReadFile() function is used. fs.readFile() is a built-in function used to read files located in our system with the syntax given below

Syntax
fs.readFile( filename, encoding, callback_function )

In the parameters, we can provide a filename as the name of the file if it is located in the same directory and a full path if the file is located on locations other than the same directory. Encoding has the encoding value of the file, by default the value of encoding is utf8.

The callback function is the function that is called once the file is read. This function takes two parameters first is err and the other is data. Err indicates if any error has occurred during reading the file and data contains the content of the file.

To create a demo for this function let's create a text file. Create a text file named “FirstFile.txt” with “My First File.” as content.

Now let's create a file named “FileRead.js”, to read the contents of the text file that we created.

Example
var http = require('http');
var fs = require('fs');
http.createServer(function (req, res) {
  fs.readFile('FirstFile.txt', "utf-8" , function(err, data) {
    res.writeHead(200, {'Content-Type': 'text/html'});
    res.write(data);
    return res.end();
  });
}).listen(8080);
console.log("File Read!");


Note
If the output is undefined it means the file is null. It starts reading the file and simultaneously executes the code. The function will be called once the file has been read meanwhile the ‘File Read!” statement is printed then the contents of the file are printed.

Initiate the file
node .\FileRead.js

Opening the localhost, we will be able to read the contents of the file as shown below,

Create File
Creating files using node.js can be done through many approaches. Some of the methods that can be used are appendFile(), open(), or  writeFile(). Let’s look into the details of each function and when to use it.
fs.appendFile()

The fs.appendFile() method of Node.js is used to synchronously append the data to the file, if the file doesn’t exist then a new file will be created with the content specified.

Syntax
fs.appendFile(filepath, data, options, callback);

In the parameters, filepath will be the path of the file provided as a string, parameter data is the data that we need to append to the file, options specifies the flag/encoding/mode and the callback is a function that is called when the data is appended to the file.

Example
var fs = require('fs');
fs.appendFile('AppendFile.txt', 'Append File demo!', function (err) {
  if (err) throw err;
  console.log('Content appended/file created.');
});


Initiate the file:

A new file named 'AppendFile.txt' will be created if it doesn’t exist and if the file exists the text provided in the code will be appended.
fs.open()

The fs.open() method is used to create, read, or write a file. Writing to a file using open() method depends on the second parameter flag, passed to the method. If we pass the parameter as “w” then the specified file is opened for writing. If the file doesn’t exist then a new blank file is created with the name specified.

Syntax
fs.open(path, flags, mode, callback)

The parameters path holds the name of the file if the file is located in the same directory and it contains the entire path if the file is located at other locations.

Mode sets the mode of the file for example r-read, w-write, r+ -readwrite, etc. The default value of the mode is readwrite.

The parameter flag indicates the behavior of the file to be opened. The values that we can provide for the value of flag parameter are r, r+, rs, rs+, w, wx, w+, wx+, a, ax, a+ or ax+.

The callback function is the function that is called after reading the file.

Let’s try to create a blank file using the open method of the fs module of Node.js.
var fs = require('fs');
fs.open('OpenFile.txt', 'w', function (err, file) {
  if (err) throw err;
  console.log('New file created!');
});


Initiate the file,

The fs.readFile() method is used only for reading the file and fs.writeFile() method is only for writing to the file, whereas fs.open() method does several operations on a file such as creating, reading, or writing.
fs.writeFile()

The method WriteFile() replaces the specified file and content if the file already exists. If the file doesn’t exist, then a new file will be created with the content as provided. This method is used to asynchronously write the specified data to a file.

Syntax
fs.writeFile(path, data, options, callback)

The path parameter here can be a string, Buffer, URL, or file description integer that denotes the path of the file where it has to be written. Using a file descriptor will make it behave similarly to fs.write() method.

Example
var fs = require('fs');
fs.writeFile('WriteFile.txt', 'New file created with content!', function (err) {
  if (err) throw err;
  console.log('File created and saved!');
});


Initiate the file,

Update Files
To update the files there are some methods from the file system module that can be used.
Methods that can be used for updating the files are fs.appendFile() and fs.writeFile().

As we already have the description of the function fs.appendFile() in the create file section, let’s have a look at an example.
var fs = require('fs');
fs.appendFile('AppendFile.txt', ' Appended text...', function (err) {
  if (err) throw err;
  console.log('Updated!');
});


Initiating this file will append the data to the existing file.

For details of the fs.writeFile() function please refer to create file section. Looking at an example of fs.writeFile() function:
var fs = require('fs');
fs.writeFile('WriteFile.txt', 'File with name WriteFile updated.', function (err) {
  if (err) throw err;
  console.log('File updated and saved!');
});


Initiating the file replaces the specified file and the contents will be updated and the file will be saved.

Delete Files
To delete files using Node.js, we can use the method fs.unlink(). This function is used to remove a file, it doesn’t work on deleting directories. To delete directories we can use the method fs.rmdir().

Syntax
fs.unlink(path, callback)

Here in this method we need to pass two parameters first is the path of the file that we need to remove, it can be string, Buffer, or URL. And another parameter is the callback. The callback is a function that would be called when the method is executed.

Example
var fs = require('fs');
fs.unlink('SampleFile.txt', function (err) {
  if (err) throw err;
  console.log('SampleFile deleted...');
});


Initiating the file, the file that we mentioned in the code will be deleted.

Rename Files
We can also rename the file names using Node.js and to rename the file names we can use the function fs.rename(). The function will be used to rename the file at oldPath to the pathname provided as newPath.

The parameters used to rename the file are oldpath, newpath, and the callback function. Here old path will be the path of the file that already exists, a new path will be the new name of the file that we want to replace the old file name with. And the callback function will be the function that will be called when the method is executed.

In the case that newPath already exists, it will be overwritten. If there is a directory at newPath, an error will be raised instead. No arguments other than a possible exception are given to the completion callback.

Example
var fs = require('fs');
fs.rename('SampleFile.txt', 'SampleFileRenamed.txt', function (err) {
  if (err) throw err;
  console.log('SampleFile File Renamed!');
});

Initiating the file, the old file will be replaced with the new file name provided.

After going through this article and performing the code snippets provided you will be able to work with all the basic file operations such as create, update, delete and rename. Please feel free to post the feedback if any and let me know if you want me to work on any content that would help to learn Node.js further.



AngularJS Hosting Europe - HostForLIFE :: Call Parent Method From Child Component And Child Method From Parent Component

clock March 10, 2022 07:42 by author Peter

In this article, I will discuss how to call child component method from parent component and parent component method from child component. For this article, I have created a demo project using Angular 12. In this demo project, I will create a simple parent and child component and I will demonstrate to call both methods vice versa.


First of all, we have created a project using the following command in the Command Prompt.
ng new myApp

Open project in visual code studio using following command
> cd myApp
> Code .

Call Child Component method from Parent Component
We can use Viewchild to call Child Component method from Parent Component

Viewchild
A ViewChild is a decorator which is used when we want to access a child component inside the parent component, we use the decorator @ViewChild() in Angular.

Here I have declared a variable name child as decorator @ViewChild(). As shown below we can access childMethod of child component inside the parent component.

Use following code for parent component
@ViewChild(ChildComponent ) child !:any ;

callChildMethod() {
   this.child.childMethod("Hello Dear, Parent Method is Called")
 }

Use following code for child component
childMethod(msg: string) {
  this.childmsg=msg;
}


Call Parent Component method from Child Component
For Calling Parent Component method from Child Component, I had created a method getParentMethod and in this method, I had set input property in HTML file of parent component. Then shown as below code inside the child component I am able to access parent method.

Use following code for parent component
getParentMethod():any {
   return {
     callParentMethod: (name:any) => {
       this.parentMethod(name)
     }
   }
 }

 parentMethod(name: string) {
   this.parentMsg=name;
 }

Use following code for child component

@Input() parentApi !: any;

callParent() {
  this.parentApi.callParentMethod("Hello Dear, Child Method is Called")
}

App.component.html
<button (click)="callChildMethod()">call child</button>
<p>{{parentMsg}}</p>
<hr/>
<app-child [_pData]="getParentMethod()"></app-child>


App.component.ts
import { Component, OnInit, ViewChild } from '@angular/core';
import { ChildComponent } from './child-component/child.component';

@Component({
  selector: 'app-root',
  styleUrls: ['./app.component.css'],
  templateUrl: './app.component.html'
})
export class AppComponent implements OnInit {
  parentMsg='';
  @ViewChild(ChildComponent ) child !:any ;

  ngOnInit(): void {
  }

  constructor() { }

  getParentMethod():any {
    return {
      callParentMethod: (name:any) => {
        this.parentMethod(name)
      }
    }
  }

  parentMethod(name: string) {
    this.parentMsg=name;
  }

  callChildMethod() {
    this.child.childMethod("Hello Dear, Parent Method is Called")
  }
}

child.component.html
<button (click)="callParent()">call parent</button>
<p>{{childmsg}}</p>

child.component.ts
import { Component, Input, OnInit } from '@angular/core';

@Component({
  selector: 'app-child',
  templateUrl: 'child.component.html',
  styleUrls: ['./child.component.css']
})
export class ChildComponent {

  @Input() _pData !: any;
  childmsg='';

  constructor() { }

  callParent() {
    this._pData.callParentMethod("Hello Dear, Child Method is Called")
  }

  childMethod(msg: string) {
    this.childmsg=msg;
  }
}


Now, run the project using the following command.
ng serve




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 Visual Studio 2022 Hosting - HostForLIFE :: Hidden Features Of Visual Studio That Developer Should Know

clock February 8, 2022 06:46 by author Peter

Most of the .NET developers are using Visual Studio IDE for their development. The Visual Studio IDE has a lot of cool hidden features. Most of the developers are not aware of these features. In this article, we are going to explore hidden features available in Visual Studio.

1) Track active document in the solution
While working on the large solution (which has several numbers of projects), tracking of current opening file in the solution is difficult. If we want to track, then we have to scroll the entire solution explorer to find out the working files or search for a specific file inside solution explorer. It is too difficult and also time-consuming process. But Visual Studio has tracking feature which helps us to understand where we are in the solution/projects.

Visual Studio can automatically highlight the active/working files in the solution by clicking on the "Sync with Active Document" option in the top bar of the solution explorer.

Disadvantage of the above approach is every time we have to manually click this option to track files. Then how to do it automatically without manual action? Yes!!!! Visual Studio has that feature also. Cool.

Follow the below steps to enable the auto tracking feature.

Step 1
Go Tools -> Options

Step 2
Select Projects and Solutions -> General on the left pane

Step 3
Select the option "Track Active Item in Solution Explorer"

This will track your current working files automatically in the solution explorer.

2) Copy multiple items to the clipboard
Mostly if we want to copy multiple lines of code from different places and paste them in a single place or when we needed, then mostly we would copy and paste one by one. It is always affecting our productivity. Then, how to copy multiple code block, and paste them as and when needed? This is another hidden feature of Visual Studio. This built-in feature is known as “Clipboard Ring”. Just cut/copy the code blocks which are stored in a memory and you can use them later by pasting.

How it works?
    Copy (ctrl + c) / Cut (ctrl + x) the number of code blocks.
    Press ctrl+shit+v Option. A small pop-up window is displayed with all copied items. You can choose which one wants to paste.
    Use the same key set to paste the copied items. The clipboard store only the last 15 copied items in the memory.

3) Separate and Maintaining the pinned tabs in Visual Studio
Most of the times we have pinned the frequently used files. Even if pinned the files, those files are aligned with other opened files in a single row. So, it is difficult to maintain/track the pinned files with other files. Pinned Tabs are very useful features in Visual Studio where we can maintain the pinned files in a separate row and refer them quickly.

Go to Tools -> Options -> Environment -> Tabs and Windows and checked the  "Show pinned tabs in separate row" option.

4) Use "Run To Cursor" and save time while debugging
It is another cool hidden feature which can improve productivity while debugging. If we want to stop the debugger in a particular line then most of us add the breakpoint and run the application. So, the debugger will stop on the targeting line. Is it possible to reduce the work? Yes. We can.

"Run to Cursor" is just like another breakpoint, but in this case, we don’t need to start the Visual Studio debugger manually and the breakpoints are cleared when it’s hit. When you select the "Run to Cursor" option, visual studio starts the debugger automatically and stopped on the selected line.

Right click on the line where you want to stop the debugger, select the "Run to Cursor" option from the context menu. The Visual Studio starts the application and it will stop on the line you had selected. From here we can continue the debugging. Shortcut for this option is "ctrl + F10".

5) Open the application in the multiple Browsers
While working on the web application (mostly front-end), we want to test the application in different browsers. When we run the application, it will open in the default browser. Most of the time we manually copied the URL and opened it in another browser. Do you think, is this improve our productivity? No Definitely Not. Visual Studio has the option to run the application in different browsers with just a single click.

Follow the below steps to open the application in multiple browsers.

Step 1

Click on run dropdown -> Web Browser -> Click "Select Web Browsers... " option.

Step 2
The Browser option window will be displayed. Select the browser which you want to test and click OK.

Step 3
Hit the ctrl+ F5 or select "Start Without Debugging" option under the Debug menu. The application will be opened with all selected browsers.

 

6) Convert JSON And XML Object Into Class
Visual Studio has a super cool feature which is to generate the classes from a JSON/XML object using just copy-paste. Please refer to my other article about the details of this feature.

In this article, we have learned about various Visual Studio hidden features which help us to improve our productivity.



AngularJS Hosting Europe - HostForLIFE :: Angular *ngIf Offers Much More Than Just An IF Condition

clock January 27, 2022 07:16 by author Peter

You might feel that there are plenty of articles around which discuss about *ngIf directive in angular - why another article?. The reason I wanted to write this article is :

Many of the articles discuss how to add/remove an element based on the IF condition and do not explain how to write ELSE part and how PIPES can be used with *ngIf.

Let's take one example scenario and see  different ways to implement it

Scenario
    Display 'Login' and 'Signup' buttons when user is not logged in
    Display 'Hello user' message and a  'Logout' button when user is already logged in

Approach #1:  Using only IF condition
<div *ngIf="isLoggedIn">    <!-- If user is logged in -->
  <label class="mr-2">Hello, User!</label>
  <button class="btn btn-primary" (click)="isLoggedIn = !isLoggedIn">
    Logout
  </button>
</div>
<div *ngIf="!isLoggedIn">  <!-- If user is NOT logged in -->
 <button class="btn btn-default mr-2" (click)="isLoggedIn = !isLoggedIn">
  Login
</button>
<button class="btn btn-primary">Signup</button>
</div>


As you can see, we are using just two IF conditions ( *ngIf=isLoggedIn   and *ngIf=!isLoggedIn ) here.

Approach #2:  Using  IF / ELSE condition
<div *ngIf="isLoggedIn; else loggedOut">  <!-- If NOT logged in use #loggedOut template-->
<label class="mr-2">Hello, User!</label>
<button class="btn btn-primary" (click)="isLoggedIn = !isLoggedIn">
  Logout
</button>
</div>
<ng-template #loggedOut>     <!-- loggedOut template -->
  <div>
  <button class="btn btn-default mr-2" (click)="isLoggedIn = !isLoggedIn">
  Login
</button>
<button class="btn btn-primary">Signup</button>
 </div>
</ng-template>

So, in the above case, we are using an IF / ELSE condition.  If the user is logged in, the div content will be shown, else it will show the content of ng-template ( identified by template reference -  #loggedOut  )

Approach #3:  Using  IF THEN / ELSE condition
<div *ngIf="isLoggedIn; then loggedIn; else loggedOut"></div>   <!-- If logged in, then use loggedIn template, else use loggedOut template -->

<ng-template #loggedIn>  <!-- loggedIn template-->
  <div>
 <label class="mr-2">Hello, User!</label>
<button class="btn btn-primary" (click)="isLoggedIn = !isLoggedIn">
  Logout
</button>
  </div>
</ng-template>

<ng-template #loggedOut>  <!-- loggedOut template -->
  <div>
    <button class="btn btn-default mr-2" (click)="isLoggedIn = !isLoggedIn">
      Login
    </button>
    <button class="btn btn-primary">Signup</button>
  </div>
</ng-template>


In the above case, we have created two templates ( one for login and the other for logout ), which looks pretty clean compared to other two approaches

There is NO performance benefit of using one approach over the other. It is just that the code looks clean and more readable when you use apporach #3  in case you want to implement IF/ ELSE.

Before we wrap-up, let's see how we can use *ngIf with Pipes.

Scenario :

Display Bitcoin price with the ability to refresh

Implementation :
    We will make a HTTP request to one of the public APIs available ( https://api.coindesk.com/v1/bpi/currentprice.json )  to get the bitcoin price.
    We will show 'Please wait...' message till we get the response
    Once we get the response, we will remove the message and show the bitcoin price
    Please note that am using the above api just for DEMO purpose here - not sure whether that can be used for real-time purposes. Please do a research before you use it for any other purposes. More free APIs can be found here : https://apipheny.io/free-api/
import { delay, Observable } from 'rxjs';

@Component({
  selector: 'ng-if',
  templateUrl: './ngif.component.html',
  styleUrls: ['./ngif.component.css'],
})
export class NgIfComponent {
  isLoggedIn = false;
  bitcoinData: Observable<any>;

  constructor(public http: HttpClient) {
    this.getBitcoinData();
  }

  getBitcoinData() {
    // Below API is used for DEMO purpose. Please do research before you use it for any other purposes.
    this.bitcoinData = this.http
      .get('https://api.coindesk.com/v1/bpi/currentprice.json')
      .pipe(delay(3000));
  }
}

<div id="bitCoinCont">
  <span *ngIf="bitcoinData | async as data; else loading"> <!-- the async pipe here ensures that the content of the span element will be rendered only after bitcoin data is fetched -->
    {{ data['bpi']['USD']['rate'] }}
  </span>
  <button class="btn btn-primary" (click)="getBitcoinData()">Refresh</button>

  <ng-template #loading>Please wait...</ng-template> <!-- Loading template - displays Please wait.. -->
</div>

Please notice the *ngIf directive above. The async pipe subscribes to the bitcoinData oservable and once the data is available, it will be stored in data. And we are using the properties of data inside span element. The async pipe with *ngIf here ensures that the content of span will be rendered only when the data is available in data variable. Till then, it loads the #loading template.



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 Visual Studio Hosting - HostForLIFE :: How To Install Visual Studio Code?

clock January 4, 2022 08:20 by author Peter

Visual Studio Code is a lightweight but powerful source code editor which runs on your desktop and is available for Windows, macOS and Linux. It comes with built-in support for JavaScript, TypeScript and Node.js and has a rich ecosystem of extensions for other languages (such as C++, C#, Java, Python, PHP, Go) and runtimes (such as .NET and Unity).

In this article, will see how to install Visual Studio Code on your PC.

Follow the below steps for the same.

Step 1
Click here to navigate to Visual Studio Code official website.



Step 2
Click on Download for Windows.



Step 3
VSCodeUserSetup-x64-1.62.3.exe will be downloaded to your Downloads folder.

Step 4
Go to the Downloads folder and double click on the executable file.



Step 5
Click on I accept the agreement and Click on Next.

Step 6
Click on Next.


Step 7
Click on Next.

Step 8
Select Add “Open with Code” action to Windows Explorer file context menu and Add “Open with Code” action to Windows Explorer directory context menu, checkboxes.
Click on Next.



Step 9
Click on Install.

Installation is in progress.

 

Step 10
Click on Finish to launch the Visual Studio Code.


Step 10
Click on Finish to launch the Visual Studio Code.

Visual Studio Code is launched.

Hope you have successfully installed Visual Studio Code on your PC.
Please like and share your valuable feedback on this article.



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 VB.NET Hosting - HostForLIFE :: Namespace Aliases In Visual Basic .NET

clock December 17, 2021 08:28 by author Peter

In Visual Basic .NET, it is possible to declare aliases for namespaces, giving the possibility of using more concise declarations, if the developer desires to do so.

Let's see an example: Typically, the use of StringBuilder class could follow the following three declarative ways:

Without Imports statement

    Dim s As New System.Text.StringBuilder("test")  
    s.Append("123")  

This kind of implementation requires the developer to declare the "s" variable writing down the path to the desired class, in our case StringBuilder, contained into System.Text namespace.

With Imports statement
    Imports System.Text  
    ' ...  
    Dim s As New StringBuilder("test")  
    s.Append("123")  


Using an Imports statement, the programmer can simply use the classes names, for the namespace(s) to be used will be declared at the beginning of the code.

Using Aliases
    Imports sb = System.Text.StringBuilder  
    '...  
    Dim s As New sb("test")  
    s.Append("123")  


The Imports statement could be implemented with customized names. In the example above, I have stated that in the rest of the code, the class System.Text.StringBuilder will be redefined as "sb". So, we can declare a new StringBuilder with the function "New sb()", accessing the same constructors possessed by System.Text.StringBuilder, being sb a simple alias of the real thing.



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