Wednesday, October 29, 2014

Covariance and Contravariance in C# - Part 2

In the previous post(http://softtechhelp.blogspot.in/2014/10/covariance-and-contravariance-in-c.html) we talked about the fundamentals of covariance and contravariance. In this post we will focus on more advance understanding of the concept.
Once we talk about covariance/contravariance, we should keep in mind that
1) Classes can not be covariant or contravariant.
2) Value type can not played around in covariant/contravariant manner.i.e. we can not talk about covariance or contravariance for IFoo<int>

In the previous post we talked about how Generic types can be created in covariant/contravariant manner. Today we will talk about how function/delegate can be used/created covariantly/contravariantly.

Delegates -
A delegate can be create in covariant or contravariant manner, or both together.
class Program
    {
        static void Main(string[] args)
        {          
            CovariantDel<Derived> d1 = GetDerived;                                 //1
            CovariantDel<Base> b1 = d1;                                                     //2
            b1();                                                                                             //3
            ContravariantDel<Base> b2 = PutBase;                                     //4
            ContravariantDel<Derived> d2 = b2;                                         //5
            d2(new Derived());                                                                      //6

            //Input Derived, Output Base
            CoVariantAndContravariantDel<Derived, Base> db1 = PutBaseGetDerive;  //7
            //Input Base, Output Base
            CoVariantAndContravariantDel<Base, Base> bb = PutBaseGetDerive;     //8
            //Input Base, Output Derived
            CoVariantAndContravariantDel<Base, Derived> bd1 = PutBaseGetDerive; //9
            //Input Derived, Output Derived
            CoVariantAndContravariantDel<Derived, Derived> dd = PutBaseGetDerive;//10
        }

        //Input Base and returns Derived
        public static Derived PutBaseGetDerive(Base b)
        {
            return b as Derived ?? new Derived();
        }
        public static void PutBase(Base b)
        {
            Console.WriteLine(b.ToString());
        }
        public static Derived GetDerived()
        {
            return new Derived();
        }
    }

    public delegate Tout CovariantDel<out Tout>();
    public delegate void ContravariantDel<in Tin>(Tin t);

    //Covariant return type and contravariant input
    public delegate Tout CoVariantAndContravariantDel<in Tin,out Tout>(Tin t);  
    public class Base { }
    public class Derived : Base { }  

Lets analyze the above code.
Covariance - CovariantDel is a delegate which is covariant, It is used to point to a method which will return type Tout, there wont be any input to the method, which ensures covariance.
If you see closely, this delegate type has same signature as Action delegate(details below).
Contravariance - ContravariantDel is contravariant delegate. If you see it has Tin as input parameter
and there is no value returned from it, hence clearly contravariant.
If you see closely, it is similar to Func<Tout>.
Both - CoVariantAndContravariantDel is a delegate is covariant for Tout and contravariant for Tin. If you see statement 7,8,9 and 10, all are valid, because of its dual nature. lets analyze them more closely -
PutBaseGetDerive - Expects a base and returns derived.
Statement 7 -
CoVariantAndContravariantDel<Derived, Base> db1 = PutBaseGetDerive;
db1 returns Base and take input as Derived. whereas PutBaseGetDerive expects a base and returns derived. How it is possible to assign PutBaseGetDerive to db1?
As mentioned in the delegate signature, Tin is contrvariant, which means, this type will be used ONLY as input. And Tout is covariant, means it will be used ONLY as return type.
Tin -> contravariant -> Derived , expectation -> Base, Always possible to get base object from derive, hence no issue.
Tout -> Covariant -> Base, actual return type is - Derived, Again simple to get base from Derive type.

Hence with the help of "in" and "out", compiler always make sure, that a correct type or its derived type is passed/returned.

Action delegate-
If you see the definition of Action, It takes input and returns void. Which clearly says the scenario of "in" Or Contravariance.
If we create an Action which can work on Basetype, We can always assign its instance to a reference of Action of Derived type.
class Program
    {
        static void Main(string[] args)
        {
            Action<Base> b = PrintBase;
            Action<Derived> d = b;
            d(new Derived());
        }
        public static void PrintBase(Base b)
        {
            Console.WriteLine(b.ToString());
        }
    }
    public class Base { }
    public class Derived : Base { }
If you recall from previous post we mentioned the similar behavior with IComparer.
Action is another

