Sorted By: Month (2) and Year (2012)

Autofac and ASP.NET Web API System.Web.Http.Services.IDependencyResolver Integration

In this post, you can make Autofac work with ASP.NET Web API System.Web.Http.Services.IDependencyResolver. Solution to the 'controller has no parameterless public constructor' error.
2012-02-27 07:43
Tugberk Ugurlu


I have been using Ninject in all of my ASP.NET MVC applications till Chris Marisic (@dotnetchris) poked me on twitter about how slow Ninject is. After a little bit of research, I changed it to Autofac which works pretty perfectly.

ASP.NET Web API has nearly the same Dependency Injection support as ASP.NET MVC. As we do not have a built in support for ASP.NET Web API in Autofac (yet), I created a simple one. The implementation is not as straight forward as Ninject and you probably saw the below error if you tried to make it work:

System.InvalidOperationException:

An error occurred when trying to create a controller of type 'TourismDictionary.APIs.Controllers.WordsController'. Make sure that the controller has a parameterless public constructor.

Let’s see how it works:

First I created a class which implements System.Web.Http.Services.IDependencyResolver interface.

internal class AutofacWebAPIDependencyResolver : 
    System.Web.Http.Services.IDependencyResolver {

    private readonly IContainer _container;

    public AutofacWebAPIDependencyResolver(IContainer container) {

        _container = container;
    }

    public object GetService(Type serviceType) {

        return 
            _container.IsRegistered(serviceType) ? 
            _container.Resolve(serviceType) : null;
    }

    public IEnumerable<object> GetServices(Type serviceType) {

        Type enumerableServiceType = 
            typeof(IEnumerable<>).MakeGenericType(serviceType);
            
        object instance = 
            _container.Resolve(enumerableServiceType);
            
        return ((IEnumerable)instance).Cast<object>();
    }
}

And I have another class which holds my registrations and sets the ServiceResolver with GlobalConfiguration.Configuration.ServiceResolver.SetResolver method which is equivalent to DependencyResolver.SetResolver method:

internal class AutofacWebAPI {

    public static void Initialize() {
        var builder = new ContainerBuilder();
        GlobalConfiguration.Configuration.ServiceResolver.SetResolver(
            new AutofacWebAPIDependencyResolver(RegisterServices(builder))
        );
    }

    private static IContainer RegisterServices(ContainerBuilder builder) {

        builder.RegisterAssemblyTypes(
            typeof(MvcApplication).Assembly
        ).PropertiesAutowired();

        //deal with your dependencies here
        builder.RegisterType<WordRepository>().As<IWordRepository>();
        builder.RegisterType<MeaningRepository>().As<IMeaningRepository>();

        return
            builder.Build();
    }
}

Then, initialize it at Application_Start:

public class MvcApplication : System.Web.HttpApplication {

    private void Configure(HttpConfiguration httpConfiguration) {

        httpConfiguration.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
    }

    protected void Application_Start() {

        Configure(GlobalConfiguration.Configuration);
        AutofacWebAPI.Initialize();
    }

}

There are different ways of doing it but I like this approach.

My Take on Task-base Asynchronous Programming in C# 5.0 and ASP.NET MVC Web Applications

I'm trying to show you what new C# 5.0 can bring us in terms of asynchronous programming with await keyword. Especially on ASP.NET MVC 4 Web Applications.
2012-02-26 17:21
Tugberk Ugurlu


I have been playing with Visual Studio Async CTP for a while now and I had enough idea on how it works and how I can use it for my benefit and that means that I am able to blog about it.

On most of the softwares we build, the main problem occurs on long running operations. If a user starts a long running operation, that operation blocks the main thread till it completes. Doing so will result pretty unusable applications and unhappy customers for your business. I am sure that we all have used that kind of applications in our lives.

Asynchronous programming model is not a new paradigm and it has been available on .NET since v1.0. I wasn’t very interested in programming 3 years ago so this concept is fairly new to me even now. The concept has evolved a lot on .NET in terms of asynchronous programming as far as I read and I think it has reached its best stage.

On the other hand, you can get confused about asynchronous programming pretty much easily as I did several times. I went back and forth about how it works and where to use it. As a result, I believe I finally got it right. On the other hand, It is much easier to get confused if you’d like to leverage asynchrony on web applications because you do not have a UI thread to flush your results out immediately. Asynchronous or not, the user has to wait the amount of time operation takes to complete. This makes asynchronous programming undesirable for web applications but if you think that way, as I did, you are missing the point.

