Async MVC Controllers

 

I previously wrote a post on MVC async controllers. Now I want to follow up on something that’s more cutting edge, unfortunately I’m one of those people that like nosing about with what new, how it will affect me and how I could leverage it in future etc., Often, I’ll readily admit it’s more bleeding edge than cutting edge (xaml support in Blend5 for example Thumbs down).

However in this post I want to show you something that you might agree is pretty nice.

A historical example

So lets take a look at the app we’re trying to build.

Client is a simple web form (yes it’s webforms but I’m trying to catch the non MVC microsofties too), the instruments are entered in the text box, fetch button is clicked and the result is output

image_thumb1

Now the workflow, for the purpose of this test I won’t be connecting to any database webservice etc, I’ve just added a delay of 10 seconds and and assign LastClose to RIC & " " & New Random().NextDouble()

image_thumb4

Here’s the code behind for the non-async button event handler

        protected void Button1_Click(object sender, EventArgs e)
        {
            Contract.Requires<ArgumentException>(!string.IsNullOrWhiteSpace(tbInst1.Text) || !string.IsNullOrWhiteSpace(tbInst2.Text), "Please enter values for instruments");
            // Make the call to the workflow to get the close for each instrument
            try
            {
                var args = new Dictionary<string, object>();
                args.Add("RIC", tbInst1.Text);                
                var res = WorkflowInvoker.Invoke(_getPricesWFDefinition, args);
                Label1.Text = res["LastClose"].ToString();
 
                args.Clear();
                args.Add("RIC", tbInst2.Text);
                res = WorkflowInvoker.Invoke(_getPricesWFDefinition, args);
                Label2.Text = res["LastClose"].ToString();
            }
            catch (Exception exp)
            {
                Trace.Warn(exp.Message);
            }
 
        }

So as you can see, we’re waiting at least 20 seconds for our page to return, nasty.
In theory we should be able to bring this down to 10 seconds as we can make the calls to the workflows in parallel.

Let me show you one way to “incorrectly” achieve this

        private void Option1()
        {
 
            var t1 = Option1TaskCreater(tbInst1, Label1);
            var t2 = Option1TaskCreater(tbInst2, Label2);
 
            Task.WaitAll(t1, t2);
 
        }
 
        private Task Option1TaskCreater(TextBox tb, Label lb)
        {
            var t1 = Task.Factory.StartNew(() =>
            {
                var args = new Dictionary<string, object>();
                args.Add("RIC", tb.Text);
                var res = WorkflowInvoker.Invoke(_getPricesWFDefinition, args);
                lb.Text = res["LastClose"].ToString();
            });
            return t1;
        } 

So we’re using the task library to make the two workflow requests async, and results look promising, down to about 10 seconds now… so any problems with doing this?

Well, tasks use threadpool threads to execute. So, the query will execute on a threadpool thread. To get true asynchronous execution(no worker threads blocked), we need to jump through a few more hoops. For webform people, there’s a very good explanation here. MVC people read on!

But Why/When use async?

The response to this question has been discussed many times in both books and magazines. ASP.NET uses threads from a common language runtime (CLR) thread pool to process requests. As long as there are threads available in the thread pool, ASP.NET has no trouble dispatching incoming requests. But once the thread pool becomes saturated-that is, all the threads inside it are busy processing requests and no free threads remain-new requests have to wait for threads to become free. If the jam becomes severe enough and the queue fills to capacity, ASP.NET throws up its hands and responds with a "Server Unavailable" to new requests.

Often to solve the problem of horizontal scalability more servers are added to the webfarm, however this only provided temporary relief to what in fact is an underlying design problem, it’s not a case of adding more processors(threads) but a case of using the threads more efficiently, as you can see from the diagram below, if you are CPU bound, there is little more you can do but add some more servers.

image_thumb2

So what is this telling us? Basically, if your app is I/O bound then you should use parallelism, if requests are computationally cheap to process, then parallelism is probably an unnecessary overhead.

If the incoming request rate is high, then adding more parallelism will likely yield few benefits and could actually decrease performance, since the incoming rate of work may be high enough to keep the CPUs busy.

If the incoming request rate is low, then the Web application could benefit from parallelism by using the idle CPU cycles to speed up the processing of an individual request. We can use either PLINQ or TPL (either Parallel loops or the Task class) to parallelize the computation over all the processors. Note that by default, however, the PLINQ implementation in .NET 4 will tie-up one ThreadPool worker per processor for the entire execution of the query. As such, it should only be used in Web applications that see few but expensive requests.

