Wednesday 30 May 2012

For those about to ASP.NET Web API, we salute you

[Level: N]

A new ASP.NET Web API aggregator has been set up at webapibloggers.com - courtesy of @alexzeitler. My humble blog is also one of the many blogs aggregated on this place. It is a nice place to follow up trends and what is happening on the community. You may also follow the twitter account at @webapicontrib.

So if you are about to ASP.NET Web API, we SALUTE you. Have a look in there.

For those about to ASP.NET Web API, we salute you!

Monday 28 May 2012

ASP.NET Web API Series - Part 7: Real world Message Handlers


Introduction

[Level T2] In the previous post we reviewed Web API's pipeline a.ka. Russian Doll model. In this post we further on what discussed with a few examples built by the community. Also before that, we look on how to use a per-route message handler while keeping all the goodness of controller functionality.

If you have written a real-world handler in ASP.NET Web API, please contact me in the comments below or on Twitter (@aliostad) to be reviewed and added to the post.

Have the cake and eat it at the same time

In the previous post, we talked about the benefits of the per-route message handlers. Henrik's example is an implementation of HttpMessageHandler which will basically needs to do every thing by itself. So the question arises, how can I have the flexibility of the per-route message handlers while benefit from all the luxury of formatting, action invocation, controller mechanisms, etc. In other words, how can I invoke my controller in a per-route case? Well that sounds like have the cake and eat it at the same time.


Well, it turns out it is possible. I managed to get this working, calling my actions using a per-route handler. The trick is that you set up your Russian dolls and last one ending with an HttpControllerDispatcher.

So let's look at an example. Here we have is a humble delegating handler that outputs the request URL to the trace.

public class TraceHandler: DelegatingHandler
{
 protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
 {
  Trace.WriteLine(request.RequestUri.ToString());
  return base.SendAsync(request, cancellationToken);
 }
}

Now if we want to set up this DelegatingHandler per-route, we simply create a new HttpControllerDispatcher and set it to the InnerHandler of the TraceHandler:

config.Routes.MapHttpRoute(
 "DefaultApi",
 "api/{controller}/{id}",
 new{ id = RouteParameter.Optional},
 null,
 new TraceHandler(){InnerHandler = new HttpControllerDispatcher(config)});

Creating HttpControllerDispatcher is easy and we just need to pass the HttpConfiguration object (depending on the SelfHost or Web scenario).

So this way we can have our per-route delegating handler running only for that route yet all the controller action binding and formatting intact.

Real-world message handlers

Since the beta version of the Web API was out, community has been building interesting and useful handlers. So I thought instead of me coming up with arbitrary or simple cases, I could introduce the great stuff community has done so far. And that is what I did. The very last one is the introduction of my CachingHandler which deserves a post on its own.

Tracking Web API usage by your customers

Filip Woj shows us how to build a DelegatingHandler to support tracking usage of your API. But not just that, actually all the nitty-gritty of building the infrastructure (repositories, etc) to support it. This can be a very useful feature if you want to monetise your API and need to charge per call or make sure the call is made within the number of calls allowed for the customer.

Radenko tries to solve a similar problem with throttling usage of the API. He uses HttpRuntime.Cache for storing the statistics. As he explains, he will be moving the storage to Membase. Generally use of the cache for storing data is not great since system can remove the data if memory becomes a scarce resource (which happens often on a web server, especially the one needing throttling).

Authentication and security

John Petersen looks into using a delegating handler for token-based authentication. He uses public/private key and RSA for creating tokens (perhaps we could also choose a stronger algorithm since token is small unlike the whole HTTP communication) and creates 3 different handlers: one to make sure the request uses TLS/SSL, other to ensure the IP address of the client is from a white-list and finally the handler to create and verify authentication token.

Antony Scott also takes on the Basic Authentication and explains how to process the authentication header and set the identity of the current thread. There is not a lot of code there, not more than you need displaying how easy it is to do basic authentication if you use all the correct points of the system.

Perhaps the most important implementation of security which also includes use of message handlers, is Dominick Baier's Thinktecture Identity model on github. Dominick explains this in his blog post here and his library supports all major standards.

