Sunday, 21 February 2016

Delegates & its 5 Modern Flavors (Func, Action, Predicate, Converter, Comparison)

Introduction

Delegate is a very powerful feature available in the .NET Framework. In this article, we will explore delegate & its new features which are being introduced in the framework. I will be using Visual Studio 2013 for coding sample code, assuming that you do have basic knowledge of .NET C# code.
I will be explaining the following flavors in this articles:
  1. Func
  2. Action
  3. Predicate
  4. Converter
  5. Comparison
I would like to get feedback on this article. Please feel to share your comments or you can also email me at shettyashwin@outlook.com. If you like this article, please don't forget to rate it.

Background

As part of the Interview panel, I have been asked to interview a lot of candidates for the opening we had. At the time of interview when questions were asked on delegates & its features, very few candidates were able to answer this question. Even one of my team members was surprised when I optimized his code & started using action delegate. Hence, I decided to write this article which shares some details on delegates & some of its features.

What are Delegates?

If I can put it into simple words, Delegate is a pointer to a method. Delegate can be passed as a parameter to a method. We can change the method implementation dynamically at run-time, only thing we need to follow doing so would be to maintain the parameter type & return type.
For example: If I declare delegate with return type int & two parameters as string and int respectively, all the references which are set using this delegate should follow this signature.
internal class Program
   {
       protected delegate int tempFunctionPointer(string strParameter, int intParamater);

       public static void Main()
       {
           DelegateSample tempObj = new DelegateSample();
           tempFunctionPointer funcPointer = tempObj.FirstTestFunction;
           funcPointer("hello", 1);
           Console.ReadKey();
           funcPointer = tempObj.SecondTestFunction;
           funcPointer("hello", 1);
           Console.ReadKey();
       }
   }

   public class Employee
   {
       public string Name { get; set; }
       public int Age { get; set; }
   }

   public class XEmployee
   {
       public string Name { get; set; }
       public int Age { get; set; }

       public bool IsExEmployee {
           get { return true; }
       }
   }

  public class DelegateSample
   {
       public int FirstTestFunction(string strParameter, int intParamater)
       {
           Console.WriteLine("First Test Function Execution");
           Console.WriteLine(strParameter);
           return intParamater;
       }

       public int SecondTestFunction(string strParameter, int intParamater)
       {
           Console.WriteLine("Second Test Function Execution");
           Console.WriteLine(strParameter);
           return intParamater;
       }

       public void ThirdTestFunction(string strParameter, int intParamater)
       {
           Console.WriteLine("Third Test Function Execution");
           Console.WriteLine(strParameter);
       }

       public bool FourthTestFunction(Employee employee)
       {
           return employee.Age < 27;
       }

       public XEmployee FifthTestFunction(Employee employee)
       {
           return new XEmployee() {Name = employee.Name, Age = employee.Age};
       }

       public int SixTestFunction(Employee strParameter1, Employee strParamater2)
       {
           return strParameter1.Name.CompareTo(strParamater2.Name);
       }
   }
Delegates can be executed synchronous or asynchronously. Code sample mentioned above is an example of synchronous processing. To make it an Asynchronous process, we need to use BeginInvoke method.
funcPointer.BeginInvoke("Hello", 1, null, null); 
First two parameters are the inputs for the function. 3rd parameter can be set for getting call back after execution of process. Detailed explanation of making Asynchronous call is available here.

When Do I Use Delegate?

Looking at the sample above, a lot of us might think this can be also achieved using Interface or abstract class, then why do we need delegate.
Delegate can be used in the following scenarios:
  1. If you don’t want to pass your interface or abstract class dependence to internal class or layers.
  2. If the code doesn't need access to any other attributes or method of the class from which logic needs to be processed.
  3. Event driven implementation needs to be done.

Different Flavors of Delegate

As .NET Framework evolved over a period of time, new flavors have been added to keep implementation simple & optimized. By default, you get all the features & functionality with flavors which you get with delegate. Let’s have a look at Func delegate.