Func -
If you see the signature of Func it is has nature of being covariant and contravariant both.
   public delegate TResult Func<out TResult>(); // Covariant
   public delegate TResult Func<in T, out TResult>(T arg); // Both

In the above mentioned example, CoVariantAndContravariantDel is nothing but the Func. 

Covariance and Contravariance in C#

Co-variance and contravariance mainly talks about the reference conversion. As you know, its always possible to assign the instance of derived type object to a reference of base type, Or in other words we can pass a derived type where ever a base type is expected, but the other way round is not possible.
Covariance and contravariance talks about this condition which was not possible in the old c#.
Important points before we start -

1) Classes can not be covariant or contravariant.
2) Value type can not played around in covariant/contravariant manner.

Covariance -
In mathematical terms - if A -> B then Fn(A) -> Fn(B)
In c# generic terms -
Base > Derived, (i .e we can pass derived, where Base required)
then Generic<Base> > Generic<Derived>
(i.e. we can pass Generic<derived> where Generic<Base> is required)

Examples  -
class Program
    {
        static void Main(string[] args)
        {
           IFoo<Derived> foos = null;     //1
            IFoo<Base> general = foos;    //2
        }
    }
    public interface IFoo<out T>
    {
        T GiveMeFoo();
    }
    public class Base { }
    public class Derived : Base { }
In the above example, as we have defined IFoo with T as "out", statement 2 will not give any error, if we remove out keyword from IFoo, it is a compile time error.
That is because, mentioning "out" means, we are explicitly telling compiler that we are not going to pass T as parameter for IFoo, we will only take it out.
Now in the above example, if we try to get object of Base out from general, it will give us object of derived which in tern can be translated into Base, hence it works.

Moreover, if you try to write AddT(T t) in the IFoo, then it will be an error, because T is covariant, and you can not have it as a input parameter.

IEnumerable -
IEnumerable is also covariant by nature, because we always take elements out from the collection, we do not process or modify them within. It is defined like IEnumerable<out T>
Its always possible to write -
IEnumerable<Derived> d1 = new List<Derived>();
IEnumerable<Base> b = d;
It is very much similar to writing
Derived d = new Derived();
Base b = d;
Which is not very new from C# perspective.

Contravariance -
In mathematical terms - if A -> B then Fn(B) -> Fn(A)
In c# generic terms -
Base > Derived, (i .e we can pass derived, where Base required)
then Generic<Base> < Generic<Derived>
(i.e. we can pass Generic<Base> where Generic<Derived> is required) MAGIC...!!!

Example -
class Program
    {
        static void Main(string[] args)
        {
            IFoo<Base> foos = new Foo(); //1
            IFoo<Derived> general = foos; //2
            general.ModifyT(new Derived()); //3
        }
    }
    public interface IFoo<in T>
    {      
        void ModifyT(T t);  
    }
    public class Foo : IFoo<Base>
    {
        public void ModifyT(Base t)
        {
            throw new NotImplementedException();
        }
    }

    public class Base { }
    public class Derived : Base { }

The above code clears says, that the statement 2 is a valid statement, which is something new to us, that is where we see the beauty of Contravariance.
This is because we explicitly mentioned T as a "in" parameter, which means the T will be an input to the method in the interface, there wont be any method in the given interface which would return the T, i.e. T will not be take out in any circumstances.
If you see statement 2, we are using general object, which is pointing to foos(of type Ifoo<Base>) and we call method ModifyT passing Derived object in it(statement 3), It can easily execute ModifyT(base), because derive can always replace Base.

This facility is only because we know the T will always be "in" (input parameter).

ICompare -
ICompare is contravariant by nature - public interface IComparer<in T>
Which means we do not take anything out with this interface, we always pass values within and compare them.
class Program
    {
        static void Main(string[] args)
        {          
            IComparer<Base> compareBase = new BaseCompare(); //1
            IComparer<Derived> compareDerived = compareBase;//2
            compareDerived.Compare(new Derived(), new Derived());//3
        }
    }  
    public class Base { }
    public class Derived : Base { }
    public class BaseCompare : IComparer<Base>
    {
        public int Compare(Base x, Base y)
        {
            throw new NotImplementedException();
        }
    }
Analyze the above code, Where we can assign a Comparer of type Base to a Derived one.
That is because in statement 3, we can always pass object of derived type, where we expect base type, and hence it works.

Tricks -
As we know mathematical formula for both covariance and contra variance -

covariance  - if A -> B then Fn(A) -> Fn(B)
contravariance -  if A -> B then Fn(B) -> Fn(A)

