Wednesday 24 April 2024

How to write Unit Tests in .net

Unit tests are automated tests that verify the behavior code like methods and functions. Writing unit tests is crucial to clean coding, as they help ensure your code works as intended and catches bugs early in the development process. I can share some tips for writing effective unit tests:

Write tests for all public methods

Every public method in your code should have a corresponding unit test. This helps ensure that your code behaves correctly and catches any unexpected behavior early.

public class Calculator {

    public int Add(int a, int b) {
        return a + b;
    }
}
[TestClass]
public class CalculatorTests {
    [TestMethod]
    public void Add_ShouldReturnCorrectSum() {
        // Arrange
        Calculator calculator = new Calculator();
        int a = 1;
        int b = 2;
        // Act
        int result = calculator.Add(a, b);
        // Assert
        Assert.AreEqual(3, result);
    }
}

Test boundary conditions 

Make sure to test boundary conditions, such as null inputs or extreme values, to catch any edge cases that may cause problems.

public class Validator {

    public bool IsPositive(int number) {
        return number > 0;
    }
}
[TestClass]
public class ValidatorTests {
    [TestMethod]
    public void IsPositive_ShouldReturnFalseForZero() {
            // Arrange
            Validator validator = new Validator();
            // Act
            bool result = validator.IsPositive(0);
            // Assert
            Assert.IsFalse(result);
        }
        [TestMethod]
    public void IsPositive_ShouldReturnTrueForPositiveNumber() {
        // Arrange
        Validator validator = new Validator();
        // Act
        bool result = validator.IsPositive(3);
        // Assert
        Assert.IsTrue(result);
    }
}

Use a consistent naming convention :

Use a consistent naming convention for your tests, such as [MethodName]_Should[ExpectedBehavior], to make it clear what the test is testing. 

Keep your tests independent :

Make sure that your tests are independent of each other and don't rely on external state. This helps ensure that your tests are reliable and reproducible. 

Run your tests frequently:

Ideally after every code change we need to run unit tests to catch bugs early in the development process.

What to choose between .NET Core and .NET?

 .NET Framework is a better choice if you:

  • you don't have enough time time to learn new technology.
  • Need a stable environment to work in.
  • Have nearer release schedules.
  • you are already working on an existing app and extending its functionality.
  • If already have an existing team with .NET expertise and building production-ready software.
  • Do not want to deal with continuous upgrades and changes.
  • Building Windows client applications using Windows Forms or WPF

.NET Core is a better choice if you:

  • IF you wanted to deploy your app on Windows, Linux, and Mac operating systems.
  • Are not afraid of learning new things.
  • Are not afraid of breaking and fixing things since .NET Core is not fully matured yet.
  • When you are learning .NET.
  • work on open source.

Tuesday 23 April 2024

How To Deploy .net Core Application On Linux

Here, I can explain steps to deploy .net core application on linux machine.

Step 1 - Publish your .net Core application:

First, create a .net core application on VS; you can make an MVC project or Web API project and if you already have an existing project, then open it.

Right Click on your project

Click on publish

Now create a new publish profile, and browse the folder where you want to publish your project dll

Click on publish so it will create your dll in the folder

Step 2 - Install required .net Module on Linux:

Now we have our web application dll and now we need to host it on the Linux environment. First, we need to understand how the deployment works in Linux. .Net applications run on Kestrel servers and we run Apache or Nginx server in Linux environments, which acts as a proxy server and handles the traffic from outside the machine and redirects it to the Kestrel server so we will have Apache or Nginx server as the middle layer.

In this article, we will use Apache as a proxy server.

First, we need to install the .net core module in our Linux environment. For that run the following commands,

  • sudo apt-get update
  • sudo apt-get install apt-transport-https
  • sudo apt-get update
  • sudo apt-get install dotnet-sdk-3.1
  • sudo apt-get install dotnet-runtime-3.1
  • sudo apt-get install aspnetcore-runtime-3.1

Step 3 - Install and configure Apache Server:

So now we have all the required .Net packages. I have installed an additional package so if you are running a different project it will help.