Func<TParameter, TOutput>

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;
First two parameters are the method input parameters. 3rd parameter (always the last parameter) is the out parameter which should be the output return type of the method.
Func<string, int, int> tempFuncPointer = tempObj.FirstTestFunction;
int value = tempFuncPointer("hello", 3);
Console.ReadKey();
Func is always used when you have return object or type from method. If you have void method, you should be using Action.

Action<TParameter>

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.
Action<string, int> tempActionPointer = tempObj.ThirdTestFunction;
tempActionPointer("hello", 4);
Console.ReadKey();  

Predicate<in T>

Predicate is a function pointer for method which returns boolean value. They are commonly used for iterating a collection or to verify if the value does already exist. Declaration for the same looks like this:
Predicate<Employee> tempPredicatePointer;  
For sample, I have created an Array which holds a list of Employees. Predicate is used to get employee below age of 27:
Predicate<Employee> tempPredicatePointer = tempObj.FourthTestFunction;
Employee[] lstEmployee = (new Employee[]
{
   new Employee(){ Name = "Ashwin", Age = 31},
   new Employee(){ Name = "Akil", Age = 25},
   new Employee(){ Name = "Amit", Age = 28},
   new Employee(){ Name = "Ajay", Age = 29},
});

Employee tempEmployee = Array.Find(lstEmployee, tempPredicatePointer);
Console.WriteLine("Person below 27 age :" + tempEmployee.Name);
Console.ReadKey();

<pre lang="cs">//Code block which gets executed while iteration 
public bool FourthTestFunction(Employee employee)
{
   return employee.Age < 27;
}  

Converter<TInput, TOutput>

Convertor delegate is used when you need to migrate / convert one collection into another by using some algorithm. Object A gets converted into Object B.
Converter<Employee, XEmployee> tempConvertorPointer 
                = new Converter<Employee, XEmployee>(tempObj.FifthTestFunction); 
For sample, I have created XEmployee entity. All the Employees in the collection get migrated to XEmployee Entity.
 Employee[] lstEmployee = (new Employee[]
            {
                new Employee(){ Name = "Ashwin", Age = 31},
                new Employee(){ Name = "Akil", Age = 25},
                new Employee(){ Name = "Amit", Age = 28},
                new Employee(){ Name = "Ajay", Age = 29},
            });

Converter<Employee, XEmployee> tempConvertorPointer 
                = new Converter<Employee, XEmployee>(tempObj.FifthTestFunction);

XEmployee[] xEmployee = Array.ConvertAll(lstEmployee, tempConvertorPointer);
Console.ReadKey(); 

//Code block which get executed while iteration 
 public XEmployee FifthTestFunction(Employee employee)
 {
    return new XEmployee() {Name = employee.Name, Age = employee.Age};
 } 

Comparison<T>

Comparison delegate is used to sort or order the data inside a collection. It takes two parameters as generic input type and return type should always be int. This is how we can declare Comparison delegate.
Comparison<string> tempComparison = new Comparison<string>(tempObj.SixTestFunction); 
In this sample, Employee Name is used to Sort the order. All the entity inside the collection will be processed using SixthTestFunction which contains the logic for processing / sorting the data as per our requirement.
Comparison<Employee> tempComparisonPointer
                = new Comparison<Employee>(tempObj.SixTestFunction);
            Array.Sort(lstEmployee, tempComparisonPointer);
            Console.ReadKey();

 public int SixTestFunction(Employee strParameter1, Employee strParamater2)
        {
            return strParameter1.Name.CompareTo(strParamater2.Name);
        }

Points of Interest

Using the new delegates, we can achieve better level of abstraction & performance can also been gained by avoiding unnecessary iteration or conversion logic. All three delegates (PredicateConverterComparison) do have optimized internal logic for iteration.

