Thursday, 18 October 2018

Delegate, Func, Action, Predicate

Delegate is a reference type that holds the reference of a class method. Any method which has the same signature as delegate can be assigned to delegate. Delegate is like function pointer in C++.
To read more delegates-c-sharp.html

Different Flavors of Delegate
  1. Func<TParameter, TOutput>
  2. Action<TParameter>
  3. Predicate<in T>
1- Func is logically similar to base delegate implementation. The difference is in the way we declare. At the time of declaration, we need to provide the signature parameter & its return type.

Func<string, int, int> tempFuncPointer;

Func is always used when you have return object or type from method. If you have void method, you should be using Action.

2- Action is used when we do not have any return type from method. Method with void signature is being used with Action delegate.

Action<string, int> tempActionPointer;

Similar to Func delegate, the first two parameters are the method input parameters. Since we do not have return object or type, all the parameters are considered as input parameters.

3- Predicate is a function pointer for method which returns boolean value. It is used to represent a set of criteria and determine if the argument matches the criteria. Declaration for the same looks like this:

Predicate<Employee> tempPredicatePointer;

Example Code: 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace TestAppConsole
{
    public class Program
    {
        public static void Main(string[] args)
        {
            Action<int> myAction = new Action<int>(DoSomething);
            myAction(123);           // Prints out "123"
                                     // can be also called as myAction.Invoke(123);

            Func<int, double> myFunc = new Func<int, double>(CalculateSomething);
            Console.WriteLine(myFunc(5));   // Prints out "2.5"


            Predicate<int> myPred = new Predicate<int>(CheckVal);   
            Console.WriteLine(myPred(1));    // Prints out "true"
           
            Console.ReadLine();
        }

        static void DoSomething(int i)
        {
            Console.WriteLine(i);
        }

        static double CalculateSomething(int i)
        {
            return (double)i / 2;
        }

        static bool CheckVal(int i)
        {
            return true;
        }

    }
}

In short:
Action is a delegate (pointer) to a method, that takes zero, one or more input parameters, but does not return anything.
Func is a delegate (pointer) to a method, that takes zero, one or more input parameters, and returns a value (or reference).
Predicate is a special kind of Func often used for comparisons.
Continue Reading →

Thursday, 11 October 2018

C# 6.0 New Features


1- String Interpolation
public string FullName => $"{FirstName} {LastName}";

2- Expression bodied function

        private Employee GetData(int Id) => Id != 0
         ? new Employee
         {
             EmpId = 1,
             EmpName = "Suraj"
         }
         : null;

        public class Employee
        {
            public int EmpId { get; set; }
            public string EmpName { get; set; }

        }

3- Null-conditional operators


var EmpId = emp?.EmpId;
var EmpName = emp?.EmpName ?? "Unspecified";

Continue Reading →

Tuesday, 9 October 2018

JavaScript Inheritance

JavaScript does not have classes unlike other languages. It uses the concept of prototypes and prototype chaining for inheritance.

Let’s implement prototype chaining

//SuperType constructor function
function SuperType(){
    this.name = "Virat"
   }
   
   //SuperType prototype
   SuperType.prototype.getSuperName = function(){
    return this.name
   }
   
   //SubType prototype function
   function SubType(){
    this.age = 26
   }
   
   //Inherit the properties from SuperType
   SubType.prototype = new SuperType();
   
   //Add new property to SubType prototype
   SubType.prototype.getSubAge = function(){
    return this.age;
   }
   
   //Create a SubType object
   var subTypeObj = new SubType();
   console.log(subTypeObj.name); //Output: Virat
   console.log(subTypeObj.age); //Output: 26
   console.log(subTypeObj.getSuperName()); //Output: Virat
   console.log(subTypeObj.getSubAge()); //Output: 26

Above code defines two consructor functions, SuperType and SubType. By default, SubType.prototype has a constructorfunction which points to the constructor function itself and proto property which inherits the default object properties.

//Inherit the properties from SuperType
SubType.prototype = new SuperType();

Now, SubType function has access to all the SuperType properties and methods.

Continue Reading →

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 →

Tuesday, 10 April 2018

MVC 5 Features

What’s New in ASP.NET MVC 5

Attribute Routing
This is where attribute based routing comes in. Using attribute based routing we can define the route in the same place where action method is defined.
   
[Route("Products/Electronics/{id}")]
     public ActionResult GetElectronicItems(string id)
     {
         ViewBag.Id = id;
          return View();
     }

To enable attribute based routing we need to add the following in the RouteConfig file.

      public static void RegisterRoutes(RouteCollection routes)
       {
           routes.MapMvcAttributeRoutes();
       }

Optional Parameter
We can also specify if there is any optional parameter in the URL pattern defined by the Route attribute with the “?” character.

      [Route("Products/Electronics/{id?}")]
      public ActionResult GetElectronicItems(int? id) {
          ViewBag.Id = id; return View();

      }

Route constraints
We can also specify parameter constraints placing the constraint name after the parameter name separated by colon. For example we can specify that the parameter type should be integer by using the following

[Route("Products/Electronics/{id:int}")]

Route Prefix
If we have multiple action methods in a controller all using the same prefix we can use RoutePrefix attribute on the controller instead of putting that prefix on every action method.

Like we can attach the following attribute on the controller
[RoutePrefix("Products")]

So now our Route attribute on our action method does not need to specify the common prefix
[Route("Electronics/{id}")]

Filter's in MVC
Filters in MVC provide us with an elegant way to implement cross cutting concerns.Cross cutting concerns is the functionality that is used across our application in different layers.Common example of such functionality includes caching ,exception handling and logging.

We can create global or controller filters in MVC 4.Global filters are filters that are applied to all the action methods in the application while controller filters apply to all the action methods in the controller.

We can create a global filter by creating a class and registering it as a global filter

public class TestGlobalFilterAttribute : ActionFilterAttribute
   {
       public override void OnActionExecuting(ActionExecutingContext context)
       {
           base.OnActionExecuting(context);
           context.RequestContext.HttpContext.Response.Write("Global filter's in MVC are cool...");
       }
   }

//Register our global filter
GlobalFilters.Filters.Add(new TestGlobalFilterAttribute()); 

Filter Overrides in MVC 5
Now if want to override our global action filter in one of our action method's then we just need to apply the OverrideActionFilters attribute.Below we have applied the attribute to the default About method in the HomeController.

[OverrideActionFilters]
public ActionResult About(){
ViewBag.Message = "Your application description page.";
return View();
}

Scaffolding
Scaffolding means generating code automatically from the model.Suppose we have some model for which we want to generate the skeleton code for the basic Create Read Update and Delete operations then instead writing the common code we can use Scaffolding feature of MVC 5.

Bootstrap
Twitter Bootstrap is added as the default user interface framework for an MVC application. Bootstrap is a free collection of HTML and CSS based design templates created at Twitter for designing forms, navigation, buttons, tables etc.

ASP.NET Identity

One ASP.NET

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# (55) CD (1) CI (2) CloudComputing (2) Coding (10) CQRS (1) CSS (2) Design_Pattern (7) DevOps (4) DI (3) Dotnet (10) DotnetCore (20) Entity Framework (5) ExpressJS (4) Html (4) IIS (1) Javascript (17) Jquery (8) jwtToken (4) 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