Skip to content

Understanding C# async/await (1) Compilation

Now the async / await keywords are in C# which provides great convenience. There are many nice documents talking about how to use async/await in specific scenarios, like using async methods in ASP.NET 4.5 and in ASP.NET MVC 4 etc. In this article we will look at the real code working behind the syntax.

Preparation

First of all, Some helper methods need to make up.

internal class HelperMethods
{
    private static void IO()
    {
        using (WebClient client = new WebClient())
        {
            Enumerable.Repeat("http://weblogs.asp.net/dixin", 10).Select(client.DownloadString).ToArray();
        }
    }

    internal static int Method(int arg0, int arg1)
    {
        int result = arg0 + arg1;
        IO(); // Do some long running IO.
        return result;
    }

    internal static Task<int> MethodTask(int arg0, int arg1)
    {
        Task<int> task = new Task<int>(() => Method(arg0, arg1));
        task.Start(); // Hot task (started task) should always be returned.
        return task;
    }

    internal static void Before()
    {
    }

    internal static void Continuation1(int arg)
    {
    }

    internal static void Continuation2(int arg)
    {
    }
}

Here Method() is a long running method doing some IO. Then MethodTask() wraps it into a Task and return that Task. Nothing special here.

Await something in async method

Since MethodTask() returns Task, let’s try to await it:

internal class AsyncMethods
{
    internal static async Task<int> MethodAsync(int arg0, int arg1)
    {
        int result = await HelperMethods.MethodTask(arg0, arg1);
        return result;
    }
}

Because we used await in the method, async must be put on the method. Now we get the first async method. According to the naming convenience, it is called MethodAsync. Of course a async method can be awaited. So we have a CallMethodAsync() to call MethodAsync():

internal class AsyncMethods
{
    internal static async Task<int> CallMethodAsync(int arg0, int arg1)
    {
        int result = await MethodAsync(arg0, arg1);
        return result;
    }
}

After compilation, MethodAsync() and CallMethodAsync() becomes the same logic. This is the code of MethodAsyc():

internal class CompiledAsyncMethods
{
    [DebuggerStepThrough]
    [AsyncStateMachine(typeof(MethodAsyncStateMachine))] // async
    internal static /*async*/ Task<int> MethodAsync(int arg0, int arg1)
    {
        MethodAsyncStateMachine methodAsyncStateMachine = new MethodAsyncStateMachine()
        {
            Arg0 = arg0,
            Arg1 = arg1,
            Builder = AsyncTaskMethodBuilder<int>.Create(),
            State = -1
        };
        methodAsyncStateMachine.Builder.Start(ref methodAsyncStateMachine);
        return methodAsyncStateMachine.Builder.Task;
    }
}

It just creates and starts a state machine MethodAsyncStateMachine:

[CompilerGenerated]
[StructLayout(LayoutKind.Auto)]
internal struct MethodAsyncStateMachine : IAsyncStateMachine
{
    public int State;
    public AsyncTaskMethodBuilder<int> Builder;
    public int Arg0;
    public int Arg1;
    public int Result;
    private TaskAwaiter<int> awaitor;

    void IAsyncStateMachine.MoveNext()
    {
        try
        {
            if (this.State != 0)
            {
                this.awaitor = HelperMethods.MethodTask(this.Arg0, this.Arg1).GetAwaiter();
                if (!this.awaitor.IsCompleted)
                {
                    this.State = 0;
                    this.Builder.AwaitUnsafeOnCompleted(ref this.awaitor, ref this);
                    return;
                }
            }
            else
            {
                this.State = -1;
            }

            this.Result = this.awaitor.GetResult();
        }
        catch (Exception exception)
        {
            this.State = -2;
            this.Builder.SetException(exception);
            return;
        }

        this.State = -2;
        this.Builder.SetResult(this.Result);
    }

    [DebuggerHidden]
    void IAsyncStateMachine.SetStateMachine(IAsyncStateMachine param0)
    {
        this.Builder.SetStateMachine(param0);
    }
}

The generated code has been cleaned up so it is readable and can be compiled. Several things can be observed here:

  • The async modifier is gone, which shows, unlike other modifiers (e.g. static), there is no such IL/CLR level “async” stuff. It becomes a AsyncStateMachineAttribute. This is similar to the compilation of extension method.
  • The generated state machine is very similar to the state machine of C# yield syntax sugar.
  • The local variables (arg0, arg1, result) are compiled to fields of the state machine.
  • The real code (await HelperMethods.MethodTask(arg0, arg1)) is compiled into MoveNext(): HelperMethods.MethodTask(this.Arg0, this.Arg1).GetAwaiter().

CallMethodAsync() will create and start its own state machine CallMethodAsyncStateMachine:

internal class CompiledAsyncMethods
{
    [DebuggerStepThrough]
    [AsyncStateMachine(typeof(CallMethodAsyncStateMachine))] // async
    internal static /*async*/ Task<int> CallMethodAsync(int arg0, int arg1)
    {
        CallMethodAsyncStateMachine callMethodAsyncStateMachine = new CallMethodAsyncStateMachine()
        {
            Arg0 = arg0,
            Arg1 = arg1,
            Builder = AsyncTaskMethodBuilder<int>.Create(),
            State = -1
        };
        callMethodAsyncStateMachine.Builder.Start(ref callMethodAsyncStateMachine);
        return callMethodAsyncStateMachine.Builder.Task;
    }
}

CallMethodAsyncStateMachine has the same logic as MethodAsyncStateMachine above. The detail of the state machine will be discussed soon. Now it is clear that:

  • async /await is a C# level syntax sugar.
  • There is no difference to await a async method or a normal method. A method returning Task will be awaitable, or – to be precise – Task can be awaited.

 

State machine and continuation

To demonstrate more details in the state machine, a more complex method is created:

internal class AsyncMethods
{
    internal static async Task<int> MultiCallMethodAsync(int arg0, int arg1, int arg2, int arg3)
    {
        HelperMethods.Before();
        int resultOfAwait1 = await MethodAsync(arg0, arg1);
        HelperMethods.Continuation1(resultOfAwait1);
        int resultOfAwait2 = await MethodAsync(arg2, arg3);
        HelperMethods.Continuation2(resultOfAwait2);
        int resultToReturn = resultOfAwait1 + resultOfAwait2;
        return resultToReturn;
    }
}

In this method:

  • There are multiple awaits.
  • There are code before the awaits, and continuation code after each await

After compilation, this multi-await method becomes the same as above single-await methods:

internal class CompiledAsyncMethods
{
    [DebuggerStepThrough]
    [AsyncStateMachine(typeof(MultiCallMethodAsyncStateMachine))] // async
    internal static /*async*/ Task<int> MultiCallMethodAsync(int arg0, int arg1, int arg2, int arg3)
    {
        MultiCallMethodAsyncStateMachine multiCallMethodAsyncStateMachine = new MultiCallMethodAsyncStateMachine()
        {
            Arg0 = arg0,
            Arg1 = arg1,
            Arg2 = arg2,
            Arg3 = arg3,
            Builder = AsyncTaskMethodBuilder<int>.Create(),
            State = -1
        };
        multiCallMethodAsyncStateMachine.Builder.Start(ref multiCallMethodAsyncStateMachine);
        return multiCallMethodAsyncStateMachine.Builder.Task;
    }
}

It creates and starts one single state machine, MultiCallMethodAsyncStateMachine:

[CompilerGenerated]
[StructLayout(LayoutKind.Auto)]
internal struct MultiCallMethodAsyncStateMachine : IAsyncStateMachine
{
    public int State;
    public AsyncTaskMethodBuilder<int> Builder;
    public int Arg0;
    public int Arg1;
    public int Arg2;
    public int Arg3;
    public int ResultOfAwait1;
    public int ResultOfAwait2;
    public int ResultToReturn;
    private TaskAwaiter<int> awaiter;

    void IAsyncStateMachine.MoveNext()
    {
        try
        {
            switch (this.State)
            {
                case -1:
                    HelperMethods.Before();
                    this.awaiter = AsyncMethods.MethodAsync(this.Arg0, this.Arg1).GetAwaiter();
                    if (!this.awaiter.IsCompleted)
                    {
                        this.State = 0;
                        this.Builder.AwaitUnsafeOnCompleted(ref this.awaiter, ref this);
                    }
                    break;
                case 0:
                    this.ResultOfAwait1 = this.awaiter.GetResult();
                    HelperMethods.Continuation1(this.ResultOfAwait1);
                    this.awaiter = AsyncMethods.MethodAsync(this.Arg2, this.Arg3).GetAwaiter();
                    if (!this.awaiter.IsCompleted)
                    {
                        this.State = 1;
                        this.Builder.AwaitUnsafeOnCompleted(ref this.awaiter, ref this);
                    }
                    break;
                case 1:
                    this.ResultOfAwait2 = this.awaiter.GetResult();
                    HelperMethods.Continuation2(this.ResultOfAwait2);
                    this.ResultToReturn = this.ResultOfAwait1 + this.ResultOfAwait2;
                    this.State = -2;
                    this.Builder.SetResult(this.ResultToReturn);
                    break;
            }
        }
        catch (Exception exception)
        {
            this.State = -2;
            this.Builder.SetException(exception);
        }
    }

    [DebuggerHidden]
    void IAsyncStateMachine.SetStateMachine(IAsyncStateMachine stateMachine)
    {
        this.Builder.SetStateMachine(stateMachine);
    }
}

The above code is already cleaned up, but there are still a lot of things. More clean up can be done, and the state machine can be very simple:

[CompilerGenerated]
[StructLayout(LayoutKind.Auto)]
internal struct MultiCallMethodAsyncStateMachine : IAsyncStateMachine
{
    // State:
    // -1: Begin
    //  0: 1st await is done
    //  1: 2nd await is done
    //     ...
    // -2: End
    public int State;
    public TaskCompletionSource<int> ResultToReturn; // int resultToReturn ...
    public int Arg0; // int Arg0
    public int Arg1; // int arg1
    public int Arg2; // int arg2
    public int Arg3; // int arg3
    public int ResultOfAwait1; // int resultOfAwait1 ...
    public int ResultOfAwait2; // int resultOfAwait2 ...
    private Task<int> currentTaskToAwait;

    /// <summary>
    /// Moves the state machine to its next state.
    /// </summary>
    void IAsyncStateMachine.MoveNext()
    {
        try
        {
            switch (this.State)
            {
                // Orginal code is splitted by "case"s:
                // case -1:
                //      HelperMethods.Before();
                //      MethodAsync(Arg0, arg1);
                // case 0:
                //      int resultOfAwait1 = await ...
                //      HelperMethods.Continuation1(resultOfAwait1);
                //      MethodAsync(arg2, arg3);
                // case 1:
                //      int resultOfAwait2 = await ...
                //      HelperMethods.Continuation2(resultOfAwait2);
                //      int resultToReturn = resultOfAwait1 + resultOfAwait2;
                //      return resultToReturn;
                case -1: // -1 is begin.
                    HelperMethods.Before(); // Code before 1st await.
                    this.currentTaskToAwait = AsyncMethods.MethodAsync(this.Arg0, this.Arg1); // 1st task to await
                    // When this.currentTaskToAwait is done, run this.MoveNext() and go to case 0.
                    this.State = 0;
                    IAsyncStateMachine this1 = this; // Cannot use "this" in lambda so create a local variable.
                    this.currentTaskToAwait.ContinueWith(_ => this1.MoveNext()); // Callback
                    break;
                case 0: // Now 1st await is done.
                    this.ResultOfAwait1 = this.currentTaskToAwait.Result; // Get 1st await's result.
                    HelperMethods.Continuation1(this.ResultOfAwait1); // Code after 1st await and before 2nd await.
                    this.currentTaskToAwait = AsyncMethods.MethodAsync(this.Arg2, this.Arg3); // 2nd task to await
                    // When this.currentTaskToAwait is done, run this.MoveNext() and go to case 1.
                    this.State = 1;
                    IAsyncStateMachine this2 = this; // Cannot use "this" in lambda so create a local variable.
                    this.currentTaskToAwait.ContinueWith(_ => this2.MoveNext()); // Callback
                    break;
                case 1: // Now 2nd await is done.
                    this.ResultOfAwait2 = this.currentTaskToAwait.Result; // Get 2nd await's result.
                    HelperMethods.Continuation2(this.ResultOfAwait2); // Code after 2nd await.
                    int resultToReturn = this.ResultOfAwait1 + this.ResultOfAwait2; // Code after 2nd await.
                    // End with resultToReturn.
                    this.State = -2; // -2 is end.
                    this.ResultToReturn.SetResult(resultToReturn);
                    break;
            }
        }
        catch (Exception exception)
        {
            // End with exception.
            this.State = -2; // -2 is end.
            this.ResultToReturn.SetException(exception);
        }
    }

    /// <summary>
    /// Configures the state machine with a heap-allocated replica.
    /// </summary>
    /// <param name="stateMachine">The heap-allocated replica.</param>
    [DebuggerHidden]
    void IAsyncStateMachine.SetStateMachine(IAsyncStateMachine stateMachine)
    {
        // No core logic.
    }
}

Only Task and TaskCompletionSource are involved in this version. And MultiCallMethodAsync() can be simplified to:

[DebuggerStepThrough]
[AsyncStateMachine(typeof(MultiCallMethodAsyncStateMachine))] // async
internal static /*async*/ Task<int> MultiCallMethodAsync_(int arg0, int arg1, int arg2, int arg3)
{
    MultiCallMethodAsyncStateMachine multiCallMethodAsyncStateMachine = new MultiCallMethodAsyncStateMachine()
        {
            Arg0 = arg0,
            Arg1 = arg1,
            Arg2 = arg2,
            Arg3 = arg3,
            ResultToReturn = new TaskCompletionSource<int>(),
            // -1: Begin
            //  0: 1st await is done
            //  1: 2nd await is done
            //     ...
            // -2: End
            State = -1
        };
    (multiCallMethodAsyncStateMachine as IAsyncStateMachine).MoveNext(); // Original code are in this method.
    return multiCallMethodAsyncStateMachine.ResultToReturn.Task;
}

Now the whole state machine becomes very clear – it is about callback:

  • Original code are split into pieces by “await”s, and each piece is put into each “case” in the state machine. Here the 2 awaits split the code into 3 pieces, so there are 3 “case”s.
  • The “piece”s are chained by callback, that is done by Builder.AwaitUnsafeOnCompleted(callback), or currentTaskToAwait.ContinueWith(callback) in the simplified code.
  • A previous “piece” will end with a Task (which is to be awaited), when the task is done, it will callback the next “piece”.
  • The state machine’s state works with the “case”s to ensure the code “piece”s executes one after another.

Callback

Since it is about callback, the simplification  can go even further – the entire state machine can be completely purged. Now MultiCallMethodAsync() becomes:

internal static Task<int> MultiCallMethodAsync(int arg0, int arg1, int arg2, int arg3)
{
    TaskCompletionSource<int> taskCompletionSource = new TaskCompletionSource<int>();
    try
    {
        // Oringinal code begins.
        HelperMethods.Before();
        MethodAsync(arg0, arg1).ContinueWith(await1 => { int resultOfAwait1 = await1.Result;
            HelperMethods.Continuation1(resultOfAwait1);
            MethodAsync(arg2, arg3).ContinueWith(await2 => { int resultOfAwait2 = await2.Result;
                HelperMethods.Continuation2(resultOfAwait2);
                int resultToReturn = resultOfAwait1 + resultOfAwait2;
        // Oringinal code ends.
                    
                taskCompletionSource.SetResult(resultToReturn);
            });
        });
    }
    catch (Exception exception)
    {
        taskCompletionSource.SetException(exception);
    }

    return taskCompletionSource.Task;
}

Please compare with the original async / await code:

HelperMethods.Before();
int resultOfAwait1 = await MethodAsync(arg0, arg1);
HelperMethods.Continuation1(resultOfAwait1);
int resultOfAwait2 = await MethodAsync(arg2, arg3);
HelperMethods.Continuation2(resultOfAwait2);
int resultToReturn = resultOfAwait1 + resultOfAwait2;
return resultToReturn;

Yeah that is the magic of C# async / await:

  • Await is literally pretending to wait. In a await expression, a Task object will be return immediately so that caller is not blocked. The continuation code is compiled as that Task’s callback code.
  • When that task is done, continuation code will execute.

Please notice that many details inside the state machine are omitted for simplicity, like context caring, etc. If you want to have a detailed picture, please do check out the source code of AsyncTaskMethodBuilder and TaskAwaiter.

What is new with ASP.NET Fall Update 2012

Download ASP.NET Fall Update 2012

  1. There are no new framework bits in this release – there is no change or update to the core products. This means that you can start using it without any updates to your server, upgrade concerns etc.
  2. This update is really an update to the project templates and Visual Studio tooling like ASP.NET MVC 3 Update.
  3. It’s a lightweight install (41 MB) download which usually take 5 – 7 minutes of installation time and never requires a reboot. You can download it here.
  4. Microsoft has added new project templates to ASP.NET MVC: Facebook Application and Single Page Templates.
  5. Lot of cool enhancements to ASP.NET Web API.
  6. Adds some tooling that makes it easy to take advantage of features like SignalR, Friendly URLs, and Windows Azure Authentication.
  7. Most of the new features are downloaded and installed as NuGet packages some from the Microsoft, a few from the community.
  8. Since ASP.NET is open source, nightly NuGet packages are available and a full fledged roadmap is available here. Most of this has been has been really been publicly available for a while.
  9. The official name of this drop is the ASP.NET Fall 2012 Update BUILD Prerelease.
  10. As with any Microsoft release, you can find out everything you need to know about the Fall Update at http://asp.net/vnext (especially the release notes).
  11. More details of this update are available at Bleeding edge ASP.NET: See what is next for MVC, Web API, SignalR and more…

More details for each of the updates to follow soon. Keep watching this blog.

Please leave your comments on which of the above feature that you want to be explained in detail.

Making animations work for disabled controls

Problem

I was using an animation to change the Background and Foreground color of a control, whenever a value attached to it changes; it was working fine except for controls which are disabled. One possible reason for this behavior is that a Rectangle or a Border is used in controls style when control is disabled, which overlays the Background panel, so even though the Background and Foreground color’s change they are not visible.

Here is the animation used

    <Storyboard     x:Key="Anim"     AutoReverse="True"     Duration="500"     FillBehavior="Stop">
        <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Background">
            <DiscreteObjectKeyFrame KeyTime="0:0:0.002">
                <DiscreteObjectKeyFrame.Value>
                    <SolidColorBrush Color="Red" />
                </DiscreteObjectKeyFrame.Value>
            </DiscreteObjectKeyFrame>
        </ObjectAnimationUsingKeyFrames>
        <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Foreground">
            <DiscreteObjectKeyFrame KeyTime="0:0:0.002">
                <DiscreteObjectKeyFrame.Value>
                    <SolidColorBrush Color="White" />
                </DiscreteObjectKeyFrame.Value>
            </DiscreteObjectKeyFrame>
        </ObjectAnimationUsingKeyFrames>
    </Storyboard>

I am setting the target for this animation at run time like this –

Storyboard anim = this.FindResource("Anim") as Storyboard; 
if (anim != null) 
{ 
    anim.SetValue(Storyboard.TargetProperty, animationTarget); 
}

and whenever value changes I do

_animation.Begin();

Note that animationTarget control can be of different type e.g. TextBox, DropDown, Calendar etc. and can be Enabled or Disabled based on ViewModel properties.

Solution

Using BooleanAnimationUsingKeyFrames: So after trying a lot of things finally I came across BooleanAnimationUsingKeyFrames, it Animates the value of a property that takes a Boolean along a set of KeyFrames over a specified Duration.