Other

Mike Wasson explains here how to create HTTP method override delegate in ASP.NET Web API. The idea is that using HTTP methods other that POST and GET might be tricky on some servers. For example, there is a known issue in IIS whereby PUT or DELETE methods will return 404 if you have WebDAV installed on the server. In such cases, by convention client sends a custom HTTP header with the key of X-HTTP-Method-Override containing the alternate method. In this case, the handler will read the header and change the method. It is important to note that binding to the controller and action selection and invocation happens later so this change of method will be effective. 

Caching

HTTP caching is a very important feature in RFC 2616. A whole chapter in the spec is dedicated to it and arguably involves some of the most complex rules in the whole spec. Caching is also one of the tenants of REST and as such plays an important role in the design, architecture and scalability model of the web. In the last few weeks I have been busy building a CachingHandler for the WebApiContrib and currently it is available in my fork of the project. In the next post, I will be going through some of the challenges I was facing and the solutions I came up in writing this complex handler. It was good fun!

Conclusion

Per-route message handlers can be enhanced if we mix delegating handler(s) with HttpControllerDispatcher. In this case, we can have a number of delegating handlers last one ending with the controller dispatcher. This leaves media formatting, controller selection, model binding and action invocation intact while we can have all the flexibility of per-route handlers.

We also reviewed a few useful handlers built by the community and available at the time of writing this post. In the next post, we will cover the CachingHandler.

Saturday 19 May 2012

ASP.NET Web API Series - Part 6: MessageHandler explained


Introduction

[Level T3] MessageHandler is a new concept in ASP.NET Web API and a very useful tool in separation of concerns in a Web API service. In this article we will review the concept and outline its usefulness with a few simple examples.

Background

IIS as the Windows platform's HTTP server implementation, has always had two concepts: a component that receives HTTP request and responsible for returning a response (endpoint of communication), and another component that sniffs the communication and can quietly read/write from/to the request/response.

In the old times of unmanaged C++ IIS application implementation, we had ISAPI extensions and ISAPI filters. So the first one was responsible for reading request and sending back a response while the other, would be sniffing incoming and outgoing messages and perhaps sneak in/out a few headers or content. Difference also explained here.

In ASP.NET we had the same two familar concepts: HTTP Handlers and HTTP Modules with corresponding IHttpHandler and IHttpModule interfaces, respecitvely. Again here, we had handlers responsible for handling the request and returning a response, while HttpModule would be sitting as a not-so-innocent-bystander and sniff in what goes and chip in when necessary.

To illustrate this further, all Web Forms pages or MVC controllers can be looked as HTTP Handlers (although the interface itself would be implemented much higher in the pipeline but would delegate the responsibility to page or controller action). On the other hand, useful tools such as Glimpse or ELMAH use HTTP module to intercept the errors or routes from the stream of incoming/outgoing request/response. ASP.NET MVC has a concept of ActionFilter which is similar but for the sake of brevity it is better not to delve into it.

ASP.NET Web API continues these two concepts yet combines them into HttpMessageHandler which is the base class for important classes in the stack such as HttpServer, HttpControllerDispatcher and HttpRoutingDispatcher. This class can be implemented as both an equivalent of HTTP module or handler. Yet DelegatingHandler, a subclass of HttpMessageHandler has been specialised into an equivalent of HTTP module. While understanding of HttpMessageHandler is important, it is much more likely that you will only implement DelegatingHandler. As such we cover it in more details.

DelegaingHandler in Web API

DelegatingHandlers are used in the Web API to represent Message Handlers before routing (see below). They are ordered modules in the HTTP pipeline stream each one receiving request, doing some work and pass to the next. On the outbound stream also response is taken, processed passed to the next. However, at any point, a handler can decide to take action and process the request returning the response without passing to the next one. If I need to show this, I would use my very crude drawing techniques:

Request/Response pipeline and Message Handlers in ASP.NET Web API - in a crude way :)


So now let's think about it. We have a stack of message handlers: first handler to receive the request is the last one to be passed the response, vice versa. This is similar to Russian Dolls, each inside the other.

