Full Trust European Hosting

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

AngularJS Hosting Europe - HostForLIFE.eu :: How to Deploy an Angular app to Firebase?

clock July 5, 2023 09:44 by author Peter

In this article, we are going to discuss a few things about Firebase and the deployment of Angular applications. Firebase is a mobile and web development platform that provides a wide range of tools and services to help developers build high-quality applications. It was originally developed by Firebase Inc., a startup founded in 2011, and was later acquired by Google in 2014.


Features of Firebase

  • Real-time Database: Firebase provides a cloud-hosted NoSQL database that allows developers to store and sync data in real-time across multiple clients. It uses a JSON-based data model and provides powerful querying capabilities.
  • Authentication: Firebase offers authentication services, enabling developers to easily add user authentication to their applications using email and password, social media logins (such as Google, Facebook, and Twitter), and other identity providers.
  • Cloud Functions: Firebase allows developers to write and deploy serverless functions that run in response to events triggered by Firebase services or HTTP requests. This feature enables developers to extend the functionality of their applications without managing servers.
  • Cloud Storage: Firebase provides secure and scalable cloud storage for developers to store and serve user-generated content like images, videos, and other files. It offers simple APIs for uploading, downloading, and managing files.
  • Hosting: Firebase Hosting allows developers to deploy and host their web applications quickly and securely. It provides a global content delivery network (CDN) to deliver static assets and dynamic content to users with low latency.
  • Analytics: Firebase Analytics provides detailed insights into user behavior and app usage. It helps developers track key metrics, understand user engagement, and make data-driven decisions to optimize their applications.
  • Performance Monitoring: Firebase Performance Monitoring helps developers gain insights into the performance of their applications. It provides real-time monitoring, tracks network requests, and identifies performance bottlenecks.

Register an Application on Firebase

Step 1
Open the following Firebase URL:
https://console.firebase.google.com/u/0/

Step 2
Add a new project.

Step 3
Configure the project name and Google Analytics with some default settings.

Step 3
Configure the project name and Google Analytics with some default settings.

 

 

 

Step 4
Register your application after clicking on the web symbol and copying the project ID that we need for deployment.

 

Create an Angular Demo Application

Step 1
Create a new angular application.
    ng new angular-firebase-deployment

Step 2
Build and run the application.
    ng serve

Step 3
Install the Firebase tool.
    npm install -g firebase-tools

Step 4
Login to the Firebase.
    firebase login

Step 5
Initialize the firebase in your current application.
    firebase init

Firebase CLI will ask you a few questions.

Which Firebase CLI features do you want to set up for this folder?
Press space to select the required feature, then enter to confirm your choices.
Select a default Firebase project for this directory: angular-demo-5658b
Here I selected angular-demo-5658b, which I created earlier.
What do you want to use as your public directory? (public) dist/angular-firebase-deployment
configure as a single-page app (rewrite all URLs to /index.html)? (y/N) Yes
The File dist/angular-firebase-deployment/index.html already exists. Overwrite? Yes
If you select Configure files for Firebase Hosting and (optionally) set up the GitHub Action Deploy option from the list at the initial level, then you need to have a repository on GitHub, and then only you can set up and configure workflow after giving access to that particular repository.


 

Create a production build using the following command:
    ng build –aot

It will create one dist folder in your project solution. dist/angular-firebase-deployment

Step 7
Execute the following command to deploy your Angular application on Firebase:
    Firebase deploy

Step 8
Finally, open the browser and open the hosting URL.




AngularJS Hosting Europe - HostForLIFE.eu :: Simplifying Usage of trackBy in Angular Directives for Effective Item Tracking

clock June 20, 2023 10:23 by author Peter

When working with lists and data rendering in Angular, it is essential to efficiently maintain track of the rendered items. A common challenge is maintaining the integrity of the rendered objects while dynamically updating the list. By utilizing the trackBy directive, Angular provides us with syntax sugar that simplifies this endeavor. This article will examine how to leverage the power of trackBy to efficiently keep track of rendered items.

Knowledge of the trackBy Directive
Essential to Angular, the trackBy directive optimizes rendering by associating a unique identifier with each list item. Using the trackBy directive, Angular can efficiently detect changes and update only the required DOM elements, resulting in enhanced performance.

Syntax and Usage

To use trackBy, please follow these steps:

Step 1. Define a Unique Identifier: Ensure that each list item in your component has a unique identifier. This is possible by incorporating an id property into your data objects.

export interface Item {
  id: number;
  // Other properties
}

// Example data
items: Item[] = [
  { id: 1, name: 'Item 1' },
  { id: 2, name: 'Item 2' },
  // Additional items
];