Here is the modified Storyboard –

    <Storyboard     x:Key="Anim"     AutoReverse="True"     Duration="500"     FillBehavior="Stop">
        <BooleanAnimationUsingKeyFrames Storyboard.TargetProperty="IsEnabled">
            <DiscreteBooleanKeyFrame             KeyTime="0:0:0.002"             Value="True" />
        </BooleanAnimationUsingKeyFrames>
        <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Background">
            <DiscreteObjectKeyFrame KeyTime="0:0:0.002">
                <DiscreteObjectKeyFrame.Value>
                    <SolidColorBrush Color="Red" />
                </DiscreteObjectKeyFrame.Value>
            </DiscreteObjectKeyFrame>
        </ObjectAnimationUsingKeyFrames>
        <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Foreground">
            <DiscreteObjectKeyFrame KeyTime="0:0:0.002">
                <DiscreteObjectKeyFrame.Value>
                    <SolidColorBrush Color="White" />
                </DiscreteObjectKeyFrame.Value>
            </DiscreteObjectKeyFrame>
        </ObjectAnimationUsingKeyFrames>
    </Storyboard>

So when this animation is applied control becomes enabled for short time interval, animation runs and the control is again disabled.

The only downside of this approach is that for some controls there is a flickering when animation is applied e.g. calendar control, calendar button becomes enabled when animation is applied and gets hidden after that.

Using TPL and PLINQ to raise performance of feed aggregator

In this posting I will show you how to use Task Parallel Library (TPL) and PLINQ features to boost performance of simple RSS-feed aggregator. I will use here only very basic .NET classes that almost every developer starts from when learning parallel programming. Of course, we will also measure how every optimization affects performance of feed aggregator.

Feed aggregator

Our feed aggregator works as follows:

  1. Load list of blogs
  2. Download RSS-feed
  3. Parse feed XML
  4. Add new posts to database

Our feed aggregator is run by task scheduler after every 15 minutes by example.

We will start our journey with serial implementation of feed aggregator. Second step is to use task parallelism and parallelize feeds downloading and parsing. And our last step is to use data parallelism to parallelize database operations.

We will use Stopwatch class to measure how much time it takes for aggregator to download and insert all posts from all registered blogs. After every run we empty posts table in database.

Serial aggregation

Before doing parallel stuff let’s take a look at serial implementation of feed aggregator. All tasks happen one after other.

internal class FeedClient
    private readonly INewsService _newsService;
    private const int FeedItemContentMaxLength = 255;
    public FeedClient()
    {
         ObjectFactory.Initialize(container =>
         {
             container.PullConfigurationFromAppConfig = true;
         });
        _newsService = ObjectFactory.GetInstance<INewsService>();
    }

    public void Execute()
    {
        var blogs = _newsService.ListPublishedBlogs();
        for (var index = 0; index <blogs.Count; index++)
        {
             ImportFeed(blogs[index]);
        }
    }

    private void ImportFeed(BlogDto blog)
    {
        if(blog == null)
            return;
        if (string.IsNullOrEmpty(blog.RssUrl))
            return;
        var uri = new Uri(blog.RssUrl);
        SyndicationContentFormat feedFormat;
        feedFormat = SyndicationDiscoveryUtility.SyndicationContentFormatGet(uri);
        if (feedFormat == SyndicationContentFormat.Rss)
            ImportRssFeed(blog);
        if (feedFormat == SyndicationContentFormat.Atom)
            ImportAtomFeed(blog);            
    }

    private void ImportRssFeed(BlogDto blog)
    {
        var uri = new Uri(blog.RssUrl);
        var feed = RssFeed.Create(uri);
        foreach (var item in feed.Channel.Items)
        {
            SaveRssFeedItem(item, blog.Id, blog.CreatedById);
        }
    }

    private void ImportAtomFeed(BlogDto blog)
    {
        var uri = new Uri(blog.RssUrl);
        var feed = AtomFeed.Create(uri);
        foreach (var item in feed.Entries)
        {
            SaveAtomFeedEntry(item, blog.Id, blog.CreatedById);
        }
    }
}

Serial implementation of feed aggregator downloads and inserts all posts with 25.46 seconds.

Task parallelism

Task parallelism means that separate tasks are run in parallel. You can find out more about task parallelism from MSDN page Task Parallelism (Task Parallel Library) and Wikipedia page Task parallelism. Although finding parts of code that can run safely in parallel without synchronization issues is not easy task we are lucky this time. Feeds import and parsing is perfect candidate for parallel tasks.

We can safely parallelize feeds import because importing tasks doesn’t share any resources and therefore they don’t also need any synchronization. After getting the list of blogs we iterate through the collection and start new TPL task for each blog feed aggregation.

using System;
using WebApplication1;
internal class FeedClient
    private readonly INewsService _newsService;
    private const int FeedItemContentMaxLength = 255;
    public FeedClient()
    {
         ObjectFactory.Initialize(container =>
         {
             container.PullConfigurationFromAppConfig = true;
         });
        _newsService = ObjectFactory.GetInstance<INewsService>();
    }

    public void Execute()
    {
        var blogs = _newsService.ListPublishedBlogs();       
        var tasks = new Task[blogs.Count];
        for (var index = 0; index <blogs.Count; index++)
        {
            tasks[index] = new Task(ImportFeed, blogs[index]);
            tasks[index].Start();
        }
        Task.WaitAll(tasks);
    }

    private void ImportFeed(object blogObject)
    {
        if(blogObject == null)
            return;
        var blog = (BlogDto)blogObject;
        if (string.IsNullOrEmpty(blog.RssUrl))
            return;
        var uri = new Uri(blog.RssUrl);
        SyndicationContentFormat feedFormat;
        feedFormat = SyndicationDiscoveryUtility.SyndicationContentFormatGet(uri);
        if (feedFormat == SyndicationContentFormat.Rss)
            ImportRssFeed(blog);
        if (feedFormat == SyndicationContentFormat.Atom)
            ImportAtomFeed(blog);           
    }

    private void ImportRssFeed(BlogDto blog)
    {
        var uri = new Uri(blog.RssUrl);
        var feed = RssFeed.Create(uri);
        foreach (var item in feed.Channel.Items)
        {
            SaveRssFeedItem(item, blog.Id, blog.CreatedById);
        }
    }
 
    private void ImportAtomFeed(BlogDto blog)
    {
        var uri = new Uri(blog.RssUrl);
        var feed = AtomFeed.Create(uri);
        foreach (var item in feed.Entries)
        {
            SaveAtomFeedEntry(item, blog.Id, blog.CreatedById);
        }
    }
}

You should notice first signs of the power of TPL. We made only minor changes to our code to parallelize blog feeds aggregating. On my machine this modification gives some performance boost – time is now 17.57 seconds.

Data parallelism

There is one more way how to parallelize activities. Previous section introduced task or operation based parallelism, this section introduces data based parallelism. By MSDN page Data Parallelism (Task Parallel Library) data parallelism refers to scenario in which the same operation is performed concurrently on elements in a source collection or array.

In our code we have independent collections we can process in parallel – imported feed entries. As checking for feed entry existence and inserting it if it is missing from database doesn’t affect other entries the imported feed entries collection is ideal candidate for parallelization.