We can use this to identify if the given condition is allowed or not.
Say IFoo is  covariant -
Covariant has a simple relation so -
Object of derive can be assign to reference of type Base
Object of  IFoo<Derived> can be assign to reference of type IFoo<Base>
Object of  IFoo<IFoo<Derived>> can be assign to reference of type IFoo<IFoo<Base>>
and so on.....

Say IFoo is contravariant -
contravariant has a opposite relation relation so -
Object of derive can be assign to reference of type Base
Object of  IFoo<Base> can be assign to reference of type IFoo<Derived>
Object of  IFoo<IFoo<Derived>> can be assign to reference of type IFoo<IFoo<Base>>
and so on.....

If you see closely, 2nd statement got reversed but 3rd one is straight again, it is because in case of contravariance we change the sign, 2nd statement is reverse one, 3rd will be straight, 4th will be again reversed and so on....
if A -> B
then Fn(B) -> Fn(A)
then Fn(Fn(A)) -> Fn(Fn(B))
then Fn(Fn(Fn(B))) -> Fn(Fn(Fn(A))) .....

Code -
  class Program
    {
        static void Main(string[] args)
        {
            IFoo<IFoo<Derived>> fooD = new FooD();
            IFoo<IFoo<Base>> fooB = fooD;      
        }
    }

    public interface IFoo<in T>
    {      
        void ModifyT(T t);  
    }

    public class FooD : IFoo<IFoo<Derived>>
    {
        public void ModifyT(IFoo<Derived> t)
        {
            throw new NotImplementedException();
        }
    }
    public class Base { }
    public class Derived : Base { }

Friday, September 26, 2014

Task parallel library - Quick notes

Task Vs ThreadPool-
Tasks internally uses Threadpool only, but it has few feature which makes it better than traditional threading. Here are few advantage of using Task over ThreadPool -
1) Along with traditional thread queue, it has internal local queue as well. Task creating another task get queued up in the local queue, rather than going into common queue. It helps in optimizing the execution.
Here is a good article which discuss about optimization -
http://www.danielmoth.com/Blog/New-And-Improved-CLR-4-Thread-Pool-Engine.aspx
2) Cancelling a task is much easier than stopping any executing code in a thread.
3) Exception handling is easier in case of Task
4) Getting result from task is much easier than thread.

Task creation -
There are multiple ways to create and start the Task -
1) var taskA = new Task(() => Console.WriteLine("Hello from taskA."));//create
   taskA.Start();//start
2) var taskA = Task.Factory.StartNew(() => Console.WriteLine("Hello from taskA."));//create + start
3) Task task1 = Task.Factory.StartNew((object obj) => Console.WriteLine(obj),123); //create + start with value passed in it.
4) Task> t = Task.Factory.StartNew>(() => { return new List() { 1,2,3 }; }); // return some value from task

Here is a good article on comparison between StartNew and Task.start - http://blogs.msdn.com/b/pfxteam/archive/2010/06/13/10024153.aspx

Exception Handling -
Task provide AggregateException, which is consolidate list of all exceptions occurred in tasks. It has property InnerException, by which we can access individual exceptions.
We can capture the exception, if we surround the task's wait/result method with try catch block.
Handle method available on aggregateException, which takes predicate. predicate takes exception as input and returns true/false if exception is handled successfully or not.
There is a property named as IsFaulted. We can use it to identify if there was any unhandled exception. We can use it if we are not using wait/result property.

Cancellation -
The requesting object creates a CancellationTokenSource object, and then passes its Token property to the cancellable operation. The operation that receives the request monitors the value of the IsCancellationRequested property of the token by polling/wait/waithandle. When the value becomes true, the listener can terminate in whatever manner is appropriate. It is advised to throw OperationCancelledException from the cancelled task, so that the state of the task can be moved to cancelled, and also it the the way to tell that task has responded to the cancellation request.
CancellationTokenSource tokenSource = new CancellationTokenSource();          
            CancellationToken token = tokenSource.Token;          
            Task taskWithFactoryAndState =
            Task.Factory.StartNew(() =>
            {              
                token.ThrowIfCancellationRequested();                                                  
            }, token);

            // cancel the second token source
            tokenSource.Cancel();
            try
            {
                taskWithFactoryAndState.Wait();
            }
            catch (AggregateException aggEx)
            {
            }