Step 2. Specify the trackBy Function: Next, create a method in your component that acts as the trackBy function. This function will be responsible for returning the unique identifier for each item.
trackByFn(index: number, item: Item): number {
  return item.id;
}

Step 3.  Apply trackBy in Template: In your HTML template, apply the trackBy directive by binding it to the ngFor loop.
<ng-container *ngFor="let item of items; trackBy: trackByFn">
  <!-- Render item here -->
</ng-container>

The benefits of using the trackBy Directive offer
Improved Performance: By associating a unique identifier with each item, Angular can efficiently track changes and update only the affected elements, resulting in optimized rendering performance.

Reduced DOM Manipulation: With trackBy, Angular avoids unnecessary DOM manipulations by reusing existing elements when the data changes, leading to a smoother user experience.

Simplified Syntax: The syntax sugar provided by the trackBy directive simplifies the usage and implementation of item tracking in Angular, making the code more readable and maintainable.

By utilizing the syntax sugar of Angular directives, specifically the trackBy directive, we can easily maintain good track of rendered items in our Angular applications. By following the steps outlined in this article, you can optimize performance, reduce unnecessary DOM manipulations, and simplify the codebase. Leveraging the power of trackBy, you can build responsive and efficient Angular applications with ease.




AngularJS Hosting Europe - HostForLIFE.eu :: Sorting Based on Selection in Check Box using Pipe

clock June 8, 2023 09:58 by author Peter

To sort an array of objects by a checkbox selection in a column using a custom pipe in Angular, you can modify the checkbox-selection.pipe.ts file as follow
Custom Pipe (checkbox-selection.pipe.ts)


To generate pipe, use the following comment.

ng g p CheckboxSelectionPipe
    g- stands for generate
    p- stands for pipe

CheckboxSelectionPipe - use your custom pipe name instead of [checkboxslectionpipe]

In Pipe declaration, we can define the filter's name (pipe); when the pipe is true, the pipe is pure, meaning that the transform() method is invoked only when its input arguments change. Pipes are pure by default.

In the transform() method, we can pass the array which needs to be filtered.

Code Explanation
In the SelectedItems array, we will filter the collection based on the selected property in the collection. If the selected property was setted to true means, it will filter into SelectedItems.
In the UnSelectedItems array, we will filter the collection based on the selected property in the collection. If the selected property was setted to false means, it will filter into UnSelectedItems.

Here I have used the spread operator (...) that will allow us to quickly copy all or part of an existing array or object into another array or object.

While returning, it will merge Selected and unselected items.
@Pipe({
  name: 'orderByCheckboxSelection',
  pure:false

})
export class CheckboxSelectionPipe implements PipeTransform {

  transform(list: any): any {
    if (!list) {
      return [];
    }

    // Sort the items based on whether they are selected or not
    let selectedItems = list.filter(item => item.selected);
    let unselectedItems = list.filter(item => !item.selected);

    return [...selectedItems, ...unselectedItems];
  }

}