Russian doll model

If you have not seen Russian dolls, well there it is for you:



 The idea is that you you buy just the biggest doll and once you open it, you find a smaller one and if you open that one, you see a smaller... until you get to the last one. 

So let's look at the DelegatingHandler and other classes in the hierarchy:

Class hierarchy of Message Handlers in System.Net.Http.dll

As can be seen, DelegatingHandler is a derived class from HttpMessageHandler and has a property of InnderHandlerThis inner handler in fact is the smaller Russian Doll inside the handler. So as you can imagine all these handlers are chained together using this InnerHandler property.

There is in fact some code in ASP.NET Web API that turns IEnumerable<DelegatingHandler> into a chain of DelegatingHandlers.

How does a DelegatingHandler work?

DelegatingHandler mainly has to implement SendAsync method. This method receives a HttpRequestMessage (and a cancellation token) and must return a Task<HttpResponseMessage>. So you might have expected to see two methods, one for handling request and one for handling response, but they are all combined into one because of the power and beauty of Task<T>.

Basically in a delegating handler, if you need to inspect the request then you would simply do it in the SendAsync. However, if you need to work on the response, you would do it in the continuation of the Task.

So let's see some code. Let's imagine I need to write to the trace all incoming request URLs and add a custom response header identifying that this URL has been written to the trace (a very fictitious case, we will see some real world scenarios in the next post), we can code it very easily:


public class DummyHandler : DelegatingHandler
{
 protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
 {
  // work on the request 
  Trace.WriteLine(request.RequestUri.ToString());

  return base.SendAsync(request, cancellationToken)
   .ContinueWith(task =>
                {
      // work on the response
                   var response = task.Result;
        response.Headers.Add("X-Dummy-Header", Guid.NewGuid().ToString());
        return response;
                });
 }
}


Execution of message handlers in Web API pipeline

Until recently, you could only register MessageHandlers globally. ASP.NET team have recently added much awaited per-route message handler support announced only a few weeks ago.

So as explained and illustrated by Henrik in the link above (and also by Kiran Challa in his nice diagram), execution of message handlers depends on whether they are registered globally or per-route. Global message handlers are executed before HttpRoutingDispatcher work while per-route message handlers are executed after it.

Registering a global message handler (DelegatingHandler)

Global message handlers (must be DelegatingHandlers) are a property of the configuration object. In a web hosted Web API:

GlobalConfiguration.Configuration.MessageHandlers.Add(
    new DummyHandler());

As we discussed, the order of registering a handler is very important and defines the size of the Russian doll, higher it is in the list, more powerful it will be as it becomes the soonest receiving the request and last receiving the response (hence more flexibility and breadth of operation).

UPDATE 06/08/2012:  The order of calling message handlers has changed for RTM release. So in RTM, first item is called first for request and last for response.

Registering a per-route message handler(s)

This is easy and is at the same time of registering the route itself. Here we register MyMessageHandler:

IHttpRoute route = config.Routes.CreateRoute(
 routeTemplate: "api/MyRoute",
 defaults: new HttpRouteValueDictionary("route"),
 constraints: null,
 dataTokens: null,
 parameters: null,
 handler: new MyMessageHandler());

config.Routes.Add("MyRoute", route);

One might wonder, it would have been great if we could register a collection of delegating handlers along with the actual handler. In fact we can! Se let's say we have two DelegatingHandler implementations as RussianDoll_1 and RussianDoll_2. So we can now say:

var handler = new RussianDoll_1()
 {
  InnerHandler = 
   new RussianDoll_2()
   {
    InnerHandler = new MyMessageHandler()
   }
 };

IHttpRoute route = config.Routes.CreateRoute(
 routeTemplate: "api/MyRoute",
 defaults: new HttpRouteValueDictionary("route"),
 constraints: null,
 dataTokens: null,
 parameters: null,
 handler: handler);

config.Routes.Add("MyRoute", route);

Conclusion

In this post, we briefly reviewed the history of two types of HTTP pipeline components: the one that is responsible for processing a request and sending back a response, and the other, a mid-stream component in the HTTP pipeline sniffing the incoming and outgoing request/response which can sometimes intervene in the message processing.