MVC4

In MVC4 it becomes even easier that my previous post on AsyncControllers, actually to me it looks quite like the WinRT async calls in .net 4.5 and C#5

Sample using task support for asynchronous controllers

You can now write asynchronous action methods as single methods that return an object of type Task or Task<ActionResult>.

e.g.

public async Task<ActionResult> Index(string city)
{    
    var newsService = new NewsService();    
    var sportsService = new SportsService();        
    return View("Common",        
                new PortalViewModel 
                {       
                    NewsHeadlines = await newsService.GetHeadlinesAsync(),        
                    SportsScores = await sportsService.GetScoresAsync()    
                });
}

In the previous action method, the calls to newsService.GetHeadlinesAsync andsportsService.GetScoresAsync are called asynchronously and do not block a thread from the thread pool.

Asynchronous action methods that return Task instances can also support timeouts. To make your action method cancellable, add a parameter of type CancellationToken to the action method signature. The following example shows an asynchronous action method that has a timeout of 2500 milliseconds and that displays a TimedOut view to the client if a timeout occurs.

[AsyncTimeout(2500)] 
[HandleError(ExceptionType = typeof(TaskCanceledException), View = "TimedOut")]
public async Task<ActionResult> Index(string city, CancellationToken cancellationToken) 
{    
    var newsService = new NewsService();    
    var sportsService = new SportsService();       
    return View("Common",        
        new PortalViewModel 
        {        
            NewsHeadlines = await newsService.GetHeadlinesAsync(cancellationToken),        
            SportsScores = await sportsService.GetScoresAsync(cancellationToken)    
        });
}
 
 
 

Conculsion

MVC4 Makes programming of async controllers even easier.

Layout in Windows Phone 7

 

So my wife left me for a hen weekend and I needed something to do with my time.
Friday night I dedicated to my real work to clear my conscience and then I went to play.

Windows 8

I spent a few frustrating hours on Saturday working on a Win8 application to compliment a certain website, frustrating… in so far as the Xaml designer in VS11/Blend on Windows 8 hangs like a good one. Actually at serveral points in time I considered changing my app to html5/js, because, for at least for the search section of the app I could see no blockers. However I want to add some pretty nifty features going forward and I don’t feel like implementing them in javascript.
I guess I may the possibility of writing them in C++/C# as a library and using this from the UX application if it continues to slow me down. I’ll have to consider cutting my losses soon if it keeps hanging the development environment that’s for sure (the joys of working with not only a Beta application, but a beta OS! Smile )

WP7

So for a bit of fresh air I started writing the WP7 app, at least this is more familiar ground to me having written quite a few of them already, and I just took my resource dictionaries from the WinRT app. To start with I just used some sample data in expression blend, dropped on a list box and bound my sample data to it.

image

But the layout wasn’t really what I wanted. I’m hoping that that API for the real data may provide me with a list of categories, one wouldn’t really want to have to release a new app every time a new section was added would they.
So my approach would be just to bind the data to a list for now (it may well turn out to be an ordered list in the API). The problem as you can see above what that I was getting a single row for each item.. not what I wanted.

Would you believe this was the first time I’ve not wanted this default layout in a WP7 app, so I decided to use the WrapPanel container that I’ve previously used in a WPF app… but alas it doesn’t exist out of the box!

Silverlight WP7 Toolkit to the rescue.

A quick Google indicated that the WP7 toolkit had the WrapPanel I was looking for, I fired up the Nuget package manager and added it to my project.

image

Items Panel

One more change was needed in my xaml, I needed to specify where to use this wrap panel.
This I specified in the ItemsPanelTemplate of the listbox in question.

image

The final result!

image

Hopefully this helps someone else out.

Reading a file in Windows 8 html5 js

 

Hi again, this is my last post were I compare the same WinRT application written in three different ways.

  • C++ / Xaml
  • C# / Xaml
  • JavaScript / html

My previous post covers c++ and c#, this one covers javascript.

JavaScript / html

image

image

I have to admit, this really took me by surprise! It was pretty painless. I had it written off before I even tried it, but this task proved somewhat simplistic. I’d one little obstacle trying to use a CDN, but other than that it was trivial.

So the penny has dropped, the WinRT developer pool is going to be massive! I predict good things.
If Microsoft play their cards correctly it will be a very successful platform (even more so with the promises of WP8 portability).