internal class FeedClient
    private readonly INewsService _newsService;
    private const int FeedItemContentMaxLength = 255;
    public FeedClient()
    {
         ObjectFactory.Initialize(container =>
         {
             container.PullConfigurationFromAppConfig = true;
         });
        _newsService = ObjectFactory.GetInstance<INewsService>();
    }

    public void Execute()
    {
        var blogs = _newsService.ListPublishedBlogs();       
        var tasks = new Task[blogs.Count];
        for (var index = 0; index <blogs.Count; index++)
        {
            tasks[index] = new Task(ImportFeed, blogs[index]);
            tasks[index].Start();
        }
        Task.WaitAll(tasks);
     }

    private void ImportFeed(object blogObject)
    {
        if(blogObject == null)
            return;
        var blog = (BlogDto)blogObject;
        if (string.IsNullOrEmpty(blog.RssUrl))
            return;
        var uri = new Uri(blog.RssUrl);
        SyndicationContentFormat feedFormat;
        feedFormat = SyndicationDiscoveryUtility.SyndicationContentFormatGet(uri);
        if (feedFormat == SyndicationContentFormat.Rss)
            ImportRssFeed(blog);
        if (feedFormat == SyndicationContentFormat.Atom)
            ImportAtomFeed(blog);           
    }

    private void ImportRssFeed(BlogDto blog)
    {
        var uri = new Uri(blog.RssUrl);
        var feed = RssFeed.Create(uri);
        feed.Channel.Items.AsParallel().ForAll(a =>
        {
            SaveRssFeedItem(a, blog.Id, blog.CreatedById);
        });
     }

     private void ImportAtomFeed(BlogDto blog)
     {
        var uri = new Uri(blog.RssUrl);
        var feed = AtomFeed.Create(uri);
        feed.Entries.AsParallel().ForAll(a =>
        {
             SaveAtomFeedEntry(a, blog.Id, blog.CreatedById);
        });
     }
}

We did small change again and as the result we parallelized checking and saving of feed items. This change was data centric as we applied same operation to all elements in collection. On my machine I got better performance again. Time is now 11.22 seconds.

Results

As we can see then with task parallelism feed aggregation takes about 25% less time than in original case. When adding data parallelism to task parallelism our aggregation takes about 2.3 times less time than in original case.

More about TPL and PLINQ

Adding parallelism to your application can be very challenging task. You have to carefully find out parts of your code where you can safely go to parallel processing and even then you have to measure the effects of parallel processing to find out if parallel code performs better. If you are not careful then troubles you will face later are worse than ones you have seen before (imagine error that occurs by average only once per 10000 code runs).

Parallel programming is something that is hard to ignore. Effective programs are able to use multiple cores of processors. Using TPL you can also set degree of parallelism so your application doesn’t use all computing cores and leaves one or more of them free for host system and other processes. And there are many more things in TPL that make it easier for you to start and go on with parallel programming.

In next major version all .NET languages will have built-in support for parallel programming. There will be also new language constructs that support parallel programming. Currently you can download Visual Studio Async to get some idea about what is coming.

Conclusion

Parallel programming is very challenging but good tools offered by Visual Studio and .NET Framework make it way easier for us. In this posting we started with feed aggregator that imports feed items on serial mode. With two steps we parallelized feed importing and entries inserting gaining 2.3 times raise in performance. Although this number is specific to my test environment it shows clearly that parallel programming may raise the performance of your application significantly.

ASP.NET MVC–Showing Asterisk for required fields

Usually we have some required fields on our forms and it would be nice if ASP.NET MVC views can detect those fields automatically and display nice red asterisk after field label. As this functionality is not built in I built my own solution based on data annotations. In this posting I will show you how to show red asterisk after label of required fields.

Here are the main information sources I used when working out my own solution:

Although my code was first written for completely different situation I needed it later and I modified it to work with models that use data annotations. If data member of model has Required attribute set then asterisk is rendered after field. If Required attribute is missing then there will be no asterisk.

Here’s my code. You can take just LabelForRequired() methods and paste them to your own HTML extension class.

public static class HtmlExtensions

    [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", 
        Justification = "This is an appropriate nesting of generic types")]
 
    public static MvcHtmlString LabelForRequired<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression, string labelText = "")
     {
        return LabelHelper(html, ModelMetadata.FromLambdaExpression(expression, html.ViewData),
            ExpressionHelper.GetExpressionText(expression), labelText);
 
    }

    private static MvcHtmlString LabelHelper(HtmlHelper html,
         ModelMetadata metadata, string htmlFieldName, string labelText)
     {
         if (string.IsNullOrEmpty(labelText))
        {
 
            labelText = metadata.DisplayName ?? metadata.PropertyName ?? htmlFieldName.Split('.').Last();
        }

        if (string.IsNullOrEmpty(labelText))
        {
            return MvcHtmlString.Empty;
        }
        bool isRequired = false;
        if (metadata.ContainerType != null)
        {
 
            isRequired = metadata.ContainerType.GetProperty(metadata.PropertyName)
                             .GetCustomAttributes(typeof(RequiredAttribute), false)
                             .Length == 1;
        }
        TagBuilder tag = new TagBuilder("label");
         tag.Attributes.Add(
             "for",
             TagBuilder.CreateSanitizedId(
                 html.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(htmlFieldName)
             )
         );
       if (isRequired)
             tag.Attributes.Add("class", "label-required");
       tag.SetInnerText(labelText);
       var output = tag.ToString(TagRenderMode.Normal);
       if (isRequired)
       {
            var asteriskTag = new TagBuilder("span");
            asteriskTag.Attributes.Add("class", "required");
            asteriskTag.SetInnerText("*");
            output += asteriskTag.ToString(TagRenderMode.Normal);
       }
       return MvcHtmlString.Create(output);
    }
}

And here’s how to use LabelForRequired extension method in your view:

    <div class="field">
     @Html.LabelForRequired(m => m.Name)
     @Html.TextBoxFor(m => m.Name)
     @Html.ValidationMessageFor(m => m.Name)
    </div> 

After playing with CSS style called .required my example form looks like this:

These red asterisks are not part of original view mark-up. LabelForRequired method detected that these properties have Required attribute set and rendered out asterisks after field names.

NB! By default asterisks are not red. You have to define CSS class called “required” to modify how asterisk looks like and how it is positioned.

Integrating Flickr with ASP.Net application

Flickr is the popular photo management and sharing application offered by yahoo. The services from flicker allow you to store and share photos and videos online. Flicker offers strong API support for almost all services they provide. Using this API, developers can integrate photos to their public website. Since 2005, developers have collaborated on top of Flickr’s APIs to build fun, creative, and gorgeous experiences around photos that extend beyond Flickr.

In this article I am going to demonstrate how easily you can bring the photos stored on flicker to your website. Let me explain the scenario this article is trying to address. I have a flicker account where I upload photos and share in many ways offered by Flickr. Now I have a public website, instead of re-upload the photos again to public website, I want to show this from Flickr. Also I need complete control over what photo to display.