In brief, Web API heavily uses the abstraction of HttpMessageHandler and DelegatingHandler - latter inheriting from the former. Web API allows for registration of global message handlers or per route handlers. In the next post, we will review some of the real-world use cases of Message Handlers.

Sunday 6 May 2012

Performance comparison of object instantiation methods in .NET

In the previous post, I compared performance of various methods of code invocation that are in our arsenal in .NET framework.

Last night I was reviewing ASP.NET Web API Source Code that I noticed this snippet:
private static Func<object> NewTypeInstance(Type type)
{
    return  Expression.Lambda<Func<object>>(Expression.New(type)).Compile();
}

But surely, compiling a lambda expression is really costly (as we have seen in the last post), why shouldn't we use simply do this (if we are suppose to just return a Func):
private static Func<object> NewTypeInstance(Type type)
{
    var localType = type; // create a local copy to prevent adverse effects of closure
 Func<object> func = (() => Activator.CreateInstance(localType)); // curry the localType
    return func;
}

Well, I asked this very question from Henrik F Nielsen, ASP.NET Web API team's architect. And he was very helpful getting back to me quickly that "compiling an expression is the fastest way to create an instance. Activator.CreateInstance is very slow".

OK, I did not know that, but it seems to be a good topic for a blog post! So here we are where I compare these few scenarios:

  1. Direct use of the constructor
  2. Using Activator.CreateInstance
  3. Using a previously bound reflected ConstructorInfo (see previous post for more info)
  4. Compiling a lambda expression every time and running it
  5. Caching a compiled lambda expression and running it (what ASP.NET Web API does)

Test and code

In this one, I could get a bit more imaginative with my code since in the last post I already established overhead/merits of various code invocation methods. For the object to construct, I use a simple class which has a default parameterless constructor. Results will be different using a parameterful constructor but I think parameterless constructor is a more pure case.

So I have created a few Action extension methods to perform the tedious repeated snippets in the last post. Each method runs 1,000,000 times which is not high enough but as we will see (and have seen in the last post), compiling a lambda expression every time is really slow so 10 million would be very high.
public class ConstructorComparison
{
 static void Main()
 {
  const int TotalCount = 1000 * 1000; // 1 million
  Stopwatch stopwatch = new Stopwatch();
  Type type = typeof(ConstructorComparison);
  var constructorInfo = type.GetConstructors()[0];
  var compiled = Expression.Lambda<Func<object>>(Expression.New(type)).Compile();

  Action usingConstructor = 
    () => new ConstructorComparison();
  Action usingActivator = 
    () => Activator.CreateInstance(type);
  Action usingReflection = 
    () => constructorInfo.Invoke(new object[0]);
  Action usingExpressionCompilingEverytime =
   () => Expression.Lambda<Func<object>>(Expression.New(type))
    .Compile();
  Action usingCachedCompiledExpression = 
    () => compiled();
  Action<string> performanceOutput = 
    (message) => Console.WriteLine(message);

  Thread.Sleep(1000);
  Console.WriteLine("Warming up ....");
  Thread.Sleep(1000);

  Console.WriteLine("Constructor");
  usingConstructor
   .Repeat(TotalCount)
   .OutputPerformance(stopwatch, performanceOutput)();

  Console.WriteLine("Activator");
  usingActivator
   .Repeat(TotalCount)
   .OutputPerformance(stopwatch, performanceOutput)();

  Console.WriteLine("Reflection");
  usingReflection
   .Repeat(TotalCount)
   .OutputPerformance(stopwatch, performanceOutput)();

  Console.WriteLine("Compiling expression everytime");
  usingExpressionCompilingEverytime
   .Repeat(TotalCount)
   .OutputPerformance(stopwatch, performanceOutput)();

  Console.WriteLine("Using cached compiled expression");
  usingCachedCompiledExpression
   .Repeat(TotalCount)
   .OutputPerformance(stopwatch, performanceOutput)();

  Console.Read();
 }
}