App.Module.ts for a particular module
Register the custom pipe in the module where you want to use it. For example, open the app.module.ts file and import and add CheckboxSelectionPipe to the declarations array.
@NgModule({
  declarations: [....,....],
  imports: [
    CheckboxSelectionPipe
  ],
  providers: [ ....]


App.Component.html
By providing the CheckBoxSelection pipe to the array needed to sort, you can sort the array based on that property's checkbox selection.
<div *ngFor="let date of collection | orderByCheckboxSelection ">
 ....
....
</div>



European Visual Studio 2017 Hosting - HostForLIFE :: Test HTTP API Endpoint without Postman using Visual Studio

clock June 5, 2023 09:46 by author Peter

You can now test our API endpoints using Visual Studio 17.5 with the aid of Visual Studio. Let's begin with an implementation example.


Step 1
Create a new Web API project using.NET Core.

Step 2

Create one API controller and multiple endpoints within the new project, which will be tested using an HTTP file.
using Microsoft.AspNetCore.Mvc;
using RudderStackDemo.Entities;
using RudderStackDemo.Repositories;

namespace RudderStackDemo.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class ProductsController : ControllerBase
    {
        private readonly IProductService _productService;

        public ProductsController(IProductService productService)
        {
            _productService = productService;
        }

        /// <summary>
        /// Product List
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> ProductListAsync()
        {
            var productList = await _productService.ProductListAsync();
            if (productList != null)
            {
                return Ok(productList);
            }
            else
            {
                return NoContent();
            }
        }

        /// <summary>
        /// Get Product By Id
        /// </summary>
        /// <param name="productId"></param>
        /// <returns></returns>
        [HttpGet("{productId}")]
        public async Task<IActionResult> GetProductDetailsByIdAsync(int productId)
        {
            var productDetails = await _productService.GetProductDetailByIdAsync(productId);
            if (productDetails != null)
            {
                return Ok(productDetails);
            }
            else
            {
                return NotFound();
            }
        }

        /// <summary>
        /// Add a new product
        /// </summary>
        /// <param name="productDetails"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> AddProductAsync(ProductDetails productDetails)
        {
            var isProductInserted = await _productService.AddProductAsync(productDetails);
            if (isProductInserted)
            {
                return Ok(isProductInserted);
            }
            else
            {
                return BadRequest();
            }
        }

        /// <summary>
        /// Update product details
        /// </summary>
        /// <param name="productDetails"></param>
        /// <returns></returns>
        [HttpPut]
        public async Task<IActionResult> UpdateProductAsync(ProductDetails productDetails)
        {
            var isProductUpdated = await _productService.UpdateProductAsync(productDetails);
            if (isProductUpdated)
            {
                return Ok(isProductUpdated);
            }
            else
            {
                return BadRequest();
            }
        }

        /// <summary>
        /// Delete product by id
        /// </summary>
        /// <param name="productId"></param>
        /// <returns></returns>
        [HttpDelete]
        public async Task<IActionResult> DeleteProductAsync(int productId)
        {
            var isProductDeleted = await _productService.DeleteProductAsync(productId);
            if (isProductDeleted)
            {
                return Ok(isProductDeleted);
            }
            else
            {
                return BadRequest();
            }
        }
    }
}

Step 3
Right-click on the project name in the solution and add the API-Test.http file inside your project.

Step 4
Add different HTTP endpoint requests inside the HTTP file.

GET https://localhost:7178/api/Products

###

@productId = 2
GET https://localhost:7178/api/Products/{{productId}}

###

POST https://localhost:7178/api/Products
Content-Type application/json

{
  "id": 3,
  "productName": "Laptop",
  "productDescription": "HP Pavilion",
  "productPrice": 80000,
  "productStock": 10
}

###

PUT https://localhost:7178/api/Products
Content-Type application/json

{
  "id": 3,
  "productName": "Laptop",
  "productDescription": "DELL",
  "productPrice": 80000,
  "productStock": 10
}

###

DELETE https://localhost:7178/api/Products?productId=1


Step 5
Now you can execute the individual API endpoint after clicking on the run button corresponding to each request as shown below.



AngularJS Hosting Europe - HostForLIFE.eu :: Dynamic JSON Data Handling in Angular

clock May 30, 2023 09:16 by author Peter

You can take the following actions to handle the provided JSON example dynamically in an Angular application:
"Data": ["confidence": 0.9983, "label": "height", "value": "5 FT 7 IN"; "confidence": 0.9971, "label": "squad", "value": "Team A"

Step 1
Create an Angular component: Run the ng produce component dynamicHandling command to create a new component using the Angular CLI.

Step 2
Import the HttpClientModule from @angular/common/http in the app.module.ts file to initiate HTTP queries.
'@angular/common/http' import HttpClientModule;

export class AppModule @NgModule("imports: [ HttpClientModule ], //...")

Step 3
To retrieve the JSON data, send an HTTP request: Import the HttpClient and issue an HTTP GET request to the component's TypeScript file (dynamic-handling.component.ts) to obtain the JSON data.

Component, OnInit, import from '@Angular/core';
'@angular/common/http' import HttpClient;

@Component('app-dynamic-handling', './dynamic-handling.component.html', and './dynamic-handling.component.css') export class DynamicHandlingComponent implements OnInit with the following parameters: jsonData: any;

  private http: HttpClient constructor

  This.http.getany>('your_api_endpoint') in ngOnInit() returns void.(data => subscribe) this.jsonData = data.Data; ); ;



Step 4
To loop through the JSON data in the template, use ngFor: Utilize the ngFor directive in the component's HTML file (dynamic-handling.component.html) to cycle through the jsonData array and dynamically display the results.

"let item of jsonData" in the div *ngFor attribute.'item.label': 'item.value' '/p' '/div'

Step 5
Include the element in the primary template: To display the dynamic handling component, include the app-dynamic-handling> and /app-dynamic-handling> tags in the app.component.html file.
App-dynamic-handling in div, app-dynamic-handling out of div.

The real API endpoint from which you may obtain the JSON data should be substituted for "your_api_endpoint" in Step 3.

As indicated in Steps 2 and 5, be sure to import the HttpClientModule into the app.module.ts file and include the dynamic handling component in the app.component.html main template.

Once the component and template have been configured, the Angular application will issue an HTTP request to retrieve the JSON data and use the ngFor directive in the template to dynamically display the information.



AngularJS Hosting Europe - HostForLIFE.eu :: How to Sort Column (Orderby) Based on Date in Angular 13 using Pipe?

clock May 25, 2023 13:02 by author Peter

To sort an array of objects by a particular date column in ascending or descending order using a custom pipe in Angular, you can modify the date-sort.pipe.ts file as follows:
Custom Pipe (date-sort.pipe.ts)


In Pipe declaration, we can define the name of the filter (pipe), When pipe is true, the pipe is pure, meaning that the transform() method is invoked only when its input arguments change. Pipes are pure by default.

In the transform() method, we can pass the array which needs to be filtered. Property parameter can as based on which date column we need to sort; ordering 'asc' | 'desc' can be also passed.

@Pipe({
  name: 'orderByDate',
  pure:false

})
export class OrderByDatePipe implements PipeTransform {

  transform(array: any[], property: string, order: 'asc' | 'desc'): any[] {
    if (!Array.isArray(array) || !property) {
      return array;
    }

    array.sort((a, b) => {
      const dateA = new Date(a[property]);
      const dateB = new Date(b[property]);

      if (order === 'asc') {
        return dateA.getTime() - dateB.getTime();
      } else {
        return dateB.getTime() - dateA.getTime();
      }
    });

    return array;
  }
}


App.Module.ts for a particular module

Register the custom pipe in the module where you want to use it. For example, open the app.module.ts file and import and add OrderByDatePipe to the declarations array:
@NgModule({
  declarations: [....,....],
  imports: [
    OrderByDatePipe
  ],
  providers: [ ....]


For use across Application

1. We can use Share.Module.ts, Register the custom pipe in share module,
@NgModule({
  declarations: [
    OrderByDatePipe
  ],
  imports: [
    CommonModule
  ]
  ,exports:[
   OrderByDatePipe

  ]
})


2. We can import ShareModule in whether we want to use it inside any module.
@NgModule({
  declarations: [...,.... ],
  imports: [
    .....
    SharedModule,
    ....
  ],
  providers: [ .....]


App.Component.html
    In your component's template, pass the desired date column and order ('asc' or 'desc') as parameters to the OrderByDatePipe :
    Make sure to replace 'scheduleStartDate' with the actual name of the date column in your array of objects.

By providing the specific property/column to the orderByDate pipe, you can sort the array based on that property's date values in either ascending or descending order.
<div *ngFor="let schedule of CurrentSchedule | orderByDate:'scheduleStartDate':'asc'">
 ....
....
</div>
 <div *ngFor="let schedule of CurrentSchedule | orderByDate:'scheduleStartDate':'desc'">
 ....
....
</div>



AngularJS Hosting Europe - HostForLIFE.eu :: Real-Time Communication Made Simple: Angular Demonstrating Web Sockets

clock May 23, 2023 07:12 by author Peter

Web Sockets
Web sockets are a protocol that facilitates bidirectional, full-duplex communication between clients and servers over a single, persistent connection. In contrast to conventional HTTP requests, which are stateless and request-response based, web sockets enable event-driven communication in real time. They are especially useful for applications requiring real-time updates, such as messaging applications, collaborative tools, and real-time dashboards.

Setting Up an Angular Project
To begin using web sockets in Angular, we must create a new project. Let's utilize the Angular CLI to scaffold the application's structure and install any necessary dependencies. Open your terminal or command prompt and proceed as follows:

Install Angular CLI if it is not already installed.

npm install -g @angular/cli

Step 2. Create a new Angular project.
ng new websocket-demo
cd websocket-demo


Establishing a Web Socket Connection
Now that we have our Angular project set up let's establish a web socket connection. We'll create a service that wraps the WebSocket API and handles the connection lifecycle. Open the terminal/command prompt and navigate to the project's root directory. Then, follow these steps.

1. Generate a WebSocket service.
ng generate service websocket

2. Open the newly generated service file (websocket.service.ts) and replace its content with the following code.
import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root'
})
export class WebsocketService {
  private socket: WebSocket;

  constructor() { }

  connect(): void {
    this.socket = new WebSocket('wss://your-websocket-url');

    this.socket.onopen = () => {
      console.log('WebSocket connection established.');
    };

    this.socket.onmessage = (event) => {
      console.log('Received message:', event.data);
    };

    this.socket.onclose = (event) => {
      console.log('WebSocket connection closed:', event);
    };

    this.socket.onerror = (error) => {
      console.error('WebSocket error:', error);
    };
  }

  sendMessage(message: string): void {
    this.socket.send(message);
  }

  closeConnection(): void {
    this.socket.close();
  }
}


3. Replace 'wss://your-websocket-url' in the connect() the method with the actual WebSocket URL you want to connect to.

Sending and Receiving Data

With our web socket service in place, we can now send and receive data between the client and server. Open the component where you want to use the web socket service (e.g., app.component.ts) and follow these steps.

Import the WebSocket service
import { Component } from '@angular/core';
import { WebsocketService } from './websocket.service';

@Component({
  selector: 'app-root',
  template: `
    <button (click)="sendMessage()">Send Message</button>
  `
})
export class AppComponent {
  constructor(private websocketService: WebsocketService) {}

  sendMessage(): void {
    const message = 'Hello, WebSocket!';
    this.websocketService.sendMessage(message);
  }
}

In the same component file (e.g., app.component.ts), add the following code to receive messages from the server.
@Component({
  // Component configuration...
})
export class AppComponent implements OnInit {
  receivedMessages: string[] = [];

  constructor(private websocketService: WebsocketService) {}

  ngOnInit(): void {
    this.websocketService.connect();
    this.websocketService.messageReceived.subscribe((message: string) => {
      this.receivedMessages.push(message);
    });
  }

  sendMessage(): void {
    const message = 'Hello, WebSocket!';
    this.websocketService.sendMessage(message);
  }
}

In the component template (app.component.html), display the received messages.
<button (click)="sendMessage()">Send Message</button>

<ul>
  <li *ngFor="let message of receivedMessages">{{ message }}</li>
</ul>

Now, when the sendMessage() the method is called, it will send a message to the server using the web socket service. The received messages from the server are stored in the receivedMessages array and displayed in the component template.

Handling Errors and Disconnections

To handle errors and disconnections gracefully, let's make some modifications to our existing code. Open the websocket.service.ts file and follow these steps,

-  Import the Subject class from RxJS to handle the stream of received messages. Add the following line at the top of the file after the existing imports.
import { Subject } from 'rxjs';

-  Inside the WebsocketService class, declare a new messageReceived property of type Subject<string>. This will be used to emit and subscribe to the received messages:
messageReceived: Subject<string> = new Subject<string>();

-  In the onmessage event handler, modify the code to emit the received message through the messageReceived subject.
this.socket.onmessage = (event) => {
  const message = event.data;
  console.log('Received message:', message);
  this.messageReceived.next(message);
};


By implementing these changes, we are now using the messageReceived subject to emit and subscribe to the received messages in our Angular component. This allows us to handle and display the messages in real time.

In this article, we have explored how to implement web sockets in an Angular project to enable real-time communication between clients and servers. We covered the fundamentals of web sockets, including setting up an Angular project, establishing a web socket connection, sending and receiving data, and handling errors and disconnections.



European Visual Studio 2017 Hosting - HostForLIFE :: Helpful Tips To Increase Productivity In Visual Studio

clock January 18, 2023 07:23 by author Peter

In this article, I'll show you some Visual Studio features that have greatly boosted developers' efficiency and productivity in their day-to-day development.


Introduction
Visual Studio is an IDE made by Microsoft and used for different types of software development such as computer programs, websites, web apps, web services, and mobile apps. It is used by many developers all over the world every day. It's a fantastic tool with lots of important features that will make the life of a developer much simpler.

Visual Studio supports 36 different programming languages. Several well-known languages that are supported by Visual Studio are C#, F#, Visual Basics, C, C++, Python, JavaScript, etc.

Let’s see how we can speed up development work with some Visual Studio built-in features.

1. Code Snippets
The Code snippets are pre-written templates that enable us to write code for our project more quickly. That can be inserted in a code file using a context menu command or a combination of hotkeys. It is used to add repeating code patterns, such as properties, loops, or conditional statements. Visual Studio has a lot of inbuilt code snippets. We are going to show a few of them which are often used while programming.

Snippets for Properties
To add an auto-implemented property, we have to type the prop key and then press TAB key twice. That will generate the following.

public <TYPE> MyProperty { get; set; } //TYPE can be int, string, bool.. etc.
//Default it will generate int type of propery as below:
public int MyProperty { get; set; }

The TAB key is used to switch between fields, EX: If we want to jump from TYPE to MyProperty or Vice versa, then we can use the TAB key.

Then we can change “TYPE” and "MyProperty":
public string Name { get; set; }

Similarly, if we want to add a full property along with its private variable, we can type propfull.

Other useful Code snippets or shortcuts. Please remember, you have to type <Snippet> TAB + TAB (hit the Tab key twice) to generate code templates.

 if  Generate if statement
 else  Generate else statement
 try  Generate try and catch statement
 tryf  Generate try and finally statement
 for  Generates a for loop
 foreach  Generates a foreach loop
 cw  Generate Console.WriteLine() statement

In Visual Studio, there are numerous built-in code snippets, You can find them all by pressing CTRL+K+X. As shown below image.

2. Code Editor Split
We can split the code editor vertically or horizontally. This is quite helpful If we need to simultaneously edit several related file's code at the same time. To add a new vertical tab group. Open the file in the editor and use the keyboard shortcut Alt + W, V. It will open the file like below.

We can spit files horizontally too. It is useful when we need to compare the same file content, To spit files horizontally use Menu Window ⇾ Split option.

Or You simply use the small drag arrows icon in the top right corner of your file window, as shown in the following screenshots.

The result will be.

3. Navigation Through the Active Windows and Tabs
To navigate between the active windows in VS. We are using the mouse to go from one window to another.
But, while doing coding, we want to quickly complete any side tasks without taking our hands off the keyboard. Therefore, we can use the CTRL+TAB combination rather than a mouse. Then, using the arrow keys, we can choose the necessary active window:

We can navigate through the active tabs in the same way that we do with the active windows. So for that, we need to press the CTRL+TAB keys and navigate with arrow keys. If we don't want to use the arrow key, then we just press the TAB key to navigate through the active tabs.

The same result can also be obtained by using CTRL+F6 or, for reverse navigation, use CTRL+SHIFT+F6.

4. Immediate Window
The Immediate window is used to debug and evaluate expressions, execute statements, and print variable values. It allows you to enter expressions to be evaluated or executed by the development language during debugging. We can write additional code that can add to or alter the current code execution.

To display the Immediate window, open a project, and then choose Debug > Windows > Immediate or press Ctrl+Alt+I.


5. Shortcuts
There are a huge number of keyboard shortcuts available in Visual Studio that let you do everything from code navigation to code generation, refactoring, debugging, and more. The most effective method for enhancing Visual Studio productivity and accelerating the coding process is to use keyboard shortcuts.



AngularJS Hosting Europe - HostForLIFE.eu :: Implementing Different Chart Types In Angular

clock August 1, 2022 09:36 by author Peter

In current day, data is everywhere and is an important part of our lives. We collect, send, analyse, and do lots of other things with data. Data in itself is not visually appealing, but we can make it beautiful. Chart is one such thing that can make data look beautiful & easier to understand / analyse. We can use different chart types to show data depending on the type of data we are showing. In this article, we will see how to add, configure and use different chart types in Angular using CanvasJS angular charts.

Adding CanvasJS angular chart to project
Let's start by adding CanvasJS angular chart component to the project. Download the component from the official download page. Copy the chart component files to the project. Generally, these files are kept under assets directory. Once it's copied, import & register the modules.
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent } from './app.component';

import * as CanvasJSAngularChart from './assets/canvasjs.angular.component';
var CanvasJSChart = CanvasJSAngularChart.CanvasJSChart;

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


As the modules are registered, you can start creating chart. Let's create & display simple column chart in angular.
import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  template: '<canvasjs-chart [options]="chartOptions"></canvasjs-chart>'
})
export class AppComponent {
    chartOptions = {
      title: {
          text: "Angular Column Chart"
      },
      data: [{
        type: "column",
        dataPoints: [
            { label: "apple",  y: 10  },
            { label: "orange", y: 15  },
            { label: "banana", y: 25  },
            { label: "mango",  y: 30  },
            { label: "grape",  y: 28  }
        ]
      }]
    }
}