If you start an operation synchronously and it takes long time, you have no option rather than blocking that thread. If you do the same operation asynchronously, what happens is that you start an operation and come back later when it finishes without waiting it to be finished. Between that duration, your thread is free and can do other stuff as well. Most of the confusion happens here I think. Creating additional threads is not cheap and may cause issues but it is all in past I think. .NET 4.0 has increases the number of thread limits very dramatically. It is still not good to walk around and create threads but it is good not to worry about them. There are couple of debates going around about asynchronous programming (or should I have said went around?):

I am not sure what is the real answer of those questions. But here are two examples:

  • Windows Runtime (WinRT) is designed to be async friendly. Anything longer than 40ms (operations related to network, file system. Mainly I/O bound operations), that is async.
  • ASP.NET Web API introduced a new way of exposing your data to the World with different formats. One thing to notice is that there is nearly no synchronous method on their API. Not metaphorically, literally there is no synchronous versions of the some methods.

That’s being said, I think we have a point here that we should take advantage of asynchrony one way or another in our applications. So, what is the problem? The problem is the way how async programming model works. As Anders Hejlsberg always says, that programing model turns our code inside out. Not to mention that it is extremely hard to do nested async operations and exception handling.

Visual Studio Async CTP and How It Works

In C# 5.0, we will have a new asynchronous programming model which looks a lot like synchronous. On the other hand, C# team has released a CTP version of those features and it has a go-live license. Here is quote from the AsyncCTP spec:

Asynchronous functions is a new feature in C# which provides an easy means for expressing asynchronous operations. Inside asynchronous functions await expressions can await ongoing tasks, which causes the rest of the execution of the asynchronous function to be transparently signed up as a continuation of the awaited task. In other words, it becomes the job of the programming language, not the programmer, to express and sign up continuations. As a result, asynchronous code can retain its logical structure.

An asynchronous function is a method or anonymous function which is marked with the async modifier. An asynchronous function can either return Task or Task<T> for some T and both of them can be awaited. Those kind of functions can also return void but it cannot be awaited. On the other hand, you can await any type if that type satisfies a certain pattern.

ASP.NET MVC 4 and C# Async Features

Benefiting from asynchrony in a right way on ASP.NET MVC applications can result huge positive performance impact. Believe it or not it’s true. I’ll show you how.

So why don't we use it much? Because it is hard and error prone. In the long run, it is hard to maintain the application as well. But with new asynchronous programming model, it is about to change.

In ASP.NET MVC 4, asynchronous programming model has been changed a lot as well. As you probably know, in ASP.NET MVC 3, our controller has to be derived from AsyncController and must satisfy a certain pattern to work with. You can see the Using an Asynchronous Controller in ASP.NET MVC article if you would like to see how it works.

In ASP.NET MVC 4, we do not need AsyncController to leverage asynchrony in our applications. Our controller actions can be marked with async keyword and return Task or Task<T> where the T is usually the type of ActionResult.

I put together a sample application which does the same thing both asynchronously and synchronously. I also did a load test and the end result was shocking. Let’s see what the code looks like:

Firstly, I created a simple REST service endpoint with new REST hotness of .NET: ASP.NET Web API. I have a simple model and collection which I store it in memory. This would be normally a database instead of memory.

public class Car {

    public string Make;
    public string Model;
    public int Year;
    public int Doors;
    public string Colour;
    public float Price;
    public int Mileage;
}

public class CarService {

    public List<Car> GetCars() {

        List<Car> Cars = new List<Car> {

            new Car{Make="Audi",Model="A4",Year=1995,Doors=4,Colour="Red",Price=2995f,Mileage=122458},
            new Car{Make="Ford",Model="Focus",Year=2002,Doors=5,Colour="Black",Price=3250f,Mileage=68500},
            new Car{Make="BMW",Model="5 Series",Year=2006,Doors=4,Colour="Grey",Price=24950f,Mileage=19500}
            //This keeps going like that
        };

        return Cars;
    }
}

And here is my Web API:

public class CarsController : ApiController { 

    public IEnumerable<Car> Get() {

        var service = new CarService();

        return service.GetCars();
    }
}

I have my service now. In my web application, I will get the data from this service and display on the web page. To do that, I created a service class which gets the data from that endpoint and deserialize the string into an object. I used the new HttpClient for asynchronous version of GetCars operation and WebClient for synchronous version of it. I also used Json.NET for working with JSON payload.