public static class ActionExtensions
{
 public static Action Wrap(this Action action, Action pre, Action post)
 {
  return () =>
       {
           pre();
           action();
           post();
       };
 }

 public static Action OutputPerformance(this Action action, Stopwatch stopwatch, Action<string> output)
 {
  return action.Wrap(
   () => stopwatch.Start(),
   () => 
    {
     stopwatch.Stop();
     output(stopwatch.Elapsed.ToString());
     stopwatch.Reset();
    }
   );
 }

 public static Action Repeat(this Action action, int times)
 {
  return () =>  Enumerable.Range(1, times).ToList()
   .ForEach(x => action());
 }
}

Results and conclusion

Here is output from the program:

Warming up ....
Constructor
00:00:00.0815479
Activator
00:00:00.1732489
Reflection
00:00:00.4263699
Compiling expression everytime
00:02:11.5762143
Using cached compiled expression
00:00:00.0855387

So as we can see:

  • Using a cached compiled expression is almost as fast as the constructor 
  • Using Activator is x2 slower
  • Using reflection is x5 slower
  • Compiling a lambda expression every time is really slow: in this case + x1000 times slower 
So indeed as Henrik said, having only the type of the class, using a cached compiled expression is the fastest method.

Saturday 5 May 2012

Performance comparison of code invocation methods in .NET


Introduction

.NET has moved to become more of a functional programming since .NET 3.0. Currently there are many ways that you can invoke execution of code such as direct call, reflection, delegates, compiled expressions, dynamic, etc. In this post I will compare performance of these methods. Part of the inspiration for this comparison was reviewing the ASP.NET Web API code.

Readability/maintainability vs. Performance

Functional programming is on the rising popularity. Why now, is it not decades old? 

Part of the popularity goes back to the fact that now we run much faster machines - with more cores. And we need to solve more complex problems and there is a need to write more readable code and be able to expression the code more succinctly. On the top of all this, add the fact that we need to invoke code in parallel to get the best of our machines horse power. 

We are writing code that compared to 20 years ago is quite inefficient, using more processor cycles. C was slower than Assembly, and C# slower than C but it certainly does not make sense to write in Assembly. But language is only part of the story. We get choices in one language itself. In .NET, we sometimes use IEnumerable<T>.Count() instead of using IList<T>.Count. While .NET in case of .Count() first tries to convert the IEnumerable<T> to ICollection<T> and if it does not succeed then loops through to get the count, in other cases framework cannot improve the performance. 

Our code is commonly a compromise between readability and performance. I for one would pick former over latter but my decision needs to be an informed decision. If a code is 1000 times slower (and that part of the code is called many times) I definitely would sacrifice readability, but if it is only twice slower, I would pick readability.

Context is also important. Poor performance on server can be costly but on the client usually would not be noticed. A real-time image processing code has to squeeze every drop of performance it can (having done real-time image processing in C++, I am pretty familiar with it), while an asynchronous batch process could use a more liberal approach. In any case, micro-optimisation is a common pitfall that I try not to fall into.

Code Invocation

In .NET we can use different ways to invoke some code (colour coded based on category):
  1. Static method call
  2. Instance method call
  3. Instance method call on virtual methods where CLR has to walk up/down the inheritance hierarchy to understand the piece of code to run.
  4. Invocation using reflection
  5. Invocation using a previously bound reflected object
  6. Invoking a delegate
  7. Invoking a Func or a compiled expression (which itself is a delegate)
  8. DynamicInvoke on a delegate
  9. Compiling a lambda expression and executing it
  10. Invocation on a dynamic object
For our test, I am using a simple class which calculates tangent of an angle. I have done all I could to make sure condition for all these scenarios are similar so that the difference in performance is only related to the call method.
internal class WidgetBase
{
 public virtual double VirtualGetTangent(double value)
 {
  throw new NotSupportedException();
 }
}

internal class Widget : WidgetBase
{

 public override double VirtualGetTangent(double value)
 {
  return Math.Sin(value) / (Math.Cos(value) + 0.0000001f);
 }

 public virtual double InstanceGetTangent(double value)
 {
  return Math.Sin(value) / (Math.Cos(value) + 0.0000001f);
 }