Now install the Apache server,

  • sudo apt-get install apache2
  • sudo a2enmod proxy proxy_http proxy_html proxy_wstunnel
  • sudo a2enmod rewrite

Now we need to make a conf file to set up our proxy on Apache. Create the following file:

  • sudo nano /etc/apache2/conf-enabled/netcore.conf

Now copy the following configuration in that file,


   ServerName www.DOMAIN.COM
   ProxyPreserveHost On
   ProxyPass / http://127.0.0.1:5000/
   ProxyPassReverse / http://127.0.0.1:5000/
   RewriteEngine on
   RewriteCond %{HTTP:UPGRADE} ^WebSocket$ [NC]
   RewriteCond %{HTTP:CONNECTION} Upgrade$ [NC]
   RewriteRule /(.*) ws://127.0.0.1:5000/$1 [P]
   ErrorLog /var/log/apache2/netcore-error.log
   CustomLog /var/log/apache2/netcore-access.log common

<VirtualHost *:80>

This tag defines the IP and port it will bind Apache so we will access our application from outside our Linux environment through this Ip:Port. 

 Now restart the Apache server, 

  • sudo service apache2 restart 
  • sudo apachectl configtest
Step 4 - Configure and Start Service:
Move your dll to the defined path with the below command.

"sudo cp -a ~/release/ /var/netcore/" 

Create a service file for our .Net application

"sudo nano /etc/systemd/system/ServiceFile.service"

Copy the following configuration in that file and  it will run our application,

[Unit]
Description=ASP .NET Web Application
[Service]
WorkingDirectory=/var/netcore
ExecStart=/usr/bin/dotnet /var/netcore/Application.dll
Restart=always
RestartSec=10
SyslogIdentifier=netcore-demo
User=www-data
Environment=ASPNETCORE_ENVIRONMENT=Production
[Install]
WantedBy=multi-user.target

ExecStart=/usr/bin/dotnet /var/netcore/Application.dll in this line replace Application.dll with your dll name that you want to run. 

Now start the service. Instead of the service name in the below commands use the name of the file made above, 

  • sudo systemctl enable {Service Name} 
  • sudo systemctl start {Service Name} 

Now your proxy server and kestrel server is running and you can access your application through any ip with port 80. 

To redeploy the code your need to replace the dll and stop and start your service again through the following commands 

  • sudo systemctl stop {Service Name} 
  • sudo systemctl start {Service Name}

Avoiding Cross-Site Scripting (XSS) attacks in C# and .NET Core

In the real world of web development, security is paramount. Cross-site scripting (XSS) remains a prevalent threat, capable of compromising the integrity and confidentiality of web applications. For developers working with C# and .NET Core, fortifying against XSS vulnerabilities is imperative. In this article, we'll delve into practical techniques and examples to safeguard your web applications against XSS attacks.

Understanding Cross-Site Scripting (XSS)

XSS occurs when attackers inject malicious scripts into web pages viewed by other users. These scripts exploit vulnerabilities in the application's handling of user inputs, leading to unauthorized access, data theft, or manipulation. Understanding the types of XSS (e.g., reflected, stored, DOM-based) is crucial for devising effective defence strategies.

Example Scenario

Consider a simple web application—a comment section where users can post messages. Without proper validation and sanitization, this application is susceptible to XSS attacks. Let's explore how we can enhance its security.

Mitigation Strategies with Examples

Input Validation and Sanitization: In C# and .NET Core, validate and sanitize user inputs rigorously to eliminate XSS vulnerabilities. Here's an example using ASP.NET Core MVC:

[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult PostComment(CommentViewModel model)
{
    if (ModelState.IsValid)
    {
        // Sanitize user input
        string sanitizedContent = HtmlEncoder.Default.Encode(model.Content);
        // Process sanitized content
        return RedirectToAction("Index");
    }
    return View(model);
}

Output Encoding: Encode user-generated content before rendering it in HTML to prevent XSS attacks. Example:

@Html.Raw(Html.Encode(comment.Content))

Implementing Content Security Policy (CSP): Configure CSP headers to restrict the execution of scripts from unauthorized sources. Example:

public void Configure(IApplicationBuilder app)
{
    app.Use(async (context, next) =>
    {
        context.Response.Headers.Add("Content-Security-Policy", "default-src 'self'");
        await next. Invoke();
    });
}

Utilizing Anti-Forgery Tokens: Protect against CSRF attacks by using anti-forgery tokens. Example:

@using (Html.BeginForm("PostComment", "Comment", FormMethod.Post))
{
    @Html.AntiForgeryToken()
    // Form fields
}

Extracting Values from PDFs in .NET Core 8 without ASP.NET

Extracting data from PDF files is a common necessity for various tasks such as data analysis, content indexing, and information retrieval. While ASP.NET Core 8 offers robust tools for PDF manipulation, there are instances where developers may prefer alternatives for flexibility or specific project requirements. In this article, we'll explore how to extract values from PDF files within the .NET Core 8 ecosystem without relying on ASP.NET, using the PdfSharpCore library. We'll provide a step-by-step guide along with examples in C# to demonstrate how to accomplish this task effectively.

  1. Understanding PdfSharpCore: PdfSharpCore is a popular .NET library for PDF document manipulation. It provides functionalities to create, modify, and extract content from PDF files. In this guide, we'll focus on utilizing PdfSharpCore to extract text from PDF documents.
  2. Installing PdfSharpCore: Before we can start using PdfSharpCore in our .NET Core application, we need to install the PdfSharpCore NuGet package. This can be done via the NuGet Package Manager Console or the .NET CLI.

Using the NuGet Package Manager Console:
Install-Package PdfSharpCore

Using the .NET CLI
dotnet add package PdfSharpCore

Extracting Text from PDFs in C#: Now we have PdfSharpCore installed, let's dive into how we can extract text from PDF files using C#.

using PdfSharpCore.Pdf;
using PdfSharpCore.Pdf.IO;
using System;

public class PdfTextExtractor
{
    public static string ExtractTextFromPdf(string filePath)
    {
        using (PdfDocument document = PdfReader.Open(filePath, PdfDocumentOpenMode.Import))
        {
            string text = "";
            foreach (PdfPage page in document.Pages)
            {
                text += page.GetText();
            }
            return text;
        }
    }

    // Example usage:
    public static void Main(string[] args)
    {
        string pdfText = ExtractTextFromPdf("sample.pdf");
        Console.WriteLine(pdfText);
    }
}

In this example, we've created a PdfTextExtractor class with a static method ExtractTextFromPdf that takes the file path of the PDF as input and returns the extracted text. Inside the method, we use PdfSharpCore to open the PDF file, iterate through its pages, and extract text from each page. Finally, the extracted text is concatenated and returned.

Monday 22 April 2024

Real-Time Data Transfer with Web Sockets and SignalR in .NET Core

 In dynamic web applications, real-time data transfer has become a crucial aspect of providing a responsive and interactive user experience. Web Socket technology, along with frameworks like SignalR in .NET Core, enables bidirectional communication between clients and servers, allowing seamless data exchange.

In this article, we'll explore how to implement Web Socket functionality using SignalR in a .NET Core application to retrieve data from a concurrent dictionary and push it to clients in real time.

Understanding Web Sockets and SignalR

Web Socket is a communication protocol that provides full-duplex communication channels over a single TCP connection, allowing for low-latency, bidirectional communication between clients and servers. It enables real-time data transfer without the overhead of HTTP polling.

SignalR is a high-level library built on top of Web Socket that simplifies real-time web functionality implementation in .NET applications. It abstracts away the complexities of managing connections and allows developers to focus on building real-time features.

Setting Up the Project

First, ensure you have the .NET Core SDK installed on your system. You can create a new .NET Core Web API project using the following command:

dotnet new webapi -n WebSocketSignalRDemo

Next, navigate to the project directory:

cd WebSocketSignalRDemo

Install the required SignalR package:

dotnet add package Microsoft.AspNetCore.SignalR

Implementing WebSocket Functionality

  1. Create a Concurrent Dictionary: In this example, let's assume we have a concurrent dictionary where real-time data updates occur. For demonstration purposes, we'll simulate this with a simple dictionary containing stock prices.
  2. Set Up SignalR Hub: Create a SignalR hub that will handle client connections and data transmission. Add methods to retrieve data from the concurrent dictionary and send it to clients.
  3. Configure SignalR in Startup: Register SignalR services and endpoints in the Startup.cs file.
  4. Client-Side Integration: Implement WebSocket client logic to receive real-time updates from the server.

Example Code:

Here's a simplified implementation of the above steps:

// Concurrent Dictionary Simulation (Replace with actual data source)

ConcurrentDictionary<string, decimal> stockPrices = new ConcurrentDictionary<string, decimal>();


// SignalR Hub

public class StockTickerHub : Hub

{

    public async Task GetLatestStockPrices()

    {

        while (true)

        {

            // Simulated data update

            foreach (var kvp in stockPrices)

            {

                await Clients.All.SendAsync("UpdateStockPrice", kvp.Key, kvp.Value);

            }

            await Task.Delay(1000); // Simulated delay

        }

    }

}


// Startup.cs

public void ConfigureServices(IServiceCollection services)

{

    services.AddSignalR();

}


public void Configure(IApplicationBuilder app, IWebHostEnvironment env)

{

    if (env.IsDevelopment())

    {

        app.UseDeveloperExceptionPage();

    }

    app.UseRouting();

    app.UseEndpoints(endpoints =>

    {

        endpoints.MapControllers();

        endpoints.MapHub<StockTickerHub>("/stockTickerHub");

    });

}


// Client-Side (JavaScript)

<!DOCTYPE html>

<html lang="en">

<head>

    <meta charset="UTF-8">

    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <title>Stock Ticker</title>

</head>

<body>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/microsoft-signalr/5.0.7/signalr.min.js"></script>

    <script>

        const connection = new signalR.HubConnectionBuilder()

            .withUrl("/stockTickerHub")

            .build();

        connection.on("UpdateStockPrice", (symbol, price) => {

            const stockList = document.getElementById("stockList");

            const listItem = document.createElement("li");

            listItem.textContent = `${symbol}: $${price}`;

            stockList.appendChild(listItem);

        });

        connection.start()

            .then(() => connection.invoke("GetLatestStockPrices"))

            .catch(err => console.error(err));

    </script>

</body>

</html>

Thursday 18 April 2024

How to Manage State in .NET Core

 In any application development, managing state effectively is crucial for maintaining data consistency and providing a seamless user experience. In .NET Core, various techniques and libraries are available for managing state, each catering to different scenarios and requirements. This article explores different state management techniques in .NET Core and provides code examples to illustrate their usage.

Built-in State Management Techniques

Session State: Session state allows storing user-specific data across multiple requests. It's useful for maintaining user authentication, shopping cart items, etc. Session state can be managed using ASP.NET Core's HttpContext.Session property.

// Setting session value HttpContext.Session.SetString("UserName", "JohnDoe"); // Retrieving session value var userName = HttpContext.Session.GetString("UserName");

View State: View state stores page-specific data that needs to be persisted across postbacks. It's commonly used in web forms applications. In ASP.NET Core, the view state is not directly available like in ASP.NET Web Forms, but you can achieve similar functionality using hidden fields or TempData.

// Storing data in TempData TempData["Message"] = "Data persisted across requests."; // Retrieving data from TempData var message = TempData["Message"];

Client-side State Management:

Cookies: Cookies are small pieces of data stored on the client's browser. They can be used to store user preferences, session identifiers, etc. In ASP.NET Core, cookies can be managed using Response. Cookies and Request.Cookies properties.

// Setting cookie Response.Cookies.Append("UserName", "JohnDoe"); // Retrieving cookie var userName = Request.Cookies["UserName"];

Local Storage: Local storage is a client-side storage mechanism available in modern web browsers. It allows storing data persistently on the client side. JavaScript can be used to interact with local storage.

// Setting data in local storage localStorage.setItem("AuthToken", "xyz123"); // Retrieving data from local storage var authToken = localStorage.getItem("AuthToken");

Third-party State Management Libraries 

Redux.NET: Redux.NET is a predictable state container for .NET applications, inspired by Redux for JavaScript. It helps manage application state in a predictable manner, especially in large-scale applications.

// Define actions public class IncrementCounter { } public class DecrementCounter { } // Define reducer public static int CounterReducer(int state, object action) { switch (action) { case IncrementCounter _: return state + 1; case DecrementCounter _: return state - 1; default: return state; } }

Fluxor: Fluxor is a low-boilerplate Redux-like library for .NET applications. It simplifies state management by providing features like actions, reducers, and effects.

// Define actions
public class IncrementCounter { }
public class DecrementCounter { }

// Define feature state
public class CounterState
{
    public int Count { get; }

    public CounterState(int count)
    {
        Count = count;
    }
}

// Define reducer
public static class CounterReducers
{
    [ReducerMethod]
    public static CounterState ReduceIncrementCounter(CounterState state, IncrementCounter action)
    {
        return new CounterState(state.Count + 1);
    }

    [ReducerMethod]
    public static CounterState ReduceDecrementCounter(CounterState state, DecrementCounter action)
    {
        return new CounterState(state.Count - 1);
    }
}

Journey from ASP.NET Framework to .NET Core

Initial development with ASP.NET framework

Initially, projects were developed using ASP.NET Framework, which provided various options for user interfaces.

  • Windows forms (WinForms): For desktop applications with rich UI controls.
  • Windows presentation foundation (WPF): For desktop applications with advanced graphics and multimedia support.
  • ASP.NET web forms: For web applications with a component-based UI model and event-driven programming.

Transition to ASP.NET MVC

  • As web development evolved, ASP.NET MVC (Model-View-Controller) emerged as a popular framework for building web applications using the ASP.NET Framework. ASP.NET MVC introduced a more structured approach to web development, separating concerns into models, views, and controllers.
  • ASP.NET MVC allowed developers to create web applications with cleaner code architecture, better testability, and improved control over HTML markup.

Introduction of .NET Core

  • With the advent of .NET Core, Microsoft introduced ASP.NET Core, a cross-platform, high-performance framework for building modern web applications and services.
  • ASP.NET Core MVC is the web framework included in ASP.NET Core, providing similar functionality to ASP.NET MVC but with enhancements and optimizations for performance, scalability, and cross-platform development.

Integration of AngularJS and Angular

  • While ASP.NET Framework and ASP.NET Core MVC provide server-side rendering of UI components, it's common to integrate client-side frameworks like AngularJS (for older projects) or Angular (for newer projects) to build interactive, dynamic user interfaces.
  • In the ASP.NET Framework, AngularJS can be integrated with server-side code to create single-page applications (SPAs) and enhance the user experience.
  • In ASP.NET Core, Angular is often preferred for its modern features, performance, and ecosystem support. ASP.NET Core provides seamless integration with Angular for building SPAs or using Angular components within server-rendered views

.Net Framework and .Net Core Version
 

S.No.ReleaseRelease Date
1.NET Framework 1.013-Feb-02
2.NET Framework 1.124-Apr-03
3.NET Framework 2.007-Nov-05
4.NET Framework 3.006-Nov-06
5.NET Framework 3.519-Nov-07
6.NET Framework 4.012-Apr-10
7.NET Framework 4.515-Aug-12
8.NET Framework 4.5.117-Oct-13
9.NET Framework 4.5.205-May-14
10.NET Framework 4.620-Jul-15
11.NET Framework 4.6.130-Nov-15
12.NET Core 1.027-Jun-16
13.NET Core 1.116-Nov-16
14.NET Core 2.014-Aug-17
15.NET Core 2.130-May-18
16.NET Core 2.204-Dec-18
17.NET Core 3.023-Sep-19
18.NET Core 3.103-Dec-19
19.NET 510-Nov-20
20.NET 608-Nov-21
21.NET 708-Nov-22
22.NET 814-Nov-23
23.NET 92024
24.NET 102025

Thursday 8 July 2021

List Of Commonly Used Angular Commands

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 JavaScript 

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 JavaScript 

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/flex-layout@9.0.0-beta.29 

Reference - https://update.angular.io


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 

Refer Angular Guide - https://update.angular.io/

Wednesday 3 June 2020

how to get & set value in state in react js

Here, I will explain how to bind state value & how to set or change state value.

Now I am creating component with name Car and create one object in constructor with keys like brand, model, color and year and stored value in state.

Next,I am binding all state value in HTML and also adding button with one function for change state value, when user click on change color button it will change color state value.

import React from 'react';
import ReactDOM from 'react-dom';

class Car extends React.Component {
  constructor(props) {
    super(props);
        this.state = {
          brand: "Ford",
          model: "Mustang",
          color: "red",
          year: 1964
        };
  }

  changeColor = () => {
    this.setState({color: "blue"});
  }

  render() {
    return (
      <div>
        <p>
          I have {this.state.color} color { this.state.model} car with {this.state.year} model.
        </p>
        <button type="button" onClick={this.changeColor}>Change color</button>
      </div>
    );
  }
}
ReactDOM.render(<Car/>, document.getElementById('root'));

Output:
Before button click : I have red color Mustang car with 1964 model.
After button click : I have blue color Mustang car with 1964 model.

Saturday 21 March 2020

Advantages of Ivy compiler and runtime in angular 9.


  • Smaller bundle sizes
  • Faster testing
  • Better debugging
  • Improved CSS class and style binding
  • Improved type checking
  • Improved build errors
  • Improved build times, enabling AOT on by default
  • Improved Internationalization

How to update to version 9?

We recommend you first update to the final release of Angular 8.

First, update to the latest version of 8

ng update @angular/cli@8 @angular/core@8

Then, update to 9

ng update @angular/cli @angular/core


Now, you can enjoy new advantages of angular 9.

Wednesday 6 November 2019

How To Use .map() In Angular

In this blog, I will explain how to use .map() functions in Angular.

We have an array containing multiple objects, each one representing an employee. You need to retrieve the id of each employee in an array object.

Input :-
var employees = [ 
 { id: 11, name: 'Ravishankar' }, 
 { id: 12, name: 'Muthu' },
 { id: 13, name: 'Mani' }, 
 { id: 14, name: 'Ajith' } 
];

Output :-
[11, 12, 13, 14] 

var employeeIds = employees.map(employee => employee.id);  

The callback runs for each value in an array and returns new value in the resulting array. The resulting array length will be the same as the original array.

How To Use .filter() In Angular

In this blog, I will explain how to use .filter() function in Angular.

We have an array containing multiple objects, each one representing an employee, but only want some of the objects in it. That’s where .filter() comes in.

var employees = [  
  {  
    "id": 1,  
    "name": "Nikhil",  
    "role": "Developer"  
  },  
  {  
    "id": 2,  
    "name": "Nikunj",  
    "role": "Tester"  
  },  
  {  
    "id": 3,  
    "name": "Dharmesh",  
    "role": "Tester"  
  },  
  {  
    "id": 4,  
    "name": "Mikin",  
    "role": "Developer"  
  }  
]  

So we want two arrays, one for employee a role is a Developer and another one is for Tester. You can achieve this using .filter().
var developers = employees.filter(employee => employee.role == "Developer"); 
var Testers = employees.filter(employee => employee.role == "Tester");   

First array returns Nikhil and Mikin.
Second array returns Nikunj and Dharmesh.

Friday 21 December 2018

How To Set Focus On Text Box In Angular 5.

Here, I will explain how to set focus on text box using ElementRef.

Demo.html : 

<input type="text" class="form-control" value="" #barcode placeholder="Barcode" [(ngModel)]="Barcode" (blur)="SetFocus()" />

Demo.Component.ts :

import { Component, OnInit, ElementRef } from '@angular/core';

export class StockDataTableComponent implements OnInit, OnChanges {
    @ViewChild('Barcode') barcode: ElementRef;
     constructor(){}

    function SetFocus(){
           this.barcode = "";
           this.barcode.nativeElement.focus();
    }
}