FlickerAPI for ASP.Net

To Integrate Flicker with ASP.Net applications, there is a library available in CodePlex. You can find it here

Visit the URL and download the latest version. The download includes a Zip file, when you unzip you will get a number of dlls. Since I am going to use ASP.Net application, I need FlickrNet.dll. See the screenshot of all the dlls, and there is a help file available in the download (.chm) for your reference.

Once you have the dll, you need to use Flickr API from your website. I assume you have a flicker account and you are familiar with Flicker services.

Arrange your photos using Sets in Flickr

In flicker, you can define sets and add your uploaded photos to sets. You can compare set to photo album. A set is a logical collection of photos, which is an excellent option for you to categorize your photos. Typically you will have a number of sets each set having few photos. You can write application that brings photos from sets to your website. For the purpose of this article I already created a set Flickr and added some photos to it. Once you logged in to Flickr, you can see the Sets under the Menu.

In the Sets page, you will see all the sets you have created. As you notice, you can see certain sample images I have uploaded just to test the functionality. Though I wish I couldn’t create good photos so please bear with me.

I have created 2 photo sets named Blue Album and Red Album. Click on the image for the set, will take you to the corresponding set page.

In the set “Red Album” there are 4 photos and the set has a unique ID. You can simply retrieve the photos with the set id from your application. In this article I am going to retrieve the images from Red album in my ASP.Net page. For that First I need to setup FlickrAPI for my usage.

Configure Flickr API Key

As I mentioned, we are going to use Flickr API to retrieve the photos stored in Flickr. In order to get access to Flickr API, you need an API key. To create an API key, navigate to the URL http://www.flickr.com/services/apps/create/

Click on Request an API key link, now you need to tell Flickr whether your application in commercial or non-commercial.

I have selected a non-commercial key. Now you need to enter certain information about your application.

Once you enter the details, Click on the submit button. Now Flickr will create the API key for your application.

Generating non-commercial API key is very easy, in couple of steps the key will be generated and you can use the key in your application immediately.

ASP.Net application for retrieving photos

Now we need write an ASP.Net application that display pictures from Flickr. Create an empty web application (I named this as FlickerIntegration) and add a reference to FlickerNet.dll. Add a web form page to the application where you will retrieve and display photos(I have named this as Gallery.aspx). After doing all these, the solution explorer will look similar to following.

I have used the below code in the Gallery.aspx page.

Image2

The output for the above code is as follows.

image3

I am going to explain the code line by line here.

First it is adding a reference to the FlickrNet namespace.

using FlickrNet;

Then create a Flickr object by using your API key.

Flickr f = new Flickr("<yourAPIKey>");

Now when you retrieve photos, you can decide what all fields you need to retrieve from Flickr. Every photo in Flickr contains lots of information. Retrieving all will affect the performance. For the demonstration purpose, I have retrieved all the available fields as follows.

PhotoSearchExtras.All

But if you want to specify the fields you can use logical OR operator(|). For e.g. the following statement will retrieve owner name and date taken.

PhotoSearchExtras extraInfo = PhotoSearchExtras.OwnerName | PhotoSearchExtras.DateTaken;

Then retrieve all the photos from a photo set using PhotoSetsGetPhotos method. I have passed the PhotoSearchExtras object created earlier.

PhotosetPhotoCollection photos = f.PhotosetsGetPhotos("72157629872940852", extraInfo);

The PhotoSetsGetPhotos method will return a collection of Photo objects. You can just navigate through the collection using a foreach statement.

foreach (Photo p in photos)
{
//access each photo properties
}

Photo class have lot of properties that map with the properties from Flickr. The chm documentation comes along with the CodePlex download is a great asset for you to understand the fields. In the above code I just used the following

p.LargeUrl – retrieves the large image url for the photo.

p.ThumbnailUrl – retrieves the thumbnail url for the photo

p.Title – retrieves the Title of the photo

p.DateUploaded – retrieves the date of upload

Visual Studio intellisense will give you all properties, so it is easy, you can just try with Visual Studio intellisense to find the right properties you are looking for.

Most of hem are self-explanatory. So you can try retrieving the required properties.

In the above code, I just pushed the photos to the page. In real time you can use the retrieved photos along with JQuery libraries to create animated photo galleries, slideshows etc.

Configuration and Troubleshooting

If you get access denied error while executing the code, you need to disable the caching in Flickr API. FlickrNet cache the photos to your local disk when retrieved. You can specify a cache folder where the application need write permission. You can specify the Cache folder in the code as follows.

Flickr.CacheLocation = Server.MapPath("./FlickerCache/");

If the application doesn’t have have write permission to the cache folder, the application will throw access denied error. If you cannot give write permission to the cache folder, then you must disable the caching. You can do this from code as follows.

Flickr.CacheDisabled = true;

Disabling cache will have an impact on the performance. Take care! Also you can define the Flickr settings in web.config file.You can find the documentation here.

Flickr is a great place for storing and sharing photos. The API access allows developers to do seamless integration with the photos uploaded on Flickr.

Consuming .NET Webservice using jQuery

Implementation shows the way to consume web service using jQuery.

The client side AJAX with HTTP POST request is significant when it comes to loading speed and responsiveness.
Following is the service created that return’s string in JSON.