References

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. Both have its own importance to query data and data manipulation. Let’s see both the fetures and take the advantage of both the fetures to boost your LINQ Query performance.

IEnumerable

  1. IEnumerable exists in System.Collections Namespace.
  2. IEnumerable can move forward only over a collection, it can’t move backward and between the items.
  3. IEnumerable is best to query data from in-memory collections like List, Array etc.
  4. While query data from database, IEnumerable execute select query on server side, load data in-memory on client side and then filter data.
  5. IEnumerable is suitable for LINQ to Object and LINQ to XML queries.
  6. IEnumerable supports deferred execution.
  7. IEnumerable doesn’t supports custom query.
  8. IEnumerable doesn’t support lazy loading. Hence not suitable for paging like scenarios.
  9. Extension methods supports by IEnumerable takes functional objects.

IEnumerable Example

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

Generated SQL statements of above query will be :

  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

IQueryable

  1. IQueryable exists in System.Linq Namespace.
  2. IQueryable can move forward only over a collection, it can’t move backward and between the items.
  3. IQueryable is best to query data from out-memory (like remote database, service) collections.
  4. While query data from database, IQueryable execute select query on server side with all filters.
  5. IQueryable is suitable for LINQ to SQL queries.
  6. IQueryable supports deferred execution.
  7. IQueryable supports custom query using CreateQuery and Execute methods.
  8. IQueryable support lazy loading. Hence it is suitable for paging like scenarios.
  9. Extension methods supports by IQueryable takes expression objects means expression tree.

IQueryable Example

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

Generated SQL statements of above query will be :

  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.
Summary
In this article I try to explain the difference between IEnumerable and IQueryable. I hope after reading this article you will be able to boost your LINQ query performance. I would like to have feedback from my blog readers. Please post your feedback, question, or comments about this article.

Asp.net HTTP Modules

ASP.NET HTTP Modules:
HTTP Modules:
HTTP Modules use to intercept HTTP requests for modifying or utilize HTTP based requests according to needs like authentication, authorization, session/state management, logging, modifying Response, URL rewriting, Error handling, Caching....
HTTP Modules are activated/called/invoked before and after HTTP Handler execution.
HTTP Modules are integral part of ASP.NET framework now and heavily being used as it cater grips upon request and let developers to generate response in a customized way, according to user requirement. Web development is all about playing with request from client to server and response from server to client.
When any request goes to web server, request passes through different phases and then at last response gets generate for client.
HTTP Modules are .Net based components/Plugins and programmed by implementing System.Web.IHTTPModule interface of .Net.

HTTP Module Background:

Before HTTP Modules, web developers/programmers used to implement Internet Server Application Programming Interface (ISAPI) Filters like me (wish interviewer asked me about by terms of ISAPI at that time then I tell him (Big Grin | :-D )), anyhow jokes apart.
As name implies ISAPI is a web server based API and used to manage request which comes to web server and generate response. ISAPI based upon web server (IIS) where as NSAPI is Netscape based web server API.
ISAPI is based upon win32 DLL and programmed in unmanaged code C/C++, which is somehow painful (:$) and due to unmanaged code, is less reliable, scalable and quite complex to implement than HTTP Modules by managed code under the framework of .Net. Hope you got it why ISAPI Filters replaced by HTTP Modules (;))
Asp.net requests goes through HTTP Modules events just like (oil flowing through pipeline and that pipeline has some filters to refine that oil)
HTTP Modules Events:
Every HTTP Module must implement following two methods of IHTTPModule interface:
Init: To register/initialize event handler to the events of HTTP Module for HTTP based application.
Dispose: To perform a clean up code means resource releasing, object removing from memory and such other resources releasing which used explicitly.
Following are list of events with their brief description:
BeginRequest: Event fired whenever any asp.net based request sent to web server. If you need to do perform at the beginning of a request for example, modify show banners, log HTTP Header information, Get/Set cultures, Response.Filter to generate response for browser according to your need.
AuthenticateRequest: If you want to check authentication of request that request comes from authenticated user or not means wants to implement custom authentication scheme. For example, look up a requested user credentials against a database to validate.
AuthorizeRequest: This method is used specifically to implement authorization mechanisms means authenticated user/request has what privileges/rights/access in that specific application for example, either user has access on all pages or not of that website or has write to create file or not or visit report pages and like this.
ResolveRequestCache: This event determines if a page served from the Output cache. If you want to write your own caching module (for example, build a file-based cache rather than a memory cache), synchronize this event to determine whether to serve the page from the cache.
AcquireRequestState: Session state is retrieved from the state store. If you want to build your own state management module, synchronize this event to grab the Session state from your state store.
PreRequestHandlerExecute: This event occurs before the HTTP handler is executed.
PostRequestHandlerExecute: This event occurs after the HTTP handler is executed.
ReleaseRequestState: Session state is stored back in the state store. If you are building a custom session state module, you must store your state back in your state store.
UpdateRequestCache: This event writes from output back to the Output cache. If you are building a custom cache module, you have to write the output back to your cache.
Error: this event always occurs when any exception (unhandled error occurs in application, this event specifically uses to handle or log error messages of that web application. (Heavily used in Error Logging Modules and Handlers (ELMAH) kind of applications). You can learn about ELMAH more from following link in detail:http://dotnetslackers.com/articles/aspnet/ErrorLoggingModulesAndHandlers.aspx
EndRequest: Request has been completed. You may want to build a debugging module that gathers information throughout the request and then writes the information on the page.
By above events list you must be getting wonder about difference between Global.asax as somehow events of Global.asax are pretty same, so let me tell you difference between Global.asax and HTTP Module (another common question asked in interviews)
But you need to register/initialize these Events explicitly in “Init” method; following is sample code of IHTTPModule implementation for couple of events.
"kwd">using System;
"kwd">using System.Web;
"kwd">using System.Collections;

"kwd">public class HelloWorldModule : IHttpModule
{
    "kwd">public String ModuleName
    {
        "kwd">get { "kwd">return "st">"HelloWorldModule"; }
    }

    "cmt">// In the Init function, register for HttpApplication 
    // events by adding your handlers.
    "kwd">public void Init(HttpApplication application)
    {
         application.BeginRequest += ("kwd">new EventHandler("kwd">this.Application_BeginRequest));
         application.EndRequest += ("kwd">new EventHandler("kwd">this.Application_EndRequest));

    }

    "cmt">// Your BeginRequest event handler.

    "kwd">private void Application_BeginRequest(Object source, EventArgs e)
    {
        HttpApplication application = (HttpApplication)source;
        HttpContext context = application.Context;
        context.Response.Write("st">"&lt;h1><font color=red>HelloWorldModule: Beginning of Request</font></h1><hr>");
    }

    "cmt">// Your EndRequest event handler.

    "kwd">private void Application_EndRequest(Object source, EventArgs e)
    {
        HttpApplication application = (HttpApplication)source;
        HttpContext context = application.Context;
        context.Response.Write("st">"&lt;hr><h1><font color=red>HelloWorldModule: End of Request</font></h1>");
    }
    "kwd">public void Dispose()
    {
    }
}
Ref: msdn
HTTP Module vs Global.asax

1. HTTP Module is pluggable component that’s why could be use for other web applications as well as on other server or in same server where as Global.asax couldn’t.
2. According to life cycle of Request, Request passed through HTTP Module first and then through Global.asax
3. Following are list of events which are supported in Global.asax but unfortunately not in HTTP Module.
  1. Application_OnStart
    This event is raised when the very first request passed through the web application.
  2. Application_OnEnd
    This event is raised just before the application is going to terminate.
  3. Session_OnStart
    This event is raised for the very first request of the user's session.
  4. Session_OnEnd
    This event is raised when the session is abandoned or expired.
Here I would like to share one more interview experience of me but now its about my friend’s interview, for which he did preparation from me/took my help or guidance for it Anyhow whilst I was helping him in his preparation for asp.net technical interview, I asked him: “ tell me when session starts?” He replied: “Simple when user logins from login page”, I said ok! Suppose site has no login page and could be accessible by anonymous user, session will never start and Session_OnStart event of Global.asax will never fire then is it? He replied: of course, I couldn’t stop me to smile; I might not laugh if he has no experience or less experience but he has more than 4 years of experience. Anyhow next day when he went for interview, interviewer asked him the same question and he smiled and said, “If you think I will say when user login session_Onstart event will fire then you are wrong. (They also started laughing).
Anyhow normally people say or according to books to tell reader in easy way that session are user based, NO! Sessions are actually browser based. Anyhow shouldn’t go away from topic as much.
Registering HTTP Module
The following is an example of registering/adding an HTTP module:
  <httpModules>    <add type="ClassName, AssemblyName" name="ModuleName" />  <httpModules>

The following is a general example of removing an HTTP module from web application.

  <httpModules>    <remove name="ModuleName" />  <httpModules>

All code suppose to be in either web.config or in machine.config
Following is the list of module is defined at machine.config or web.config by default. ($WINDOWS$\Microsoft.NET\Framework\$VERSION$\CONFIG\ CONFIG Files)

<httpModules><add name="OutputCache" type="System.Web.Caching.OutputCacheModule"/><add name="Session" type="System.Web.SessionState.SessionStateModule"/><add name="WindowsAuthentication" ="System.Web.Security.WindowsAuthenticationModule"/><add name="FormsAuthentication" type="System.Web.Security.FormsAuthenticationModule"/><add name="PassportAuthentication" type="System.Web.Security.PassportAuthenticationModule"/><add name="RoleManager" type="System.Web.Security.RoleManagerModule"/><add name="UrlAuthorization" type="System.Web.Security.UrlAuthorizationModule"/><add name="FileAuthorization" type="System.Web.Security.FileAuthorizationModule"/><add name="AnonymousIdentification" type="System.Web.Security.AnonymousIdentificationModule"/><add name="Profile" type="System.Web.Profile.ProfileModule"/><add name="ErrorHandlerModule" type="System.Web.Mobile.ErrorHandlerModule, System.Web.Mobile, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"/><add name="ServiceModel" type="System.ServiceModel.Activation.HttpModule, System.ServiceModel, Version=3.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"/></httpModules>
Performance:
You can improve performance of your application by removing default (but not in used) HTTP Modules registered in machine.config file as these are activated/invoked/called on each request for your application unnecessarily by <remove …> for example,

<httpModules>    <!-- Remove unnecessary Http Modules for faster pipeline -->     <remove name="Session" />      <remove name="WindowsAuthentication" />     <remove name="PassportAuthentication" />     <remove name="AnonymousIdentification" />     <remove name="UrlAuthorization" />

     <remove name="FileAuthorization" />     <remove name="OutputCache" />     <remove name="RoleManager" />     <remove name="Profile" />     <remove name="ErrorHandlerModule" />     <remove name="ServiceModel" />  </httpModules>
But please make sure before its implementation/applying that you are not using them. If you are using any of these, you may exclude that from existing list.
Conclusion
HTTP Modules are quite simple to understand and quite flexible by means of its number of events. HTTP modules integrate with whole application and every request passed through HTTP Module. So HTTP Module should be implemented very carefully. Take the time to completely understand its advantages, disadvantages, implementation and concepts before implementing a solution.
To get more detailed understanding of HTTP Modules with real time examples implmentation, I would recommend you to visit following links:

Recommended Links:
For URL Redirection example click here
For Security based example click here
For IP based security example click here
For Error Manager Example click here
For Videos click here and  here

What should you required to learn machine learning

  To learn machine learning, you will need to acquire a combination of technical skills and domain knowledge. Here are some of the things yo...