Monday, February 12, 2018

Delegates

Delegates
class Program
    {
        public delegate void SomeMethodPtr();
        static void Main(string[] args)
        {
            SomeMethodPtr obj = new SomeMethodPtr(SomeMethod);
            obj();  //or obj.Invoke();
            Console.ReadLine();
        }

        static void SomeMethod()
        {
            Console.WriteLine("Some method called");
        }
    }
When we can call a method directly, what is the use of calling a method indirectly? Basically, a delegate is a representative to communicate between 2 parties.
The actual use of delegates is callback
public class MyClass
 {
  public delegate void MyDelegate(int input);
  public void LongRunningMethod(MyDelegate _delegate)
    {
      for (int i = 0; i < 2000; i++)
       {
        _delegate(i);
        }
    }
 }
static void XyzMethod(int i)
{            Console.WriteLine(i);
}
static void Main(string[] args)
{
 MyClass obj = new MyClass();
         obj.LongRunningMethod(XyzMethod);
 Console.ReadLine();
}
In this example, we can pass data between the caller and the program with the help of delegates.
Delegates are used by framework writes so that custom logic can be injected at the time of code.

Delegate,  Anonymous Method, Action, Func, Predicate
class Program
    {
        static double fn_Prodvalues(int val1, int val2)
        {
            return val1 * val2;
        }
        static void Main(string[] args)
        {
            Delegate_Prod dpObj; double result=0;

            dpObj = new Delegate_Prod(fn_Prodvalues);    // Delegate
            result = dpObj(5, 6);

            dpObj = delegate(int x, int y) { return x * y; };    // Anonymous Method  --introduced in c# 2.0
            result = dpObj(9, 6);

            dpObj = (x, y) => x * y;  // Lambda Expression -- Introduced in c# 3.0
            result = dpObj(7, 8);

            //Action<T>  no return type
            Action<int,int> action=delegate(int x, int y){Console.WriteLine(x*y);};
            Action<int, int> action2 = (x, y) => Console.WriteLine(x*y); ;
            action2(4, 4);

            //Func<T,out TResult> has a return type
            Func<int, int, int> func = (x, y) => x * y;
            result = func(5, 6);

            //Predicate<T> T is the input type, and it returns back only boolean
            Predicate<int> predicate = delegate(int x) { return x > 10; };
            Predicate<int> predicate2 = x => x > 10;
            Console.WriteLine(predicate(9));
  
            Console.WriteLine(result);
            Console.ReadKey();
        }
    }

Another example
static void Main(string[] args)
        {
            List<int> lst = new List<int>() { 2, 3, 4, 5, 6, 7, 4, 3, 45, 6 };
            //IEnumerable<int>result= lst.Where(x=>x>5);
            IEnumerable<int> result = lst.Where(fc); // Both Methods work
        }

        static Func<int, bool> fc = delegate(int c) { return c > 5; };


Extension Methods
An extension method is a static method of a static class, where the "this" modifier is applied to the first parameter
using System;
namespace ExtensionMethodsExample
{
   public static class Extension
    {
       public static int WordCount(this string str)
       {
           string[] userString = str.Split(new char[] { ' ', '.', '?' },
                                       StringSplitOptions.RemoveEmptyEntries);
           int wordCount = userString.Length;
           return wordCount;
       }
    }
}

An extension method having the same name and signature like as an instance method will never be called since it has low priority than instance method.
An extension method couldn't override the existing instance methods.
An extension method cannot be used with fields, properties or events.
The compiler doesn't cause an error if two extension methods with same name and signature are defined in two different namespaces and these namespaces are included in same class file using directives. Compiler will cause an error if you will try to call one of them extension method.

IEnumerable VS IQueryable


IEnumerable VS IQueryable
In LINQ to query data from database and collections, we use IEnumerable and IQueryable for data manipulation. IEnumerable is inherited by IQueryable, Hence IQueryable has all the features of IEnumerable and except this, it has its own features.


IEnumerable
IQueryable
Namespace
System.Collections Namespace
System.Linq Namespace
Derives from
No base interface
Derives from IEnumerable
Supported
Supported
Not Supported
Supported
How does it work
While querying data from database, IEnumerable executes select query on server side, load data in-memory on client side and then filter data. Hence does more work and becomes slow.
While querying data from database, IQueryable executes select query on server side with all filters. Hence does less work and becomes fast.
Suitable for
LINQ to Object and LINQ to XML queries
LINQ to SQL queries
Custom Query
Doesn’t support
Supports using CreateQuery and Executemethods
Extension method
parameter
Extension methods supported in IEnumerable takes functional objects.
Extension methods supported in IEnumerable takes expression objects, i.e., expression tree.
When to use
When querying data from in-memory collections like ListArray, etc.
When querying data from out-memory (like remote database, service) collections.
Best Uses
In-memory traversal
Paging

1.  IEnumerable<Employee> list = dc.Employees.Where(p => p.Name.StartsWith("S"));
2.  list = list.Take<Employee>(10);


1.  SELECT [t0].[EmpID], [t0].[EmpName], [t0].[Salary] FROM [Employee] AS [t0]
2.  WHERE [t0].[EmpName] LIKE @p0
Notice that in this query "top 10" is missing since IEnumerable filters records on client side

1.  IQueryable<Employee> list = dc.Employees.Where(p => p.Name.StartsWith("S"));
2.  list = list.Take<Employee>(10);


1.  SELECT TOP 10 [t0].[EmpID], [t0].[EmpName], [t0].[Salary] FROM [Employee] AS [t0]
2.  WHERE [t0].[EmpName] LIKE @p0
Notice that in this query "top 10" is exist since IQueryable executes query in SQL server with all filters.



Asp.net Core Continued

65 66 67 68 69 70 71 65 ASP.NET Core Identity It is a membership system Step 1 : Inherit from IdentityDbContext class instead of ...