Here we first imported the CanvasJS chart component & then define the options for the chart. CanvasJS takes data to be plotted along with other chart element customization options as 'chart-options'. In the above example, you can observe labels are passed to each datapoint which are shown below every bar (vertical bar charts are called as column chart). The same can be changed to horizontal bar or line or pie by just changing type property. The data is an array of objects where each dataseries is an object - this means if you pass multiple objects, it creates chart with multiple series.

Line Chart

Line chart is a way to represent data in the form of line. Often they are used to show the trend or to compare two different data sets. In the above simple chart that you created, just change type property to 'line' & that should create a line chart instead of column. CanvasJS has different kinds of lines - regular line, spline (similar to line except that the line is smooth), step-line (similar to line but line is in the form of steps/staircase).
chartOptions = {
  title: {
      text: "Angular Line Chart"
  },
  data: [{
    type: "line",
    dataPoints: [
        { label: "apple",  y: 10  },
        { label: "orange", y: 15  },
        { label: "banana", y: 25  },
        { label: "mango",  y: 30  },
        { label: "grape",  y: 28  }
    ]
  }]
}

Just by filling the region between the base and the datapoints value, it create area chart. Component supports different area forms like area, range area, stacked area & gets clubbed with different types of line to create more combinations.

Bar Chart
In bar chart, data is represented in the form of rectangles - vertical bars / horizontal bars. Syntax is same as line but type field takes different value. Bars can be vertical called column chart or horizontal called bar chart. CanvasJS angular component has different kinds of bar charts like bar, range bar, stacked bar, stacked bar 100%, column, range column, stacked column, stacked column 100% & waterfall.
chartOptions = {
  title: {
    text: "Angular Bar Chart"
  },
  data: [{
  type: "bar",
  dataPoints: [
    { label: "apple",  y: 10  },
    { label: "orange", y: 15  },
    { label: "banana", y: 25  },
    { label: "mango",  y: 30  },
    { label: "grape",  y: 28  }
  ]
  }]
}