SynchronizationContext -
Using TaskScheduler.FromCurrentSynchronizationContext() we can marshal any task on UI thread. We can pass it as one of the parameter to task and .NET will execute the task on given context.
Here is a good article on the same- http://blogs.msdn.com/b/pfxteam/archive/2009/09/22/9898090.aspx

Continuation -
We can use continueWith API to chain any task. There are different flavor available of ContinueWith like WhenAny,WhenAll, OnlyonFaulted, OnlyOnRanToCompletion etc, which we can use to chain as per our need. It is one of the powerful feature of Task library as we can implement pipe execution model with it.
Continue task wont execute in case of exception or cancellation.

Parallel.For and Parallel.Foreach -
Parallel.For(0, 10, (i) => {
                Console.WriteLine(i);
            });

            List list = new List() {"one", "two","three","four","five"};
            Parallel.ForEach(list, (str) => {
                Console.WriteLine(str);
            });


There is no guarantee of the sequence.
We can terminate the loop in between using stop or break API in the following manner -
List list = new List() {"one", "two","three","four","five"};
            Parallel.ForEach(list, (str,state) => {
                Console.WriteLine(str);
                state.Break(); // or state.Stop();
            });

There is slight difference between stop and break -
1) breakindex - In case of break, we can identify at which point does the loop break -
List list = new List() {"one", "two","three","four","five"};
            var result = Parallel.ForEach(list, (str,state) => {
                Console.WriteLine(str);
                state.Break(); // or state.Stop();
            });
            long? breakIndex = result.LowestBreakIteration;

2) Stop notifies that all iteration will immediately stop but in case of break all higher iterations will be stopped, the lower iteration will still execute.-
Parallel.For(0, 100, (i, loopState) =>
            {
                if (i == 85)
                {
                    loopState.Break();
                }
                Thread.Sleep(20);
                list.Add(i);
            }
            );
In this code, if we are using Break, then all values including 85 will be added into list, but we use Stop, there might be some values >85 will be added, and some of the values less than 85 that will not be added.

TaskCompletionSource
This is another mechanism of creating Task. In this case, we create a task which is not assiciated with any delegate. There are other ways like APM or events available in .NET, which can give us asynchronous way of handling function. Using TCS, we need not to care what underlying model we have used, we can just wrapped it around TAsk and use it power.
It has SetResult and SetException kind of methods availble which set the result/exception to the given task. Every TCS can have only 1 task associated with it.
TaskCompletionSource tcs = new TaskCompletionSource();
            ThreadPool.QueueUserWorkItem(_ => {
                int data = MakeServiceCall();
                tcs.SetResult(data);
            });
            tcs.Task.Wait();
            Console.WriteLine(tcs.Task.Result);

Good article on the same - http://blogs.msdn.com/b/pfxteam/archive/2009/06/02/9685804.aspx

Tuesday, January 21, 2014

How IIS process a request

Those who need basic understanding of IIS, please Click Here.
Depending upon the extension, IIS determines the handler. What if the url does not have any extension(case of MVC and webapi). Well in that case the old IIS(5.0,6.0) wont work as expected, but the 7.0 will work.

The difference between 6.0 and 7.0 is, 7.0 by default run in integrated mode. That is, it treats every request to be .NET request and hence it does not need any extension to identify, if it is .NET request or not.

The below diagram gives an overview of how request is handled in IIS.

The request from the browser once reaches to IIS, it resolve the extension(for old IIS) and pass it to the respective handler(aspnet_wp.exe in 5.0 and w3wp.exe in 6.0/7.0).

Once it reaches to these process, it creates object of ApplicationManager, which loads AppDomain(if not loaded) and pass the request to respective appdomain. Application manager is responsible for managing different appdomain in the process.

In the Appdomain, a hosting environment is created, which provides information(like folder where application is, applicationID, sitename etc) about application

Once hosting environment is created, it creates object of HttpContext, HttpRequest, HttpResponse.

After all these objects are created, application is started by creating object of HttpApplication(if global.asax is available, then object of global.asax created which inherits frm HttpApplication only). The HttpApplication will take care of performing ASP.NET life cycle. All the events raised in page life cycle is taken care by HttpApplication. (If it is global.asax, then the event in global file also taken care of.)

Ref -
http://msdn.microsoft.com/en-us/library/ms178473(v=vs.100).aspx
http://msdn.microsoft.com/en-us/library/bb470252(v=vs.100).aspx

Friday, January 10, 2014

Routing in IIS