public class CarRESTService {

    readonly string uri = "http://localhost:2236/api/cars";

    public List<Car> GetCars() { 

        using (WebClient webClient = new WebClient()) {
            
            return JsonConvert.DeserializeObject<List<Car>>(
                webClient.DownloadString(uri)
            );
        }
    }

    public async Task<List<Car>> GetCarsAsync() {

        using (HttpClient httpClient = new HttpClient()) {
            
            return JsonConvert.DeserializeObject<List<Car>>(
                await httpClient.GetStringAsync(uri)    
            );
        }
    }
}

Above GetCars method is very boring as you see. Nothing to talk about. The real deal is in the second method which is GetCarsAsync:

  • The method is marked with async keyword which indicates that the method has some asynchronous code.
  • We used await keyword before HttpClient.GetStringAsync method which returns Task<string>. But notice here that we use it as string. The await keyword enables that.

Lastly, here is my controller:

public class HomeController : Controller {

    private CarRESTService service = new CarRESTService();

    public async Task<ActionResult> Index() {

        return View("index",
            await service.GetCarsAsync()
        );
    }

    public ActionResult IndexSync() {

        return View("index",
            service.GetCars()
        );
    }
}

We have two actions here, one is Index which is an asynchronous function and returns Task<ActionResult> and the second one is IndexSync which is a typical ASP.NET MVC controller action. When we navigate to /home/index and /home/indexsync, we cannot really see the difference. It takes approx. the same time.

In order to measure the difference, I configured a load test with Visual Studio 2010 Ultimate Load Testing features. I hit the two pages for 2 minutes. I started with 50 users and it incremented by 20 users per 5 seconds and max user limit was 500. The result was really shocking in terms of page response time.

asyncFTW

While average response time for the synchronous one is about 11.2 seconds, it is 3.65 for asynchronous one. I think the difference is pretty compelling and overwhelming.

From now on, I am adopting the Windows approach: "Anything longer than 40ms (operations related to network, file system. Mainly I/O bound operations), that is async!"

If you believe that some of the information here is wrong or misleading, please make me suffer and post a comment which would bring me down. Also, do the same if you have any additional information that is worth mentioning on this post but I missed.

Resources

Getting Started With ASP.NET Web API - Tutorials, Videos, Samples

I would like to point you those resources (Tutorials, Videos, Samples) in order to get started with ASP.NET Web API.
2012-02-24 06:49
Tugberk Ugurlu


ASP.NET team shipped the beta version of ASP.NET Web API which has been known as WCF Web API for more than a year. It has seen 6 preview versions and we have now nearly the final bits and pieces. The beta version of the product has been merged with ASP.NET MVC so that we won’t feel ourselves in a fork in the road in order to create REST APIs.

In my opinion, ASP.NET Web API is really exciting because it offers a simple and pluggable way to expose your data to the World. The one of the best parts is that you don’t have to just expose it as XML or JSON. You have the XML and JSON support out of the box but the format of the data is really up to you. Since nearly all of the devices out there today know how to communicate through HTTP, your data has the best possible reach.

One of the other great features of ASP.NET Web API is that everything has been built asynchrony in mind. So, you can scale out very easily. On the other hand, don’t act prejudicial that it is ASP.NET based and cannot run anywhere other than IIS. It has a self hosting capability as well (I honestly don’t know how it works at the background but it looks promising).

It has been not much since the product beta version has shipped but there are pretty good blog posts and articles about ASP.NET Web API out there. Instead of writing one, I would like to point you those resources.

Note

The follwing set of blog posts have been wtitten based on the beta release of ASP.NET Web API. It is highly likely that there will be some sort of conflicts if you are playing with a later version of the product.

Getting Started

Routing

Validation, Data Annotations & Model Binding

Message Handlers, Filters & Formatters

HttpClient

Dependency Injection & Unit Testing

Self Hosting

Uncategorized

Samples

Also, there are some great videos done by @jongalloway on ASP.NET web site as well as some other videos:

ASP.NET Web API Video Series

ASP.NET Web API Videos of Mine On NedirTv (In Turkish)

Some Other Great Talks, Webcasts and Other Type of Visuals

After-Beta Resources

The following blog posts target the features and changes which will be available for the next release of the product after beta.

Some Other Great Talks, Webcasts and Other Type of Visuals

If you have any other related blog post, tutorial, sample or whatever related to ASP.NET Web API, please comment and I will add them to this list. I will also add new things to this list that I come across. Enjoy:)

