Tuesday 21 July 2020

Subject and BehaviorSubject differences - Angular

What is the difference between Subject and BehaviorSubject?

BehaviourSubject will return the initial value or the current value on Subscription. When it is subscribed it emits the value immediately. A Subject doesn't hold a value.

Subject example (with RxJS 5 API):
const subject = new Rx.Subject();
subject.next(1);
subject.subscribe(x => console.log(x));
Console output will be empty

BehaviorSubject example:
const subject = new Rx.BehaviorSubject();
subject.next(1);
subject.subscribe(x => console.log(x));
Console output: 1

BehaviourSubject
BehaviourSubject will return the initial value or the current value on Subscription

var bSubjectnew Rx.BehaviorSubject(0);  // 0 is the initial value

bSubject.subscribe({
  next: (v=> console.log('observerA: ' + v)  // output initial value, then new values on `next` triggers
});

bSubject.next(1);  // output new value 1 for 'observer A'
bSubject.next(2);  // output new value 2 for 'observer A', current value 2 for 'Observer B' on subscription

bSubject.subscribe({
  next: (v=> console.log('observerB: ' + v)  // output current value 2, then new values on `next` triggers
});

bSubject.next(3);

Output wiil be:
observerA: 0
observerA: 1
observerA: 2
observerB: 2
observerA: 3
observerB: 3
Subject
Subject does not return the current value on Subscription. It triggers only on .next(value) call and return/output the value. only values emitted after its subscription can be captured.

var subject = new Rx.Subject();

subject.next(1); //Subjects will not output this value

subject.subscribe({
  next: (v=> console.log('observerA: ' + v)
});
subject.subscribe({
  next: (v=> console.log('observerB: ' + v)
});

subject.next(2);
subject.next(3);

Output will be:
observerA: 2
observerB: 2
observerA: 3
observerB: 3
subject-vs-behavior-vs-replay-vs-async

Each next subscribers receive...
Subject...only upcoming values
BehaviorSubject...one previous value and upcoming values
ReplaySubject...all previous values and upcoming values
AsyncSubject...the latest value when the stream will close

Continue Reading →

Thursday 16 July 2020

How to Improve Web API Performance

Web Api: This is a framework for building HTTP services with easy and simple way.
Web API is open source an ideal platform for building REST-ful services over the .NET Framework.
It is light weight architecture and good for devices which have limited bandwidth like smart phones.

In this page, we will discuss about the techniques to improve the Web API performance.

1: JSON serializer over XML:
JSON serializer use JSON Formatter and by default Web API provides media-type formatters for both JSON and XML.A media type formatter is used to read CLR objects from an HTTP message and write the CLR object in HTTP message body.
JSON serializer is highly recommend and it very faster compare to other Serlializer like XML.

2: Asynchronous Task Based WebAPI :
     Async Web API action help to increase the number of concurrent HTTP requests Web API can handle. We can implement asynchronous programming for web api controller by using keywords async, Task, await

public class UserController : ApiController
{       
  public async Task<IHttpActionResultRead()
  {
   var data = await _db.UserMaster.ToListAsync();
   return Ok(data);
  }
 }

3: Cache Data:
Web API  does not provide the output Caching attribute to cache web api response but you can Cache data in memory to process same future request without hitting database and it improve the performance of ASP.NET Web API and Microsoft provides the System.Runtime.Caching library for memory caching. 

4: Multi Result sets or combined results
Web API should return as many objects as you can in one Web API request and combining objects into one aggregate object and It reduce the number of HTTP request to web API

Example : Aggregate Object ‘UserScreenData’

class UserScreenData
{
public List<StateStates { getset; }
public List<CountryCountries { getset; }
}

 Web API Method to return Aggregate object

public async Task<IHttpActionResultGetScreenData()
{
 UserScreenData screen = new Controllers.UserScreenData();
 screen.State = await _db.State.ToListAsync();
 screen.Countries = await _db.Country.ToListAsync();
 return Ok(data);
}

5: Implement compression
You should use compression techniques to compress the data that is transmitted over the wire. You can use GZip or Deflate compression on your Web API to compress data transferred between the server and the client. You can do the compression at the IIS level or by using a custom delegating handler or even using a custom action filter. You can learn more on how you can achieve this from  Click here

Below example you can use in Dotnet Core WebAPI.
public void ConfigureServices(IServiceCollection services)
{
    services.AddResponseCompression();
    services.Configure<GzipCompressionProviderOptions>(options => {
        options.Level = CompressionLevel.Fastest;
    });
}

6: Use classic ADO.NET if possible
Hand coded ADO.NET is still the fastest way to get data from database. If the performance of Web API is really important for you, don’t use ORMs.

The Dapper and the  hand-written fetch code are very fast, as expected, all ORMs are slower than those three.

But if you write your data access logic in optimize ways in EF Core, then definitely it improves the performance of the application. Here, we have some of the techniques which will increase the performance.
  1. Use No Tracking while getting the data which is the only read-only purpose. It improves performance.
  2. Try to filter the data on the database side, don’t fetch the whole data using query and then filter at your end. You can use some function available in EF Core like Where, Select which help you to filter the data on the database side.
  3. Retrieve only the required number of records which is necessary using the help of Take and Skip. You can take one example of paging where you can implement Take and Skip while clicking on the page number.
Let's take one example and try to understand how we can optimize the EF Core query using Select and AsNoTracking.

public async Task < PaginatedList < Post >> GetPagedPendingPosts
     (int pageIndex, int pageSize, List<Category> allowedCategories)
{
  var allowedCatIds = allowedCategories.Select(x => x.Id);
  var query = _context.Post
    .Include(x => x.Topic.Category)
    .Include(x => x.User)
    .Where(x => x.Pending == true && allowedCatIds.Contains(x.Topic.Category.Id))
    .OrderBy(x => x.DateCreated);

  return await PaginatedList<Post>.CreateAsync(query.AsNoTracking(), pageIndex,                                                                 pageSize);
}



Continue Reading →

Tuesday 7 July 2020

Difference between Constructor and ngOnInit

Angular provides lifecycle hook ngOnInit by default.

Why should ngOnInit be used, if we already have a constructor?

The Constructor is a default method of the class that is executed when the class is instantiated and ensures proper initialization of fields in the class and its subclasses. 

ngOnInit is a lifecycle hook called by Angular to indicate that Angular is done creating the component.
We have to import OnInit in order to use like this (implementing OnInit is not mandatory but considered good practice):

import {ComponentOnInitfrom '@angular/core';

then to use the method of OnInit we have to implement in the class like this.

export class App implements OnInit{
    constructor(){
     //called first time before the ngOnInit()
    }
    ngOnInit(){
      //called after the constructor and called  after the first ngOnChanges()
       }
      }

Mostly we should use ngOnInit for all the initialization/declaration and avoid stuff to work in the constructor. The constructor should only be used to initialize class members but shouldn't do actual "work".
So you should use constructor() to setup Dependency Injection and not much else. ngOnInit() is better place to "start" - it's where/when components' bindings are resolved.



Continue Reading →

Friday 3 July 2020

Difference Among Angular 8, 7, 6, 5, 4, 3, 2

Difference Among Angular 8, 7, 6, 5, 4, 3, 2 — Breakdown, New Features, and Changes

The first version of Angular was released in the year of 2010. Some people call this as AngularJS and some people call as Angular 1. But it is officially named as AngularJS.


Let’s dive into changes angular made overtime all the way from angular 2 to angular 8.

Angular 2
  1. Released in 2016
  2. Complete rewrite of Angular 1
  3. Written entirely in typescript
  4. Component-based instead of Controller
  5. ES6 and typescript supported
  6. More testable as component-based
  7. Support for Mobile/Low-end devices
  8. Up to typescript 1.8 is supported
Angular 4
  1. Released in 2017
  2. Changes in core library
  3. Angular 4 is simply the next version of angular 2, the underlying concept is the same & is an inheritance from Angular 2
  4. Lot of performance improvement is made to reduce size of AOT compiler generated code
  5. Typescript 2.1 & 2.2 compatible — all feature of ts 2.1 & 2.2 are supported in Angular 4 application
  6. Animation features are separated from @angular/core to @angular/animation
    — don’t import @animation packages into the application to reduce bundle size and it gives the performance improvement.
  7. Else block in *ngIf introduced:
    — Instead of writing 2 ngIf for else , simply add below code in component template:

    *ngIf=”yourCondition; else myFalsyTemplate
    “<ng-template #myFalsyTemplate>Else Html</ng-template>”
Angular 5
  1. Released 1st November 2017
  2. Build optimizer: It helps to removed unnecessary code from your application
  3. Angular Universal State Transfer API and DOM Support — By using this feature, we can now share the state of the application between the server side and client side very easily.
  4. Compiler Improvements: This is one of the very nice features of Angular 5, which improved the support of incremental compilation of an application.
  5. Preserve White space: To remove unnecessary new lines, tabs and white spaces we can add below code(decrease bundle size)

    // in component decorator you can now add:
    “preserveWhitespaces: false”
    // or in tsconfig.json:
    “angularCompilerOptions”: { “preserveWhitespaces”: false}`
  6. Increased the standardization across all browsers: For internationalization we were depending on `i18n` , but in ng 5 provides a new date, number, and currency pipes which increases the internationalization across all the browsers and eliminates the need of i18n polyfills.
  7. exportAs: In Angular 5, multiple names support for both directives and components
  8. HttpClient: until Angualar 4.3 @angular/HTTP was been used which is now depreciated and in Angular 5 a new module called HttpClientModule is introduced which comes under @angular/common/http package.
  9. Few new Router Life-cycle Events being added in Angular 5: In Angular 5 few new life cycle events being added to the router and those are:

    ActivationStart, ActivationEnd, ChildActivationStart, ChildActivationEnd, GuardsCheckStart, GuardsCheckEnd, ResolveStart and ResolveEnd.

  10. Angular 5 supports TypeScript 2.3 version.
  11. Improved in faster Compiler support:
    A huge improvement made in an Angular compiler to make the development build faster. We can now take advantage of by running the below command in our development terminal window to make the build faster.
    ng serve/s — aot
Angular 6
  1. Released on April 2018
  2. This release is focused less on the underlying framework, and more on tool-chain and on making it easier to move quickly with angular in the future
  3. No major breaking changes
  4. Dependency on RxJS 6 (this upgrade have breaking changes but CLI command helps in migrating from older version of RxJS)
  5. Synchronizes major version number of the:
    — Angular framework
    — Angular CLI
    — Angular Material + CDK
    All of the above are now version 6.0.0, minor and patch releases though are completely independent and can be changed based on a specific project.
  6. Remove support for <template> tag and “<ng-template>” should be used.
  7. Registering provider: To register new service/provider, we import Service into module and then inject in provider array. e.g:

    // app.module.ts
    import
    {MyService} from './my-service';
    ...
    providers: [...MyService]
    ... But after this upgrade you will be able to add providedIn property in injectable decorator. e.g: // MyService.ts @Injectable({ providedIn: 'root'}) export class MyService{}
  8. CLI Changes: Two new commands have been introduced
    — ng update <package>
    * Analyse package.json and recommend updates to your application
    * 3rd parties can provide update scripts using schematics
    * automatically update code for breaking changes
    * staying update and low maintenance
    — ng add
    * add new capablities to your applicaiton
    * e.g ng add @angular/material : behind the scene it add bit of necessary code and changes project where needed to add it the thing we just told it to add.
    * Now adding things like angular material, progressive web app, service workers & angular elements to your existing ng application will be easy.
  9. It uses angular.json instead of .angular-cli.json
  10. Support for multiple projects: Now in angular.json we can add multiple projects
  11. CLI + Material starter templates: Let angular create code snippet for your basic components. e.g:

    — Material Sidenav
    * ng generate @angular/material:material-nav — name=my-nav
    Generate a starter template including a toolbar with app name and then the side navigation & it's also responsive
    — Dashboard
    * ng generate @angular/material:material-dashboard — name=my-dashboard
    Generates Dynamic list of cards
    — Datatable
    * ng generate @angular/material:material-table — name=my-table
    Generates Data Table with sorting, filtering & pagination
Angular 7:
  1. Released on October 2018
  2. This is a major release and expanding to the entire platform including-
    — Core framework,
    — Angular Material,
    — CLI
  3. CLI Prompts: The CLI will now prompt users as when running common commands likeng new or ng add @angular/material with the intend of getting aid for building a new project using SCSS.
  4. Added a new interface — UrlSegment[] to CanLoad interface
  5. Added a new interface — DoBootstrap interface
  6. Angular 7 added a new compiler — Compatibility Compiler (ngcc)
  7. Introduce a new Pipe called — KeyValuePipe
  8. Angular 7 now supporting to TypeScript 2.9.
  9. Added a new elements features — enable Shadow DOM v1 and slots
  10. Added a new router features — warn if navigation triggered outside Angular zone
  11. Added a new mapping for ngfactory and ngsummary files to their module names in AOT summary resolver.
  12. Added a new “original” placeholder value on extracted XMB
  13. Added a new ability to recover from malformed URLs
  14. Added a new compiler support dot (.) in import statements and also avoid a crash in ngc-wrapped
  15. Update compiler to flatten nested template fns
Angular 8:
  1. Releasing March/April 2019
  2. Being smaller, faster and easier to use and it will be making Angular developers life easier.
  3. Added Support for TypeScript 3.2
  4. Added a Navigation Type Available during Navigation in the Router
  5. Added pathParamsOrQueryParamsChange mode for runGuardsAndResolvers in the Router
  6. Allow passing state to routerLink Directives in the Router
  7. Allow passing state to NavigationExtras in the Router
  8. Restore the whole object when navigating back to a page managed by Angular Router
  9. Added support for SASS
  10. Resolve generated Sass/Less files to .css inputs
  11. Added Predicate function mode for runGuardsAndResolvers:-
    This option means guards and resolvers will ignore changes when a provided predicate function returns `false`. This supports use cases where an application needs to ignore some param updates but not others. For example, changing a sort param in the URL might need to be ignored, whereas changing the `project` param might require a re-run of guards and resolvers.
  12. Added functionality to mark a control and its descendant controls as touched: — add markAllAsTouched () to AbstractControl
  13. Added an ng-new command that builds the project with Bazel
  14. Use image based cache for windows BuildKite
  15. Export NumberValueAccessor & RangeValueAccessor directives

Continue Reading →

Topics

ADFS (1) ADO .Net (1) Ajax (1) Angular (43) Angular Js (15) ASP .Net (14) Authentication (4) Azure (3) Breeze.js (1) C# (47) CD (1) CI (2) CloudComputing (2) Coding (7) CQRS (1) CSS (2) Design_Pattern (6) DevOps (4) DI (3) Dotnet (8) DotnetCore (16) Entity Framework (2) ExpressJS (4) Html (4) IIS (1) Javascript (17) Jquery (8) Lamda (3) Linq (11) microservice (3) Mongodb (1) MVC (46) NodeJS (8) React (11) SDLC (1) Sql Server (32) SSIS (3) SSO (1) TypeScript (1) UI (1) UnitTest (1) WCF (14) Web Api (15) Web Service (1) XMl (1)

Dotnet Guru Archives