So what didn’t I like about this particular app? Not much really, other that realising I’ve a lot more talent to content with Winking smile

 

Summary

So I compared the three different approaches, for the task in question c#/xaml or js/html won hands down.
C++ was overkill.

I think each option would have to be considered on an application per application basis.

 

btw: on a non related note: my wife has just switched on the bedroom networked TV and windows 8 on the laptop here in the sitting room started installing stuff

image

I’m sure it’s got to be cool, if only I knew what for Smile

jQuery and WinRT

 

As part of this WinRT comparison I’m doing, I next need to recreate my apps in html+js.

This is my first WinRT app I’ve written in html+js and right off the mark I hit a problem with the WinRT sandbox. These days I won’t write a web app without jQuery it’s just awesome. so I wanted it in my app.

My first instinct was to use Nuget to bring down jQuery for me, but alas no Nuget extension that I could find for vs11, so next easiest step was to use the CDN. Sad smile doesn’t work.

So I go to jQuery.com, download it, and then use add the local script, now it all works.

image

hopefully this post might save someone a few minutes of head scratching.

Reading a file in windows 8 CPP vs CSharp

I left my last blog very indecisive, would I use CPP, would I use .NET or would it be html/js.

Again I’m thinking Cpp is really for faster and better performance, and while it might even be the hands down winner on ARM architecture, I don’t expect to see any performance differences in the app I’m going to write.

I’m actually going to write the same application 3 times, and I’ll review my findings as I go along.

I’ll present the c++ and the c# apps here and the html/js will follow in the next blog post.

First up was the cpp. To be honest I did find this painful to write, the syntax is pretty convoluted. At least the markup for cpp is Silverlight so that was a no brainer.

<Grid x:Name="LayoutRoot" Background="#FF0C0C0C">
    <Button Content="Open" HorizontalAlignment="Left" 
         Height="4" Margin="84,45,0,0" VerticalAlignment="Top"
         Width="194" Click="Button_Click"/>
    <TextBlock HorizontalAlignment="Left" Height="381" 
        Margin="282,45,0,0" Text="TextBox" VerticalAlignment="Top" 
        Width="1065" x:Name="tb1"/>
</Grid>

I’ll even use the same markup for the C# application.

Now to the code

C++

#include "pch.h"
#include "MainPage.xaml.h"
 
using namespace Windows::UI::Xaml;
using namespace Windows::UI::Xaml::Controls;
using namespace Windows::UI::Xaml::Data;
using namespace Windows::Storage;
using namespace Windows::Storage::Pickers;
using namespace Windows::Storage::Streams;
using namespace Windows::Foundation;
using namespace CppApplication17;
 
MainPage::MainPage()
{
    InitializeComponent();
}
 
MainPage::~MainPage()
{
}
 
void CppApplication17::MainPage::Button_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
{
 
    auto openPicker = ref new FileOpenPicker();
    openPicker->SuggestedStartLocation = PickerLocationId::Desktop;
    openPicker->FileTypeFilter->Append(".log");
    auto pickOp = openPicker->PickSingleFileAsync();
 
    TextBlock^ content = tb1;
 
    pickOp->Completed = ref new AsyncOperationCompletedHandler<StorageFile^>(
    [content](IAsyncOperation<StorageFile^>^ operation)
    {        
        StorageFile^ file = operation->GetResults();
        if (file)
        {
            //content->Text = file->FileName;
            auto openOp = file->OpenForReadAsync();
            openOp->Completed = ref new AsyncOperationCompletedHandler<IInputStream^>(
            [content, file](IAsyncOperation<IInputStream^>^ readOperation)
            {
                auto stream = readOperation->GetResults();
                auto reader = ref new DataReader(stream);
                auto loadOp = reader->LoadAsync(file->Size);
 
                loadOp->Completed = ref new AsyncOperationCompletedHandler<unsigned int>(
                [content, reader](IAsyncOperation<unsigned int>^ bytesRead)
                {
                    auto contentString = reader->ReadString(bytesRead->GetResults());
                    content->Text = contentString;
                });                
                loadOp->Start();
            });
            openOp->Start();
        }
    });
    pickOp->Start();
}

 

C#

using System;
using Windows.Storage.Pickers;
using Windows.Storage.Streams;
using Windows.UI.Xaml;
 
namespace CSharpApp12
{
    partial class MainPage
    {
        public MainPage()
        {
            InitializeComponent();
        }
 