ASP.NET Web API and ELMAH Integration

See how ASP.NET Web API Plays Nice With ELMAH. This blog post is a Quick introduction to ASP.NET Web API and System.Web.Http.Filters.IExceptionFilter
2012-02-23 11:53
Tugberk Ugurlu


As you all probably heard, ASP.NET MVC 4 Beta is now available and has new features in it. One of them is that ASP.NET MVC has shipped with ASP.NET Web API (which was previously know as WCF Web API). Here is the quote from ASP.NET web site which explains what Web API Framework is all about shortly:

ASP.NET Web API is a framework that makes it easy to build HTTP services that reach a broad range of clients, including browsers and mobile devices. ASP.NET Web API is an ideal platform for building RESTful applications on the .NET Framework.

I am not going to give an into on ASP.NET Web API. There are great into tutorials and videos on ASP.NET web site for ASP.NET Web API. Instead, I will give you an example of a custom filter implementation.

A couple of months ago, I wrote a blog post about WCF Web API HttpErrorHandlers: WCF Web API Plays Nice With ELMAH - A Quick Introduction to WCF Web API HttpErrorHandler. It works nicely on WCF Web API but this version of the framework, things a little bit changed. Instead of ErrorHandlers, we now have Filters which is more generic.

In order to make ELMAH work with ASP.NET Web API, we need to create a new Attribute which implements IExceptionFilter interface. Since we have ExceptionFilterAttribute (which implements the IExceptionFilter interface) available at the framework, we will derived from that class instead. Here is the whole implementation:

public class ElmahErrorAttribute : 
    System.Web.Http.Filters.ExceptionFilterAttribute {

    public override void OnException(
        System.Web.Http.Filters.HttpActionExecutedContext actionExecutedContext) {

        if(actionExecutedContext.Exception != null)
            Elmah.ErrorSignal.FromCurrentContext().Raise(actionExecutedContext.Exception);

        base.OnException(actionExecutedContext);
    }
}

Now we have our attribute, we need to tell the framework to use it. It is very straight forward as well. Here is how my Global.asax (Global.asax.cs) looks like:

public class WebApiApplication : System.Web.HttpApplication {

    protected void Application_Start() {

        Configure(
            System.Web.Http.GlobalConfiguration.Configuration
        );
    }

    private void Configure(HttpConfiguration httpConfiguration) {

        httpConfiguration.Filters.Add(
            new ElmahErrorAttribute()
        );

        httpConfiguration.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
    }
}

This will make Elmah log the errors. Now, you can configure ELMAH to send you an e-mail when an error occurred or you can log the error inside an XML file, SQL Server Database, wherever you what.

One more thing to mention about is that when you hit an error, the response will carry the exception details at the body of the response if you run your application locally. You can configure this option as well with the following configuration:

httpConfiguration.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Never;

My Story of Seeing a Company Which Has High Level Cheapness At Their Core

I am telling you my story of seeing a company which has high level cheapness at their core and trying to explain why I think this way
2012-02-18 09:35
Tugberk Ugurlu


Yesterday, I went to fast food restaurant to have lunch after a wonderful movie (in Aydin, Turkey). As you expected, I was starving and try to figure out how to have it my way there. At the end, I decided to have a burger menu.

Just after I ordered, I nicely asked one more tiny mayonnaise and ketchup and the response that I got was unreasonably shocking and stupid. In a programmer's brain, it was a HTTP 509 Bandwidth Limit Exceeded. The reason why this is stupid is not that they asked me extra money for that, because I have been going their restaurants pretty often and they responded nicely and tried to make my dreams come true if I request the same thing. Not to mention their stuff told me that this is the rule that they have been applying for nearly two years. That's lie and a big one.

In the middle of my day, this really hit me and I thought that this was the lowest level a company can go down. This shows how poor and cheap their service is and that they have no idea on how to train their stuff so that they behave the same way. I am not judging them for asking extra money for these little boxes of souce, this is their cheapness in my opinion unless a person abuses this. I mean it is reasonable to reject the request of the person if s/he asked for 100 boxes of mayonnaise and ketchup but for one more, this is the high level of cheapness my dear friend.

The funny part is that they told me I could have one special souce since I ordered Chicken Tenders along with the burgers. That sentence really made my day. I told them to keep it as my donation to their poor company so that the company can grow more and get rid of this cheapness.

I am writing this as a customer complaint and you, that restaurant, should take this into considiration.

Tags