 public static double GetTangent(double value)
 {
  return Math.Sin(value) / (Math.Cos(value) + 0.0000001f);
 }

}

Now let's see how each scenario is implemented (I have commonly ignored the return value).
static void CallStatic(double value)
{
 Widget.GetTangent(value);
}

static void CallInstance(double value, Widget widget)
{
    widget.InstanceGetTangent(value);
}

static void CallVirtualInstance(double value, Widget widget)
{
 widget.VirtualGetTangent(value);
}

First three call types need not much explanation. Static method and instance method do not have much difference. Internally in CLR, instance method has an additional parameter for the instance itself passing this to it. Jeff Richter explains the difference between IL's call and callvirt where callvirt is slower than call but as we will see difference is minimal.
static void CallReflector(double value, Widget widget)
{
    MethodInfo methodInfo = typeof(Widget).GetMethods(BindingFlags.Instance |
  BindingFlags.Public).Where(x => x.Name == "InstanceGetTangent").First();
    methodInfo.Invoke(widget, new object[] { value });
}

static void CallMethodInfo(double value, MethodInfo methodInfo, Widget widget)
{
    methodInfo.Invoke(widget, new object[] { value });
}
With reflection, we have two steps. First one is binding where we get the MethodInfo from the type object. Next one is the actual execution where we use Invoke to execute the method. As you can see, second method is passed the MethodInfo while the first one binds every time. In our example, this will incur the overhead of boxing since both our input and output are double while parameters passed in and out of Invoke is object. However, I have decided to keep it so since this could also happen in a real scenario.

public delegate double CalculateIt(double value);

static void CallDelegate(double value, CalculateIt d)
{
 d(value);
}

static void CallFunc(double value, Func<double, double> func)
{
 func(value);
}

static void CallDelegateDynamicInvoke(double value, Delegate d)
{
 d.DynamicInvoke(new object[] { value });
}

static void CallExpression(double value, Expression<Func<double, double>> expression)
{
    Func<double , double> compile = expression.Compile(); 
    compile(value);
}
CalculateIt is a delegate defined above and called in the first method. Difference between first call and third is that the first one is a strongly typed delegated while the third one is simply weakly typed delegate that can be only called using DynamicInvoke.
static void CallDynamic(double value, Widget widget)
{
    dynamic d = widget;
    d.InstanceGetTangent(value);
}
Dynamic object call is simple and uncomplicated as can be seen above.

NOTE: Metrics of running a compiled expression is the same as that of Func so it is not separately calculated. My point here is to show that compiling an expression all the time is expensive and I have seen cases were people do it - if you have not seen. I particularly saw an example where it was used for Null Guard expressions.

Test execution

Each method was called 10,000,000 times and results where compared. I have used a code which is very verbose but I was trying to eliminate anything that could skew the results.

There are other factors such as garbage collection and other processes running on the machine but I have ran the code quite a few times and results were more or less consistent with only 1-2% variation.


Results review

As it can be seen, compiling an expression is 10 times slower than most other call types including Func<T> delegates (result of expression compilation). This is particularly important since some of the new frameworks (e.g. ASP.NET Web API) heavily use expression compilation.
Also of importance is that binding is significant overhead in reflection. By binding once and invoking many times we can improve the performance.

Another important insight is that dynamic, unlike what it is famous for, is not that much slower than strongly typed direct calls (less than twice).

Conclusion

Compiling a lambda expression and running it is the slowest type of code invocation. There is not a meaningful difference between calling a static, instance, virtual method or Func/delegate. Calling a method on a dynamic object less than twice slower than making a direct call.

Source code

As I said, my code is very verbose to eliminate any element that could skew the result. In case you need to review, modify or run the source code, I have brought the source code here:

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Dynamic;
using System.IO;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Security.AccessControl;
using System.Text;
using System.Threading;

namespace PerformanceComparison
{

 class Program
 {
  private static Random _random = new Random();
  public delegate double CalculateIt(double value);

