Wednesday, 26 September 2018

Angular Code Questions

Q: How to get data from url in Angular 
http://localhost:4200/about/7

const routesRoutes = [
    { path: ''component: DatabindingComponent },
    { path: 'about/:id'component: AboutComponent },
    { path: 'notfound'component: NotfoundComponent },
    { path: '**'redirectTo: 'notfound' }
   ];

export class AboutComponent implements OnInit {
    idstring;  id2string;
    constructor(private routeActivatedRoute) { }
    
    ngOnInit() {
       this.route.params.subscribe((params=> {
       this.id = params.id;
this.id2 = this.route.snapshot.params.id;
      });
    }

Q: Data Binding in Angular

databinding.component.ts
export class DatabindingComponent implements OnInit {
    companystring;
    urlstring;
    name:string;
    constructor() {}
    
    ngOnInit() {
    this.company = 'Dot Net Guru';
    this.url = 'http://www.dotnetguru.in';
    this.name='Suraj';
    }
    
    Greet() {
     console.log(this.name);
     alert('Hi from Angular!');
     }
    }

databinding.component.htm
//Interpolation
<p>{{company}}, {{name}}</p>
<img src='{{imagePath}}'/>
//Property Binding
<a [href]="url">Website</a>
<img [src]='imagePath'/>
<input type="text" [value]="name"/>
//Event Binding
<button type="button" (click)="Greet()">Greet</button>
//Two Way data binding
<input type="text" [(ngModel)]="name"/

Angular attribute binding
<tr><th [attr.colspan]="columnSpan">Employee Details</th></tr>

Angular class binding: https://www.youtube.com/
Angular style binding: https://www.youtube.com/

Q: Directive (If, If-else, loop, switch-case)

dir.component.ts
export class DirComponent implements OnInit {
    numnumber;
    alphabet:string;
    colors=['red','blue','green'];
    
    constructor() {}
    ngOnInit() {
       this.num = 1;
      }
    }

dir.component.html
<p>
<input type="number" [(ngModel)]="num" />
</p>

<h3>ngIf</h3>
<div *ngIf="num%2==0">
Even Number
</div>

<div *ngIf="num%2>0">
Odd Number
</div>

<h3>ngIf..else</h3>
<div *ngIf="num%2==0 then divif; else divelse"></div>
<ng-template #divif>Even Number</ng-template>
<ng-template #divelse>Odd Number</ng-template>

<h3>ngSwitch</h3>
<p>
<input type="text" [(ngModel)]="alphabet" />
</p>

<div [ngSwitch]="alphabet">
<div *ngSwitchCase="'a'">Vowel</div>
<div *ngSwitchCase="'e'">Vowel</div>
<div *ngSwitchCase="'i'">Vowel</div>
<div *ngSwitchCase="'o'">Vowel</div>
<div *ngSwitchCase="'u'">Vowel</div>
<div *ngSwitchDefault>Not Vowel</div>
</div>

<h3>Loop</h3>
<ul>
<li *ngFor="let item of colors; let i=index">
{{i+1}} {{item}}
</li>
</ul>
Output: 

Q: Pipe
<tr *ngFor="let item of emp | orderBy: 'name' : true" >
<td>{{item.name | uppercase}}</td>
<td>{{item.address | lowercase | reverse}}</td>
<td>{{item.joining | date:'dd/MM/yyyy'}}</td>
<td>{{item.salary | currency:'INR'}}</td>
</tr>

Q: Access data from parent to child component

Parent Component
@Component({
    selector: 'app-master',
    templateUrl: './master.component.html',
    styles: []
  })
  export class MasterComponent implements OnInit {
    companystring;
    constructor() {
      this.company = 'Dot Net Tricks';
    }
    ngOnInit() {}
  }

Parnet Component html
<app-details [companyName]="company"></app-details>

Child Component
import { ComponentOnInitInputOutputfrom '@angular/core';

@Component({
  selector: 'app-details',
  templateUrl: './details.component.html',
  styles: []
})
export class DetailsComponent implements OnInit {
  @Input() companyNamestring;
  constructor() { }

  ngOnInit() {}
}

Child Component html
<p>{{companyName}}</p>

Q: Access data from child to parent component

Child Component html
<button type="button" (click)="SendMessage()">Send Msg</button>

Child Component
import {Component,OnInit,Output,EventEmitterfrom '@angular/core';
@Component({
  selector: 'app-details',
  templateUrl: './details.component.html',
  styles: []
})
export class DetailsComponent implements OnInit {
@Output() sendMsgEventEmitter<string>=new EventEmitter<string>();
  constructor() {}
  ngOnInit() {}

  SendMessage() {
    this.sendMsg.emit('Message from Child');
  }
}

Parent Component html
<h2>Parent Component : {{msg}}</h2>
<app-details [companyName]="company" (sendMsg)="ReceivedMsg($event)"></app-details>

Parent Component 
import { ComponentOnInit } from '@angular/core';

@Component({
  selector: 'app-master',
  templateUrl: './master.component.html',
  styles: []
})
export class MasterComponent implements OnInit {
  msgstring;
  constructor() {}
  ngOnInit() {}
  ReceivedMsg(msgstring) {
    this.msg = msg;
    alert(msg);
  }
}

Q: What is the equivalent of ngShow and ngHide in Angular?
Just bind to the hidden property.
[hidden]="!myVar"

*ngIf vs [hidden]
*ngIf effectively removes its content from the DOM while [hidden] modifies the display property and only instructs the browser to not show the content but the DOM still contains it.

Continue Reading →

Sunday, 23 September 2018

Introduction To Design Pattern

Design patterns represent the best practices used by experienced object-oriented software developers. Design patterns are solutions to general problems that software developers faced during software development. 
Design pattern are evolved over a period of time by experienced software developers. They promote re usability which leads to a more robust and maintainable code. 
The Design patterns can be classified into three main categories: 
  1. Creational Patterns
  2. Structural Patterns
  3. Behavioral Patterns
Creational Patterns- Creational design patterns are related to the way of creating objects. Creational design patterns are used when a decision is made at the time of instantiation of a class.  
  • Factory method/Template
  • Singleton
  • Abstract Factory
  • Builder
  • Prototype
Structural Patterns- Structural design patterns are concerned with how classes and objects can be composed, to form larger structures.
 The structural design patterns simplifies the structure by identifying the relationships.
These patterns focus on, how the classes inherit from each other and how they are composed from other classes.
  • Adapter
  • Proxy
  • Bridge
  • Filter
  • Composite
  • Decorator
  • Façade
  • Flyweight
Behavioral Patterns- Behavioral patterns are concerned with the assignment of responsibilities between objects, or, encapsulating behavior in an object and delegating requests to it.
Unlike the Creational and Structural patterns, which deal with the instantiation process and the blueprint of objects and classes, the central idea here is to concentrate on the way objects are interconnected. In a word, we can say this: If Creational is about instantiation, and Structural is the blueprint, then Behavioral is the pattern of the relationship among objects.
  • Interpreter
  • Strategy pattern
  • Template method/ pattern
  • Chain of responsibility
  • Command pattern
  • Iterator pattern
  • Visitor pattern
What Is Factory Pattern?
Factory it's such a Design Pattern which defines an interface for creating an object, but lets the classes that implement the interface decide which class to instantiate. Factory Pattern lets a class postpone instantiation to sub-classes. For more info. clink on the link  http://softmindit.blogspot.com/Link 1

What is Singleton Pattern
Singleton pattern is a creational pattern which allows only one instance of a class to be created which will be available to the whole application. The major advantage of Singleton design pattern is its saves memory because the single instance is reused again and again; there is no need to create a new object at each request. For example, in our application, we can use a single database connection shared by multiple objects, instead of creating a database connection for every request.

What are the drawbacks of using singleton design pattern?
The major drawbacks of using singleton design pattern are:
a)Singleton causes code to be tightly coupled. The singleton object is exposed globally and is available to a whole application. Thus, classes using this object become tightly coupled; any change in the global object will impact all other classes using it.
b)Singleton Pattern does not support inheritance.

Adapter: is a structural design pattern This allows incompatible classes to work together by converting the interface of one class into another.  
 If you have two applications, with one spitting out output as XML with the other requiring JSON input, then you’ll need an adapter between the two to make them work seamlessly.

Proxy: is a structural design pattern that provides an object that acts as a substitute for a real service object used by a client. A proxy receives client requests, does some work (access control, caching, etc.) and then passes the request to a service object. Click here for more

What Is Strategy Pattern?
In Strategy pattern, a class behavior or its algorithm can be changed at run time. This type of design pattern comes under behavior pattern.
In Strategy pattern, we create objects which represent various strategies and a context object whose behavior varies as per its strategy object. The strategy object changes the executing algorithm of the context object.
Real-World Analogy: Imagine that you have to get to the airport. You can catch a bus, order a cab, or get on your bicycle. These are your transportation strategies. You can pick one of the strategies depending on factors such as budget or time constraints. LINK 1Link 2

Intercepting Filter Pattern: The intercepting filter design pattern is used when we want to do some pre-processing / post-processing with request or response of the application. Filters are defined and applied on the request before passing the request to actual target application. Filters can do the authentication/ authorization/ logging or tracking of request and then pass the requests to corresponding handlers. Following are the entities of this type of design pattern.

Observer PatternThis pattern is a one-to-many dependency between objects so that when one object changes state, all its dependents are notified.
 For the sake of simplicity, think about what happens when you follow someone on Twitter. You are essentially asking Twitter to send you (the observer) tweet updates of the person (the subject) you followed. The pattern consists of two actors, the observer who is interested in the updates and the subject who generates the updates.
 A subject can have many observers and is a one to many relationship. However, an observer is free to subscribe to updates from other subjects too. You can subscribe to news feed from a Facebook page, which would be the subject and whenever the page has a new post, the subscriber would see the new post.


MVC Pattern: MVC Pattern stands for Model-View-Controller Pattern. This pattern is used to separate application's concerns.
For more design patter under the link Click here
Continue Reading →

Garbage Collection and Finalization Queue

Finalize is a special method that is automatically called by the garbage collector (GC) before the object is collected. This method is only called by the GC. The destructor in C# is automatically translated into Finalize. You can see the IL code using IDASM where you will see that destructor is renamed to finalize.

When a new object is created, the memory is allocated in the managed heap. If newly created object have a Finalize() method or a destructor then a pointer pointing to that object is put into the finalization queue. Basically, finalization queue is an internal data structure that is controlled and managed by the GC. Hence each pointer in finalization queue points to an object that have its Finalize method call before the memory is reclaimed.

Generations
The heap is organized into generations so it can handle long-lived and short-lived objects. Garbage collection primarily occurs with the reclamation of short-lived objects that typically occupy only a small part of the heap. There are three generations of objects on the heap:

Generation 0: This is the youngest generation and contains short-lived objects. An example of a short-lived object is a temporary variable. Garbage collection occurs most frequently in this generation.

Generation 1: This generation serves as a buffer between short-lived objects and long-lived objects.

Generation 2: This generation holds long-lived objects like a static and global variable, that needs to be persisted for a certain amount of time. Objects which are not collected in generation Zero, are then moved to generation 1, such objects are known as survivors, similarly objects which are not collected in generation One, are then moved to generation 2 and from there onwards objects remain in the same generation.

Before the collections for dead objects, the garbage collector looks into the finalization queue for pointers identifies these objects. If the pointer found, then the pointer is flushed from the finalization queue and append to the freachable queue .The freachable queue is also an internal data structure and controlled by the garbage collector. Now each and every pointer with in the freachable queue will identify an object that is ready to have its Finalize method called.

Memory allocation
  • Garbage Collector (GC) is the part of the .NET framework that allocates and releases memory for your .NET applications.
  • When a new process is started, memory is allocated in to the managed heap.
  • Objects are allocated in the heap continuously one after another.
  • Memory allocation is a very fast process as it is just the adding of a value to a pointer.
Memory release
The garbage collector's optimizing engine determines the best time to perform a collection based on the allocations being made. When the garbage collector performs a collection, it releases the memory for objects that are no longer being used by the application. It determines which objects are no longer being used by examining the application's roots. An application's roots include static fields, local variables and parameters on a thread's stack, and CPU registers. Each root either refers to an object on the managed heap or is set to null. The garbage collector has access to the list of active roots that the just-in-time (JIT) compiler and the runtime maintain. Using this list, the garbage collector creates a graph that contains all the objects that are reachable from the roots. https://docs.microsoft.com

When GC Gets Triggered?
There are no specific timings for GC to get triggered, GC automatically starts operation on the following conditions:
  1. When virtual memory is running out of space.
  2. When allocated memory is suppressed acceptable threshold (when GC found if the survival rate (living objects) is high, then it increases the threshold allocation).
  3. When we call GC.Collect() method explicitly, as GC runs continuously, we actually do not need to call this method.
Continue Reading →

Topics

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

Dotnet Guru Archives