[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string getData(string marks)
{
DataTable dt = retrieveDataTable("table", @"
SELECT * FROM TABLE WHERE MARKS=’"+ marks.ToString() +"’ ");
List<object> RowList = new List<object>();
foreach (DataRow dr in dt.Rows)
{
Dictionary<object, object> ColList = new Dictionary<object, object>();
foreach (DataColumn dc in dt.Columns)
{
ColList.Add(dc.ColumnName,
(string.Empty == dr[dc].ToString()) ? null : dr[dc]);
}
RowList.Add(ColList);
}
JavaScriptSerializer js = new JavaScriptSerializer();
string JSON = js.Serialize(RowList);
return JSON;
}

Consuming the webservice
$.ajax({
type: "POST",
data: ‘{ "marks": "’ + val + ‘"}’, // This is required if we are using parameters
contentType: "application/json",
dataType: "json",
url: "/dataservice.asmx/getData",
success: function(response) {
RES = JSON.parse(response.d);
var obj = JSON.stringify(RES);
}
error: function (msg) {
alert(‘failure’);
}
});

Remember to reference jQuery library on the page.

New SEO extension for the ASP.NET MVC routing engine

Cobisi SEO Extensions – this is the name of the product – is an advanced tool for software developers that allows to optimize ASP.NET MVC web applications and sites for search engines. It comes with a powerful routing engine, which extends the standard ASP.NET routing module to provide a much more flexible way to define search optimized routes, and a complete set of classes that make customizing the entire routing infrastructure very easy and cool.

In its simplest form, defining a route for an MVC action is just a matter of decorating the method with the [Route("…")] attribute and specifying the desired URL. The library will take care of the rest and set up the route accordingly; while coding routes this way, Cobisi SEO Extensions also shows how the final routes will be, without leaving the Visual Studio IDE!

Image1

Manage MVC routes with ease

In fact, Cobisi SEO Extensions integrates with the Visual Studio IDE to offer a large set of time-saving improvements targeted at ASP.NET developers. A new tool window, for example, allows to easily browse among the routes exposed by your applications, being them standard ASP.NET routes, MVC specific routes or SEO routes. The routes can be easily filtered on the fly, to ease finding the ones you are interested in. Double clicking a SEO route will even open the related ASP.NET MVC controller, at the beginning of the specified action method.

Image2

In addition to that, Cobisi SEO Extensions allows to easily understand how each SEO route is composed by showing the routing model details directly in the IDE, beneath each MVC action route.

image3

Furthermore, Cobisi SEO Extensions helps developers to easily recognize which class is an MVC controller and which methods is an MVC action by drawing a special dashed underline mark under each items of these categories.

Differences Between NHibernate and Entity Framework

NHibernate and Entity Framework are two of the most popular O/RM frameworks on the .NET world. Although they share some functionality, there are some aspects on which they are quite different. This post will describe this differences and will hopefully help you get started with the one you know less. Mind you, this is a personal selection of features to compare, it is by no way an exhaustive list.

History

First, a bit of history. NHibernate is an open-source project that was first ported from Java’s venerable Hibernate framework, one of the first O/RM frameworks, but nowadays it is not tied to it, for example, it has .NET specific features, and has evolved in different ways from those of its Java counterpart. Current version is 3.3, with 3.4 on the horizon. It currently targets .NET 3.5, but can be used as well in .NET 4, it only makes no use of any of its specific functionality. You can find its home page at NHForge.

Entity Framework 1 came out with .NET 3.5 and is now on its second major version, despite being version 4. Code First sits on top of it and but came separately and will also continue to be released out of line with major .NET distributions. It is currently on version 4.3.1 and version 5 will be released together with .NET Framework 4.5. All versions will target the current version of .NET, at the time of their release. Its home location is located at MSDN.

Architecture

In NHibernate, there is a separation between the Unit of Work and the configuration and model instances. You start off by creating a Configuration object, where you specify all global NHibernate settings such as the database and dialect to use, the batch sizes, the mappings, etc, then you build an ISessionFactory from it. The ISessionFactory holds model and metadata that is tied to a particular database and to the settings that came from the Configuration object, and, there will typically be only one instance of each in a process. Finally, you create instances of ISession from the ISessionFactory, which is the NHibernate representation of the Unit of Work and Identity Map. This is a lightweight object, it basically opens and closes a database connection as required and keeps track of the entities associated with it. ISession objects are cheap to create and dispose, because all of the model complexity is stored in the ISessionFactory and Configuration objects.

As for Entity Framework, the ObjectContext/DbContext holds the configuration, model and acts as the Unit of Work, holding references to all of the known entity instances. This class is therefore not lightweight as its NHibernate counterpart and it is not uncommon to see examples where an instance is cached on a field.

Mappings

Both NHibernate and Entity Framework (Code First) support the use of POCOs to represent entities, no base classes are required (or even possible, in the case of NHibernate).

As for mapping to and from the database, NHibernate supports three types of mappings:

  • XML-based, which have the advantage of not tying the entity classes to a particular O/RM; the XML files can be deployed as files on the file system or as embedded resources in an assembly;
  • Attribute-based, for keeping both the entities and database details on the same place at the expense of polluting the entity classes with NHibernate-specific attributes;
  • Strongly-typed code-based, which allows dynamic creation of the model and strongly typing it, so that if, for example, a property name changes, the mapping will also be updated.

Entity Framework can use:

  • Attribute-based (although attributes cannot express all of the available possibilities – for example, cascading);
  • Strongly-typed code mappings.

Database Support

With NHibernate you can use mostly any database you want, including:

  • SQL Server;
  • SQL Server Compact;
  • SQL Server Azure;
  • Oracle;
  • DB2;
  • PostgreSQL;
  • MySQL;
  • Sybase Adaptive Server/SQL Anywhere;
  • Firebird;
  • SQLLite;
  • Informix;
  • Any through OLE DB;
  • Any through ODBC.

Out of the box, Entity Framework only supports SQL Server, but a number of providers exist, both free and commercial, for some of the most used databases, such as Oracle and MySQL. See a list here.

Inheritance Strategies

Both NHibernate and Entity Framework support the three canonical inheritance strategies: Table Per Type Hierarchy (Single Table Inheritance), Table Per Type (Class Table Inheritance) and Table Per Concrete Type (Concrete Table Inheritance).

Associations

Regarding associations, both support one to one, one to many and many to many. However, NHibernate offers far more collection types:

  • Bags of entities or values: unordered, possibly with duplicates;
  • Lists of entities or values: ordered, indexed by a number column;
  • Maps of entities or values: indexed by either an entity or any value;
  • Sets of entities or values: unordered, no duplicates;
  • Arrays of entities or values: indexed, immutable.

Querying

NHibernate exposes several querying APIs:

  • LINQ is probably the most used nowadays, and really does not need to be introduced;
  • Hibernate Query Language (HQL) is a database-agnostic, object-oriented SQL-alike language that exists since NHibernate’s creation and still offers the most advanced querying possibilities; well suited for dynamic queries, even if using string concatenation;
  • Criteria API is an implementation of the Query Object pattern where you create a semi-abstract conceptual representation of the query you wish to execute by means of a class model; also a good choice for dynamic querying;
  • Query Over offers a similar API to Criteria, but using strongly-typed LINQ expressions instead of strings; for this, although more refactor-friendlier that Criteria, it is also less suited for dynamic queries;
  • SQL, including stored procedures, can also be used;
  • Integration with Lucene.NET indexer is available.

As for Entity Framework:

  • LINQ to Entities is fully supported, and its implementation is considered very complete; it is the API of choice for most developers;
  • Entity-SQL, HQL’s counterpart, is also an object-oriented, database-independent querying language that can be used for dynamic queries;
  • SQL, of course, is also supported.

Caching

Both NHibernate and Entity Framework, of course, feature first-level cache. NHibernate also supports a second-level cache, that can be used among multiple ISessionFactorys, even in different processes/machines:

Out of the box, Entity Framework does not have any second-level cache mechanism, however, there are some public samples that show how we can add this.

ID Generators

NHibernate supports different ID generation strategies, coming from the database and otherwise:

  • Identity (for SQL Server, MySQL, and databases who support identity columns);
  • Sequence (for Oracle, PostgreSQL, and others who support sequences);
  • Trigger-based;
  • HiLo;
  • Sequence HiLo (for databases that support sequences);
  • Several GUID flavors, both in GUID as well as in string format;
  • Increment (for single-user uses);
  • Assigned (must know what you’re doing);
  • Sequence-style (either uses an actual sequence or a single-column table);
  • Table of ids;
  • Pooled (similar to HiLo but stores high values in a table);
  • Native (uses whatever mechanism the current database supports, identity or sequence).

Entity Framework only supports:

  • Identity generation;
  • GUIDs;
  • Assigned values.

Properties

NHibernate supports properties of entity types (one to one or many to one), collections (one to many or many to many) as well as scalars and enumerations. It offers a mechanism for having complex property types generated from the database, which even include support for querying. It also supports properties originated from SQL formulas.

Entity Framework only supports scalars, entity types and collections. Enumerations support will come in the next version.

Events and Interception

NHibernate has a very rich event model, that exposes more than 20 events, either for synchronous pre-execution or asynchronous post-execution, including:

  • Pre/Post-Load;
  • Pre/Post-Delete;
  • Pre/Post-Insert;
  • Pre/Post-Update;
  • Pre/Post-Flush.

It also features interception of class instancing and SQL generation.

As for Entity Framework, only two events exist:

Tracking Changes

For NHibernate as well as Entity Framework, all changes are tracked by their respective Unit of Work implementation. Entities can be attached and detached to it, Entity Framework does, however, also support self-tracking entities.

Optimistic Concurrency Control

NHibernate supports all of the imaginable scenarios:

  • SQL Server’s ROWVERSION;
  • Oracle’s ORA_ROWSCN;
  • A column containing date and time;
  • A column containing a version number;
  • All/dirty columns comparison.

Entity Framework is more focused on Entity Framework, so it only supports:

  • SQL Server’s ROWVERSION;
  • Comparing all/some columns.

Batching

NHibernate has full support for insertion batching, but only if the ID generator in use is not database-based (for example, it cannot be used with Identity), whereas Entity Framework has no batching at all.

Cascading

Both support cascading for collections and associations: when an entity is deleted, their conceptual children are also deleted. NHibernate also offers the possibility to set the foreign key column on children to NULL instead of removing them.

Flushing Changes

NHibernate’s ISession has a FlushMode property that can have the following values:

  • Auto: changes are sent to the database when necessary, for example, if there are dirty instances of an entity type, and a query is performed against this entity type, or if the ISession is being disposed;
  • Commit: changes are sent when committing the current transaction;
  • Never: changes are only sent when explicitly calling Flush().

As for Entity Framework, changes have to be explicitly sent through a call to AcceptAllChanges()/SaveChanges().

Lazy Loading

NHibernate supports lazy loading for

  • Associated entities (one to one, many to one);
  • Collections (one to many, many to many);
  • Scalar properties (thing of BLOBs or CLOBs).

Entity Framework only supports lazy loading for:

  • Associated entities;
  • Collections.

Generating and Updating the Database

Both NHibernate and Entity Framework Code First (with the Migrations API) allow creating the database model from the mapping and updating it if the mapping changes.

Extensibility

As you can guess, NHibernate is far more extensible than Entity Framework. Basically, everything can be extended, from ID generation, to LINQ to SQL transformation, HQL native SQL support, custom column types, custom association collections, SQL generation, supported databases, etc. With Entity Framework your options are more limited, at least, because practically no information exists as to what can be extended/changed. It features a provider model that can be extended to support any database.

Integration With Other Microsoft APIs and Tools

When it comes to integration with Microsoft technologies, it will come as no surprise that Entity Framework offers the best support. For example, the following technologies are fully supported:

Documentation

This is another point where Entity Framework is superior: NHibernate lacks, for starters, an up to date API reference synchronized with its current version. It does have a community mailing list, blogs and wikis, although not much used. Entity Framework has a number of resources on MSDN and, of course, several forums and discussion groups exist.

Conclusion

Like I said, this is a personal list. I may come as a surprise to some that Entity Framework is so behind NHibernate in so many aspects, but it is true that NHibernate is much older and, due to its open-source nature, is not tied to product-specific timeframes and can thus evolve much more rapidly. I do like both, and I chose whichever is best for the job I have at hands. I am looking forward to the changes in EF5 which will add significant value to an already interesting product.

So, what do you think? Did I forget anything important or is there anything else worth talking about? Looking forward for your comments!

Separate Web API’s action for mobile request using ASP.NET MVC 4

ASP.NET MVC 4.0 has two great features: One is Display Mode allows you to create mobile-specific and desktop-specific views and Second is Web API platform for building RESTful applications. Sometimes, You might need to return different data or perform different operations for desktop and mobile request. This article explains how to implement separate actions for mobile request keeping same URL format in Web API.

1. In Visual Studio, Select File > New Project > ASP.NET MVC 4 Web Application > Enter name > OK

2. Select ‘Web API‘ > View Engine: ‘Razor‘ > OK

3. You’ll get default ValuesController. When you access <your app url>/api/Values, the array of string value1, value2 is returned.

To create separate action for mobile request, We are going to create separate controller having ‘Mobile‘ suffix.

Right Click on ‘Controllers‘ folder > Add Controller > Give Name ‘ValuesMobileController‘ > Template: ‘API Controller with empty read/write actions‘ > Add

To differentiate both controllers, replace value1, value2 to mobile-value1, mobile-value2 in get method.

4. Now our object is to call action of Mobile controller when request comes from mobile device.

In Global.asax:

default api route:

routes.MapHttpRoute(

name: "DefaultApi",

routeTemplate: "api/{controller}/{id}",

defaults: new { id = RouteParameter.Optional }

);

Change it to:

routes.MapHttpRoute(

name: "DefaultApi",

routeTemplate: "api/{controller}/{id}",

defaults: new { id = RouteParameter.Optional }

).RouteHandler = new MyRouteHandler();

and add following class:

public class MyRouteHandler : HttpControllerRouteHandler

{

protected override IHttpHandler GetHttpHandler(RequestContext requestContext)

{

//Check whether request comes from mobile browser

if (requestContext.HttpContext.Request.Browser.IsMobileDevice)

{

string controller = requestContext.RouteData.Values["controller"].ToString();

requestContext.RouteData.Values["controller"] = controller + "Mobile";

}

return new MyHttpControllerHandler(requestContext.RouteData);

}

}

public class MyHttpControllerHandler : HttpControllerHandler, IRequiresSessionState

{

public MyHttpControllerHandler(RouteData routeData)

: base(routeData)

{

}

}

You have to import following namespaces:

using System.Web.Http.WebHost;
using System.Web.SessionState;

In this RouteHandler, Request.Browser.IsMobileDevice checks whether request comes from mobile browser and change controller name with ‘Mobile‘ suffix.

Now run app on browser, For testing, You can change user-agent to iPhone with user agent switcher Firefox add-on and open same URL. you’ll get mobile-value1 and mobile-value2.