Pie Chart
Pie chart is probably the most commonly used chart where datapoint is represented as slices of the pie. Each slice will show the relational proportion between the data. Pie chart can further be modified to have a hollow space in the centre making it look like a donut & hence this type of chart is called doughnut / donut chart.
chartOptions = {
  title: {
    text: "Angular Pie Chart"
  },
  data: [{
  type: "pie",
  dataPoints: [
    { label: "apple",  y: 10  },
    { label: "orange", y: 15  },
    { label: "banana", y: 25  },
    { label: "mango",  y: 30  },
    { label: "grape",  y: 28  }
  ]
  }]
}


Financial Chart
Financial chart is generally used to show the stock data / trades. These are most commonly used chart type in stock, forex, shares, etc. These charts will generally be dynamic charts - keeps updating latest data automatically by fetching data from some API.
chartOptions = {
  title: {
    text: "Angular Financial Chart"
  },
  data: [{
  type: "candlestick",
  dataPoints: [
    { label: "Jan", y: [1341.55, 1503.21, 1341.55, 1434.22] },
    { label: "Feb", y: [1462.00, 1532.10, 1271.00, 1339.32] },
    { label: "Mar", y: [1351.60, 1410.15, 1013.53, 1162.81] },
    { label: "Apr", y: [1122.00, 1359.98, 1079.81, 1348.66] },
    { label: "May", y: [1328.50, 1441.00, 1299.00, 1428.92] },
    { label: "Jun", y: [1418.39, 1475.94, 1347.01, 1413.60] },
    { label: "Jul", y: [1411.09, 1586.98, 1409.81, 1482.95] },
    { label: "Aug", y: [1486.64, 1659.21, 1458.65, 1634.18] },
    { label: "Sep", y: [1636.63, 1733.18, 1406.55, 1469.59] },
    { label: "Oct", y: [1484.27, 1687.00, 1436.00, 1621.01] },
    { label: "Nov", y: [1628.16, 1818.06, 1616.03, 1760.73] },
    { label: "Dec", y: [1774.36, 1847.19, 1699.00, 1751.88] }
  ]
  }]
}