  static void Main(string[] args)
  {

   const int TotalCount = 10000 * 1000; // 10 million
   Stopwatch stopwatch = new Stopwatch();
   Expression<Func<double, double>> expression = 
    (double value) => Math.Sin(value) / (Math.Cos(value) + 0.0000001f);
   Func<double, double> func = expression.Compile();
   Widget widget = new Widget();

   Thread.Sleep(2000);

   // ________   Static ____________________________________________________
   Console.WriteLine("Static ---------------------------------------");
   stopwatch.Start();
   for (int i = 0; i < TotalCount; i++)
   {
    CallStatic(_random.NextDouble());
   }
   stopwatch.Stop();
   Console.WriteLine(stopwatch.Elapsed.ToString());
   stopwatch.Reset();

   // ________   Instance ____________________________________________________
   Console.WriteLine("Instance ---------------------------------------");
   stopwatch.Start();
   for (int i = 0; i < TotalCount; i++)
   {
    CallInstance(_random.NextDouble(), widget);
   }
   stopwatch.Stop();
   Console.WriteLine(stopwatch.Elapsed.ToString());
   stopwatch.Reset();

   // ________   Instance Virtual _______________________________________________
   Console.WriteLine("Instance Virtual --------------------------------");
   stopwatch.Start();
   for (int i = 0; i < TotalCount; i++)
   {
    CallVirtualInstance(_random.NextDouble(), widget);
   }
   stopwatch.Stop();
   Console.WriteLine(stopwatch.Elapsed.ToString());
   stopwatch.Reset();

   // ________   Reflected ____________________________________________________
   Console.WriteLine("Reflected ---------------------------------------");
   stopwatch.Start();
   for (int i = 0; i < TotalCount; i++)
   {
    CallReflector(_random.NextDouble(), widget);
   }
   stopwatch.Stop();
   Console.WriteLine(stopwatch.Elapsed.ToString());
   stopwatch.Reset();

   // ________   Reflected after binding ___________________________________________________
   Console.WriteLine("Reflected after binding ------------------------------");
   MethodInfo methodInfoInstance = typeof(Widget).GetMethod("InstanceGetTangent",
    BindingFlags.Instance | BindingFlags.Public);
   stopwatch.Start();
   for (int i = 0; i < TotalCount; i++)
   {
    CallMethodInfo(_random.NextDouble(), methodInfoInstance, widget);
   }
   stopwatch.Stop();
   Console.WriteLine(stopwatch.Elapsed.ToString());
   stopwatch.Reset();

   // ________   Delegate ____________________________________________________
   Console.WriteLine("Delegate -------------------------------------------------");
   stopwatch.Start();
   CalculateIt c = widget.InstanceGetTangent;
   for (int i = 0; i < TotalCount; i++)
   {
    CallDelegate(_random.NextDouble(), c);
   }
   stopwatch.Stop();
   Console.WriteLine(stopwatch.Elapsed.ToString());
   stopwatch.Reset();

   // ________   Func ____________________________________________________
   Console.WriteLine("Func -------------------------------------------------");
   stopwatch.Start();
   for (int i = 0; i < TotalCount; i++)
   {
    CallFunc(_random.NextDouble(), func);
   }
   stopwatch.Stop();
   Console.WriteLine(stopwatch.Elapsed.ToString());
   stopwatch.Reset();

   // ________   Delegate (Dynamic Invoke) ____________________________________________________
   Console.WriteLine("Delegate DynamicInvoke ------------------------------------------");
   stopwatch.Start();
   for (int i = 0; i < TotalCount; i++)
   {
    CallDelegateDynamicInvoke(_random.NextDouble(), func);
   }
   stopwatch.Stop();
   Console.WriteLine(stopwatch.Elapsed.ToString());
   stopwatch.Reset();

   // ________   Expression ____________________________________________________
   Console.WriteLine("Expression -------------------------------------------------");
   stopwatch.Start();
   for (int i = 0; i < TotalCount / 100; i++)
   {
    CallExpression(_random.NextDouble(), expression);
   }
   stopwatch.Stop();
   Console.WriteLine(stopwatch.Elapsed.ToString());
   stopwatch.Reset();

   // ________   Dynamic ____________________________________________________
   Console.WriteLine("Dynamic -------------------------------------------------");
   stopwatch.Start();
   for (int i = 0; i < TotalCount; i++)
   {
    CallDynamic(_random.NextDouble(), widget);
   }
   stopwatch.Stop();
   Console.WriteLine(stopwatch.Elapsed.ToString());
   stopwatch.Reset();

   Console.Read();
  }