        async private void Button_Click(object sender, RoutedEventArgs e)
        {
            var openPicker = new FileOpenPicker();
            openPicker.SuggestedStartLocation = PickerLocationId.Desktop;
            openPicker.FileTypeFilter.Add(".log");
            var file = await openPicker.PickSingleFileAsync();
            if (file != null)
            {
                uint size = (uint)file.Size;
                var inputStream = await file.OpenForReadAsync();
                var dataReader = new DataReader(inputStream);                
                tb1.Text = dataReader.ReadString(await dataReader.LoadAsync(size));                
            }
        }
    }
}

 

 

Now I’m not going to explain every trivial detail, but’s here where I felt I c# won out.

  • C++ 11 lambda syntax is a bit clumbsy, I don’t like having to pass down my closure variables or having to make a local copy first
  • C++ intellisense is vastly inferior, to the point of being just painful. Lets be honest, tooling cannot be under estimated when it comes to productivity. (this is why I when I write Java I find that only since i started using IntelliJ has my speed really ramped up, it’s the right tool for my background.)
  • I’m fast at typing, but using . is a lot faster than –> for pointers.
  • The async await construct is just magical!, now, to those you who I’m sure will complain that I’m comparing apples with oranges, you have a bit of a moot point, in C++ I could have used the parallel patterns library to make it a little neater, but nowhere near as close to C#.

My next post I’ll rewrite the same application in html + js. I predict that the syntax is not that difficult but productivity is where I feel I may fall down… let’s see.. It promises to be interesting.

It’s COM Jim, but not as we know it!

 

Those of you that started out in windows c++ like me are likely familiar with COMPunch, COM+Ghost, DCOM Ninja
If you stayed in unmanaged land then you’ve probably still very familiar with, ATL, HResults etc.
However if on the other hand, like me, you progressed into the managed realm, then those icons above probably sum up your recollections.

For me I once considered myself pretty hot in C++ (shamefully I still do but I’m sure I’d have to spend a week hands on to really tick that box), COM collections on stl (ICollectionOnSTLImpl) were a walk in the park, multiple inheritance was a given and finding you didn’t release a COM reference was the highlight of your day. But, fast forward a few years and then you really scratch your head as to why life had to be so difficult.

Well I’ll answer that question, performance is by far and above one of the biggest factors. With Windows8 fast approaching you may be starting to panic a little, I guess even more so if you started you coding life in a managed kingdom, but fear not, and let me dispel some common misconceptions that are solved with the C++ Component Extensions (C++/CX for short)

  • COM means HRESULTS – No, C++/CX gives yields exceptions from the underlying Fail HResults.
  • COM means no returns – No, C++/CX allows return values
  • COM means reference counting – Kinda, but you don’t have to worry about AddRef and Release, you use the “ref new” keyword and C++/CX does the reference counting for you (not garbage collection!)
  • COM mens CoCreateInstance etc - Again C++/CX ref new takes care of this for you
  • COM means interfaces - C++/CX takes care of IUnknow/IDispatch, if fact IDispatch has been superseded.
  • COM means no inheritance - C++/CX takes care of this for you.

So will I develop my apps in C++/C#/JS+Html (come on don’t expect me to add VB.NET that battle was lost a long time ago Smile.

Well here’s my feelings:

  • C++ maybe, depends on how much pref i need from my machines (sacrificing time to market), if i want to use an existing library,  Parallel patterns library, C++ AMP etc.
  • C# yes, I like this language and it’s a RAD language (albeit i won’t have access to the full Framework)
  • JS+HTML, I’m not sold on this yet, maybe, if i want to produce for the web then I choose js+html+asp not silverlight, would I ever have enough of a code base to reuse on WinRT??… jury is out..

Visual Studio you rock.

 

I’m was not sure what I’d installed but tonight I needed to create a few regular expressions, and as i started typing this appeared in VS2010

 

image

Pretty cool if I say so myself.

A quick look at my extension manager and I see

image

Visual Studio you rock!

I’ve used quite a few IDE’s lately

  • Netbeans
  • Eclipse
  • IntelliJ (pretty good)
  • XCode 4.0