More Chart Types & Additional Examples
You can check out CanvasJS angular charts gallery page where more working examples are shown with varieties of use-cases & customization. Also complete customization options can be found on CanvasJS's documentation section.

Conclusion
CanvasJS angular chart component makes it easy to showcase varieties of chart types in your application and dashboard. It also supports dynamic charts making it easier to automate to show latest data always.



Blazor Hosting - HostForLIFE :: Picking Between Blazor Server And Blazor WebAssembly

clock February 16, 2022 07:26 by author Peter

At this point we’ve all heard of Blazor. But when people first start out with Blazor, the analysis paralysis of picking between the types of Blazor projects can keep people from picking it up quickly—and being able to quickly dive in and have something up and running is one of the primary benefits of using Blazor in the first place.

My hope with this article is to provide a simple understanding of the differences between Blazor Server and Blazor WebAssembly, and give you the knowledge to pick the right tool for the job.

 

Both Blazor project types use the same component-based structure for writing web applications. If you’ve ever used React, you’ll understand what this looks like. Each unit of work or piece of UI is broken up into individual components, and components can be composed together as bigger, more complex components. In Blazor, we write these as Razor Components (.razor) which allows us to weave HTML and C# within the same code file. It’s great to work with and allows for very dynamic and maintainable UI components.

 