  static void CallStatic(double value)
  {
   Widget.GetTangent(value);
  }

  static void CallInstance(double value, Widget widget)
  {
   widget.InstanceGetTangent(value);
  }

  static void CallVirtualInstance(double value, Widget widget)
  {
   widget.VirtualGetTangent(value);
  }


  static void CallReflector(double value, Widget widget)
  {
   MethodInfo methodInfo = typeof(Widget).GetMethod("InstanceGetTangent",
    BindingFlags.Instance | BindingFlags.Public);
   methodInfo.Invoke(widget, new object[] { value });
  }

  static void CallMethodInfo(double value, MethodInfo methodInfo, Widget widget)
  {
   methodInfo.Invoke(widget, new object[] { value });
  }

  static void CallDelegate(double value, CalculateIt d)
  {
   d(value);
  }

  static void CallFunc(double value, Func<double, double> func)
  {
   func(value);
  }

  static void CallDelegateDynamicInvoke(double value, Delegate d)
  {
   d.DynamicInvoke(new object[] { value });
  }

  static void CallExpression(double value, Expression<Func<double, double>> expression)
  {
   Func<double, double> compile = expression.Compile();
   compile(value);
  }




  static void CallDynamic(double value, Widget widget)
  {
   dynamic d = widget;
   d.InstanceGetTangent(value);
  }



 }

 internal class WidgetBase
 {
  public virtual double VirtualGetTangent(double value)
  {
   throw new NotSupportedException();
  }
 }

 internal class Widget : WidgetBase
 {

  public override double VirtualGetTangent(double value)
  {
   return Math.Sin(value) / (Math.Cos(value) + 0.0000001f);
  }

  public virtual double InstanceGetTangent(double value)
  {
   return Math.Sin(value) / (Math.Cos(value) + 0.0000001f);
  }

  public static double GetTangent(double value)
  {
   return Math.Sin(value) / (Math.Cos(value) + 0.0000001f);
  }

 }

}


Thursday 3 May 2012

Android Ice Cream Sandwich: Delicious!

Android's Ice cream Sandwich is definitely not new but my phone came up for upgrading only two weeks ago. I have been using it for the last two weeks and all I can say is that I am quite impressed.

It is all it claims in the link above and more. UI is very intuitive and Google has certainly catapulted its platform from a cheap just-do-the-job to a real iPhone rival. It is not just the platform but all the Google goodies coming with it, Gmail, Chrome beta, Google Reader they are just a real treat.

I have had Android since 18 months ago and have a free app on the market for listening to podcasts (called PodcastCharger). To be honest, before this I was seriously thinking of leaving Android to another platform (probably Windows phone) since some have already done it because of lack of updates support but I think Google have woken up to the sound of discontent and are pushing for upgrades. I think with this release, that is it... no one can catch Android in market share anymore.

Things that stand out for me in this release are:

  1. Support for right-to-left languages: being a Persian/Iranian by birth, I read a lot of Farsi material but could not on my phone. The support was surprising and frustratingly lacking in all previous versions but finally Google has risen to the challenge fixed provided this feature.
  2. Great UI experience: UX is miles better - especially with the new Google apps. UI flows nicely and is consistent unlike before where you felt it is just cobbled together by some amateurish geek. It certainly looks flat and metro so I think Microsoft can take some of the credit.
  3. Nice new features: menus have been simplified, new features have been added or just made available and usable (such as data usage)
  4. Snazzy and slick: there is a particular minimalism in the views which is just chic.
  5. NFC and direct Wi-Fi: there seems to be new features (which I have not yet used) allowing peer-to-peer communication which I think will really make it attractive for non-Android users to buy into.
In one word, I am impressed. And enjoying my Ice Cream Sandwich. [I have a Samsung Galaxy S2]