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 routes: Routes = [
{ path: '', component: DatabindingComponent },
{ path: 'about/:id', component: AboutComponent },
{ path: 'notfound', component: NotfoundComponent },
{ path: '**', redirectTo: 'notfound' }
];

export class AboutComponent implements OnInit {
id: string;
constructor(private route: ActivatedRoute) { }

ngOnInit() {
   this.route.params.subscribe((params) => {
   this.id = params.id;
  });
}

Q: Data Binding in Angular

databinding.component.ts

export class DatabindingComponent implements OnInit {
company: string;
url: string;
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
<h3>Interpolation</h3>
<p>{{company}}, {{name}}</p>

<h3>Property Binding</h3>
<a [href]="url">Website</a>
<input type="text" [value]="name"/>

<h3>Event Binding</h3>
<button type="button" (click)="Greet()">Greet</button>

<h3>Two Way data binding</h3>
<input type="text" [(ngModel)]="name"/>

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

dir.component.ts
export class DirComponent implements OnInit {
num: number;
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 {
  company: string;
  constructor() {
    this.company = 'Dot Net Tricks';
  }
  ngOnInit() {}
}

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

Child Component
import { Component, OnInit, Input, Output} from '@angular/core';

@Component({
  selector: 'app-details',
  templateUrl: './details.component.html',
  styles: []
})
export class DetailsComponent implements OnInit {
  @Input() companyName: string;
  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,EventEmitter} from '@angular/core';
@Component({
  selector: 'app-details',
  templateUrl: './details.component.html',
  styles: []
})
export class DetailsComponent implements OnInit {
@Output() sendMsg: EventEmitter<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 { Component, OnInit } from '@angular/core';

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


Continue Reading →

Topics

ADO .Net (2) Ajax (1) Angular Js (17) Angular2 (22) ASP .Net (14) Azure (1) Breeze.js (1) C# (48) CloudComputing (1) CMS (1) CSS (2) Design_Pattern (3) DI (3) Dotnet (21) Entity Framework (3) ExpressJS (4) Html (3) IIS (1) Javascript (5) Jquery (9) Lamda (2) Linq (11) Mongodb (1) MVC (47) NodeJS (7) RDLC (1) Report (1) Sql Server (29) SSIS (3) SSRS (2) WCF (12) Web Api (8) Web Service (1) XMl (1)