Blazor Server or WebAssembly. Which one is better?

 

This question gets asked a lot, but when it comes down to it, it’s not really the right question to ask. They are both amazing in their own regard, but it’s important to understand that they are very different fundamentally. A better question to ask is, “Which one is better for my situation?”

 

Blazor Server
Blazor Server, at its heart, is an ASP.NET Core server-side web app. The entire application runs on the server and the pages/components are rendered on the server before being sent as HTML to the client.

 

Blazor Server is very unique, and to my knowledge is the first technology to do things the way it does.

 

When a user connects to your Blazor Server web app, a SignalR connection is established between the client and the server. Every UI interaction from the user is sent as a small packet via this SignalR connection to the server. Every update or redraw of the UI is sent by the server to the client via SignalR.

 

This connection is maintained throughout the entire session, and if the connection is broken for any reason (exceptions/errors, connection issues, server restarts, etc) the user must refresh the page to re-establish the SignalR connection—otherwise the app will not be functional.

 

This is a very unique approach to web development. It allows us to make highly dynamic, flexible and responsive Single-Page-Applications (SPAs) that are entirely server-side applications.

 

Pros

  • Data access is simpler. You do not need complicated API authentication schemes and session security to handle data access within your application. This is a server-side app after all, you can use an internal API or just use the Repository Pattern directly within your Blazor project.
  • The code is processed on the server before the client machine gets any code, so they do not have access to the C# code from the browser. This again makes security, authorization, and data access much simpler endeavors
  • Because of the previously mentioned points, Blazor Server is very easy to work with. You can jump in and work on your application very quickly and without many roadblocks.