One thing is for certain, only IntelliJ comes close (but then the Refactor developers are pretty familiar with VStudio Nyah-Nyah

Disclaimer: I’ve been using visual studio since the mid 90ies so I’m truly biased.

Converting EPM operations to Tasks using the TPL

 

Previous post

Overview

The Event Programming Model (EPM from her on in) was introduced in .NET 2.0, it’s purpose was to serve as a simpler pattern for asynchronous operations than the Asynchronous Programming Model (APM / IAsyncResult, see my previous post on APM) where possible, mostly in UX code. Methods that use this pattern typically end in Async and have a Completion event.

The best known implementation of the EPM is the BackgroundWorker component, it’s got a distinct advantage in that it tries to use a synchronization context to fire the event on the thread from which it was called, the APM on the other hand offers no such guarantee.

Let’s see this in action (.net 4.0)


image

What you can see in the snippet above is a simple windows form (been a while my old friend) application. Let me paint you a picture, it’s early February 2012 and I’m stuck here at Brussels international airport, in the middle of a snow blizzard wondering if I’m going to have a flight home. The plane that will take me there is arriving in from Dublin so I’m looking at the live departures to see if it’s departed (already 15 mins late darn it.. ) anyway back to the post at hand; I’m downloading the page html with the call to DownloadStringAsync(), you can see in the completion event handler that I’m not doing any Invoking (dispatching to those of you that never had the pleasure of windows forms).

Now this is what it looks like after the event gets fired.

image

hey and looks like it’s running MS tech (notice that viewstate, incase the .aspx didn’t give it away!) nice! If you come from a web background this may not seem that odd to you, but if you started out desktop application development like me there was one golden rule you never forgot and that’s that always talk to the GUI in one thread and one thread only.

If the event handler wasn’t in the GUI thread above we would have received a cross thread exception like this:

image

 

Sadly TPL doesn’t handle the EPM as easily as the APM specifically in respect to the synchronization context, but lets see how we approach it, you may have to if you’re pre .net 4.0 as the DownloadStringAsync doesn’t exist!

image

With the code above we hit the cross-thread exception problem. We could do a Control.BeginInvoke (or Dispatcher.BeginInvoke in WPF), but lets imagine we were writing a library and we wanted it to be framework agnostic, how would we do this?

Actually it’s pretty simple, we just supply a context like this:

image

p.s. I got home at 4am Sad smile

Strategy pattern

 

So what is the strategy pattern? It’s one of the simplest object orientated design patterns, I find that it helps clean up day to day object orientated design. It’s purpose is to

  • Encapsulate a family of related algorithms such that they are callable through a common interface.
  • Independent evolution, algorithms can vary and evolve separately from classes using them.
  • Allow a class to serve a single purpose
  • Separates the calculation from the the delivery of it’s results. (separation of concerns)
How do we know when we should consider the strategy pattern?
  • Look for switch statements with possible common interface
  • Adding a new calculation to a class could break existing calculations (breaking the Open-Close principle, i.e. a class should be open for extension, but closed for modification.

UML – Strategy model

image

Consequences:

  • Strategies may not use class members from context
  • Tests may now be written for individual concrete strategies
  • Strategies may be mocked when testing the Context class
  • Adding a new Strategy does not modify the Context class

How to implement:

  • Class based
  • Functional programming approach with anonymous methods (Delegates and Funcs as opposed to new classes), I like this when the calculations are trivial
  • Property injection
  • Method strategy (passed to a method and not to the context class constructor)

Show me the code:

    Context class

    image

    Here we see the strategy is getting passed to the context in the constructor, this class should be closed to modification, Trip is just an empty class for my demo and it’s not actually used in the calculation sample.

      Strategy interface
    image

      Sample Strategy

      image

       

      So, what is the strategy pattern again? It’s something you possibly do on a day to day basis and you don’t even realise it.

      e.g. If you write ASP.MVC code, you quite likely are passing interfaces to you controllers for dependency injection and testability ---> Strategy pattern.

      Regds,
      Brian.

    Converting APM operations to Tasks using the TPL

     

    Those of you have have already used .net 4.5 developer preview will know that tasks are becoming more common in the API, especially with the advent of the async await keywords.

    But many of you (including me) can’t really advocate .net 4.5 in the enterprise so what are our options should we like to use the TaskParallelLibrary?

    As you may be aware APM (Asynchronous Programming Model) was the original .NET mechanism for handling Async operations, it will be familiar to you as the IAsyncResult pattern.

    So lets take a common operation of reading from a stream, in .net 4.5 we already have a Stream.ReadAsync, but again what if we don’t have .net 4.5 at our disposal?

    The task parallel library helps bridge the gap with Task.Factory.FromAsync, here I place it in an extension method for ease of use.

    image