I was going through the link below to understand the routing in IIS -
http://www.iis.net/learn/extensions/url-rewrite-module/iis-url-rewriting-and-aspnet-routing

I found it useful and have noted few important points which might summarize the whole article.
Here are those points -

IIS URL Rewriting
The URL rewriting module analyzes the requested URL and changes it to a different URL on the same server.The URL rewriting module runs early in the request-processing pipeline, modifying the requested URL before the Web server decides which handler to use to process the request.

ASP.NET Routing
Developers can associate a certain URL with a handler that can process requests made to that URL.
ASP.NET routing is implemented as a managed-code module that plugs into the IIS request-processing pipeline at the Resolve Cache stage (PostResolveRequestCache event) and at the Map Handler stage (PostMapRequestHandler event).During the PostResolveRequestCache event, the module looks through a routing table for a route that matches the requested URL path. If a match is found, the module obtains a reference to the handler that corresponds to that route and saves the reference as part of the current HTTP context. A handler can be any .NET Framework object that implements the System.Web.IHttpHandler interface.
During the PostMapRequestHandler event, the module checks if the HTTP context contains any information about a handler. If it does, ASP.NET routing uses the information to set the Handler property of the current HTTP context. This ensures that during the Execute Handler stage, IIS will execute the handler that was selected by the routing module.























Difference between URL Rewriting and ASP.NET Routing -
1) The IIS URL Rewrite module can be used with any type of Web application, which includes ASP.NET, PHP, ASP, and static files. ASP.NET routing can be used only with .NET Framework-based Web applications.
2) The IIS URL Rewrite module works the same way regardless of whether integrated or classic IIS pipeline mode is used for the application pool. For ASP.NET routing, it is preferable to use integrated pipeline mode. ASP.NET routing can work in classic mode, but in that case the application URLs must include file name extensions or the application must be configured to use "*" handler mapping in IIS.
3) The IIS URL Rewrite module can make rewriting decisions based on domain names, HTTP headers, and server variables. By default, ASP.NET routing works only with URL paths and with the HTTP-Method header.
4) In addition to rewriting, the URL Rewrite module can perform HTTP redirection, issue custom status codes, and abort requests. ASP.NET routing does not perform these tasks.

Friday, January 3, 2014

ASP .NET Web API Basics - part 1

REST - Representational State Transfer
REST suggest use of HTTP protocol(Get, Post etc) to do any operation on server. As per REST following is the protocol we should follow these conventions with HTTP verbs-
Get - Retrieve resource
Post - Create resource
Put - Update resource
Delete - Delete resource

Here are the url example which will help us understand how to achieve different server side operations based on HTTP verbs -

Get Request -
http://mydomain.com/api/books   -- retrieve all books
http://mydomain.com/api/books/1 -- retrieve book with id 1
Similarly we can utilize the POST, PUT and DELETE operations.

WebAPI -
It is possible to achieve REST full service architecture using WCF also, but it is not that straight forward, it requires a lot of configuration. Moreover TDD point of view, it is not easy to test it.

Microsoft came up with new solution which they call it as ASP.NET WEB API, which is kind of combination of both WCF WEB API and ASP.NET MVC(conceptual idea only).
It allow you to write REST based services.
Here is the architecture placement of WEBAPI(via Microsoft site) -











Creating project
This is how you can build a sample WEB-API app -
Creating project -> VS -> new project of type MVC4 -> Select Web API

WebAPI Vs MVC -
http://softtechhelp.blogspot.in/2013/11/webapi-vs-mvc.html

Controller
WebAPI controller inherits from Apicontroller.
The function name is directly mapped with the HTTP verb. Which means if i have a controller named as Person and have Get method in it, an HTTP get request to /person will execute this method. I can have overloaded methods to handle different get methods with arguments as well.
Example -
http://mydomain.com/api/books   -- retrieve all books
http://mydomain.com/api/books/1 -- retrieve book with id 1

Routing
Similar to MVC, WebAPI also has a routing table, which defines the URL structure. By default the url structure is /api/{controller}. You can always customize it.

Response format-
By default the response of get request is an XML. But it depends on what client is requesting for. If you see in fiddler, the client sends the "Accept" tag, where it mentions the desired format of the response. If we modify it and make it text/json, the same code will respond back with the same data in JSON format.

FromBody tag -
If you see the post method in the controller, the input args has "FromBody" attribute attached to it, which is responsible for de-serializing the object sent.