These are very big benefits to consider. As a developer you can write a very feature-rich app quickly, while still following best practices.

Cons

  • As previously mentioned, a SignalR connection is maintained for each individual client connected to the web app. These connections have a slight overhead on the server and can start to get expensive at large scale. If your application must support a very large number of concurrent users, it’s definitely something to consider. (Most applications will not see the kind of scale where this will matter.)
  • Since UI interactions are reliant on a socket connection between the client and server, latency due to poor internet connection or physical distance from the server can negatively affect the experience of the user. Users with high latency may experience a noticeable lag in the UI interactions or will have a generally unpleasant experience. If your application will have a very diverse global reach, this will be something to consider.

Blazor WebAssembly

Blazor WebAssembly works very differently than Blazor Server. The entire application, along with its components and dependencies, are sent to the client. A very light-weight version of the .NET Runtime is also sent to the client. The Blazor application is then run entirely by the client’s browser with the help of WebAssembly.

This model of execution allows for a very pleasant user experience, since the UI interaction is not at all dependent on a persistent connection to the server. The client’s machine is doing all the work, so there is no server load to speak of when it comes to serving up the app to a user. In fact, you can even host a Blazor WebAssembly app entirely as a static website on a service such as Netlify, GitHub Pages, Azure Static Web Apps, etc. without writing a dedicated web server.

Pros

  • Scale. Blazor WebAssembly apps can achieve arbitrary scale because the server is not running the application, the client is. This model allows for scaling to a high amount of concurrent users cheaply.
  • Blazor WebAssembly apps can work offline or be written as PWAs (Progressive Web Apps)
  • Performance is generally very good and offers a great user experience because the application is running on the client’s machine as opposed to a server
  • Since you don’t need a dedicated server running and maintaining active user sessions, hosting a Blazor WebAssembly application can have a significantly lower cost.

Cons

  • Data access and security is more complicated, since this application will be running entirely on the client side. All data access must be done over public APIs, which means that if you have user-specific or session-specific data, then the API auth and security must be managed. Additionally, the client will have access to your code (which is true of all client-side web frameworks) so you have to be aware of this while developing your app.
  • Relatively big download size for the user. Initial app load time may take longer while the client’s machine downloads all the necessary files for the application to run. This isn’t unique to Blazor however and it’s somewhat common among front-end web frameworks to be a bit heavily front-loaded.
  • WebAssembly is not supported by all browsers. It is a W3C standard so all modern standard-compliant browsers do have support or will be including support, but legacy browsers will not support this technology.

Summary

There are many more points to consider with each project type, as Blazor is very complex and full of nuance. But hopefully this article will provide a fundamental overview of both project types and what you should consider about each of them.

To summarize, you should consider picking Blazor Server for:

  • Intranet/internal applications
  • Apps that don’t expect to have a massive concurrent user-base
  • Apps where you want to have the full support of a .NET Core server behind it, and all the tools and features you get with it

And Blazor WebAssembly for:

  • Apps that expect to have very large scale with lots of concurrent users
  • Apps that can be used offline or with an intermittent connection
  • Apps where performance might be a concern / users might be accessing your app from different parts of the world

Hope this information has been helpful. Stay safe and happy coding!



About HostForLIFE.eu

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 offered the latest Windows 2016 Hosting, ASP.NET Core 2.2.1 Hosting, ASP.NET MVC 6 Hosting and SQL 2017 Hosting.


Tag cloud

Sign in