Category Archives: 2669

C# 5.0 Async/Await Demo Code

I’ve published the sample code I use to demonstrate the use of async/await in C# 5.0. You can find it here.

Projects

PauloMorgado.AyncDemo.WebServer

This project is a simple web server implemented as a console application using Microsoft ASP.NET Web API self hosting and serves an image (with a delay) that is accessed by the other projects.

This project has a dependency on Json.NET due to the fact the the Microsoft ASP.NET Web API hosting has a dependency on Json.NET.

The application must be run on a command prompt with administrative privileges or a urlacl must be added to allow the use of the following command:

netsh http add urlacl url=http://+:9090/ user=machine\username


To remove the urlacl, just use the following command:



netsh http delete urlacl url=http://+:9090/


PauloMorgado.AsyncDemo.WindowsForms



This Windows Forms project contains three regions that must be uncommented one at a time:



Sync with WebClient



This code retrieves the image through a synchronous call using the WebClient class.



Async with WebClient



This code retrieves the image through an asynchronous call using the WebClient class.



Async deadlock



This code how async operations can still deadlock.



Async with HttpClient with cancelation



This code retrieves the image through an asynchronous call with cancelation using the HttpClient class.



PauloMorgado.AsyncDemo.Wpf



This WPF project contains three regions that must be uncommented one at a time:



Sync with WebClient



This code retrieves the image through a synchronous call using the WebClient class.



Async with WebClient



This code retrieves the image through an asynchronous call using the WebClient class.



Async deadlock



This code how async operations can still deadlock.



Async with HttpClient with cancelation



This code retrieves the image through an asynchronous call with cancelation using the HttpClient class.

Extension Methods And Type Inference In Action

I make extensive use of extension methods, either to make classes small and focused or to improve readability.

While porting a .NET 1.1 WinForms application to C# 3.0, I found lots of code like this:

delegate int Int32DelegateStringBoolean(string text, bool flag);

void DoStuff()
{
    // ...

    var x = (int)this.Invoke(new Int32DelegateStringBoolean(GetStuff), new object[] { "some text", true });

    // ...
}

int GetStuff(string text, bool flag)
{
    // ...
}


.NET 2.0 introduced a nicer API and it became possible to write the code calling Invoke like this:



var x = (int)this.Invoke(new Int32DelegateStringBoolean(GetStuff), "some text", true);


But it’s still not strongly typed enough to my taste and the compiler can’t verify if any mistake was made. This will still be valid code at compile time that will break at run time:



var x = (long)this.Invoke(new Int32DelegateStringBoolean(GetStuff), "some text", 10M, 5);


To make the code safer and more readable, I decided to create extension methods to extend the Control class and provide strongly type Invoke methods.



Instead of defining custom delegates for each need, I used the Action and Func delegates exiting in the framework and wrote extension methods like this:



public static TResult InvokeFunc<T1, T2, TResult>(this Control control, Func<T1, T2, TResult> func, T1 param1, T2 param2)
{
    return (TResult)(control.Invoke(func, param1, param2));
}


Now I can replace the call to Invoke with this call:



var x = this.InvokeFunc<string, bool, int>(new Func<string, bool, int>(GetStuff), "some text", true);


And the compiler is now able to match the type of the delegate, the parameters and the return value.



Starting with the C# 2.0 compiler, there is no need to write the delegate instantiation if the compiler can infer the type of the delegate, which makes the code even simpler:



var x = this.InvokeFunc<string, bool, int>(GetStuff, "some text", true);


The C# compiler is even capable of inferring the type parameters of the InvokeFunc method making the code even smaller and more readable:



var x = this.InvokeFunc(GetStuff, "some text", true);


A lot better than what we started with, isn’t it?



So far, I’ve implemented these:



/// <summary>
/// Provides extended functionality to <see cref="System.Windows.Forms.Control"/>.
/// </summary>
public static class ControlExtensions
{
    /// <summary>
    /// Executes the specified function (<paramref name="func"/>) on the thread that owns the control's underlying window handle.
    /// </summary>
    /// <typeparam name="TResult">The type of the result.</typeparam>
    /// <param name="control">The control to invoke the function on.</param>
    /// <param name="func">The function to invoke.</param>
    /// <returns>A <typeparamref name="TResult"/> that contains the return value from the function (<paramref name="func"/>) being invoked.</returns>
    public static TResult InvokeFunc<TResult>(this Control control, Func<TResult> func)
    {
        return (TResult)(control.Invoke(func));
    }

    /// <summary>
    /// Executes the specified function (<paramref name="func"/>) on the thread that owns the control's underlying window handle.
    /// </summary>
    /// <typeparam name="T1">The type of the parameter of the function.</typeparam>
    /// <typeparam name="TResult">The type of the result.</typeparam>
    /// <param name="control">The control to invoke the function on.</param>
    /// <param name="func">The function to invoke.</param>
    /// <param name="param1">The parameter of the action.</param>
    /// <returns>A <typeparamref name="TResult"/> that contains the return value from the function (<paramref name="func"/>) being invoked.</returns>
    public static TResult InvokeFunc<T1, TResult>(this Control control, Func<T1, TResult> func, T1 param1)
    {
        return (TResult)(control.Invoke(func, param1));
    }

    /// <summary>
    /// Executes the specified function (<paramref name="func"/>) on the thread that owns the control's underlying window handle.
    /// </summary>
    /// <typeparam name="T1">The type of the first parameter of the function.</typeparam>
    /// <typeparam name="T2">The type of the second parameter of the function.</typeparam>
    /// <typeparam name="TResult">The type of the result.</typeparam>
    /// <param name="control">The control to invoke the function on.</param>
    /// <param name="func">The function to invoke.</param>
    /// <param name="param1">The first parameter of the function.</param>
    /// <param name="param2">The second parameter of the function.</param>
    /// <returns>A <typeparamref name="TResult"/> that contains the return value from the function (<paramref name="func"/>) being invoked.</returns>
    public static TResult InvokeFunc<T1, T2, TResult>(this Control control, Func<T1, T2, TResult> func, T1 param1, T2 param2)
    {
        return (TResult)(control.Invoke(func, param1, param2));
    }

    /// <summary>
    /// Executes the specified function (<paramref name="func"/>) on the thread that owns the control's underlying window handle.
    /// </summary>
    /// <typeparam name="T1">The type of the first parameter of the function.</typeparam>
    /// <typeparam name="T2">The type of the second parameter of the function.</typeparam>
    /// <typeparam name="T3">The type of the third parameter of the function.</typeparam>
    /// <typeparam name="TResult">The type of the result.</typeparam>
    /// <param name="control">The control to invoke the function on.</param>
    /// <param name="func">The function to invoke.</param>
    /// <param name="param1">The first parameter of the function.</param>
    /// <param name="param2">The second parameter of the function.</param>
    /// <param name="param3">The third parameter of the function.</param>
    /// <returns>A <typeparamref name="TResult"/> that contains the return value from the function (<paramref name="func"/>) being invoked.</returns>
    public static TResult InvokeFunc<T1, T2, T3, TResult>(this Control control, Func<T1, T2, T3, TResult> func, T1 param1, T2 param2, T3 param3)
    {
        return (TResult)(control.Invoke(func, param1, param2, param3));
    }

    /// <summary>
    /// Executes the specified function (<paramref name="func"/>) on the thread that owns the control's underlying window handle.
    /// </summary>
    /// <typeparam name="T1">The type of the first parameter of the function.</typeparam>
    /// <typeparam name="T2">The type of the second parameter of the function.</typeparam>
    /// <typeparam name="T3">The type of the third parameter of the function.</typeparam>
    /// <typeparam name="T4">The type of the forth parameter of the function.</typeparam>
    /// <typeparam name="TResult">The type of the result.</typeparam>
    /// <param name="control">The control to invoke the function on.</param>
    /// <param name="func">The function to invoke.</param>
    /// <param name="param1">The first parameter of the function.</param>
    /// <param name="param2">The second parameter of the function.</param>
    /// <param name="param3">The third parameter of the function.</param>
    /// <param name="param4">The forth parameter of the function.</param>
    /// <returns>A <typeparamref name="TResult"/> that contains the return value from the function (<paramref name="func"/>) being invoked.</returns>
    public static TResult InvokeFunc<T1, T2, T3, T4, TResult>(this Control control, Func<T1, T2, T3, T4, TResult> func, T1 param1, T2 param2, T3 param3, T4 param4)
    {
        return (TResult)(control.Invoke(func, param1, param2, param3, param4));
    }

    /// <summary>
    /// Executes the specified action (<paramref name="action"/>) on the thread that owns the control's underlying window handle.
    /// </summary>
    /// <param name="control">The control to invoke the action on.</param>
    /// <param name="action">The action to invoke.</param>
    public static void InvokeAction(this Control control, Action action)
    {
        control.Invoke(action);
    }

    /// <summary>
    /// Executes the specified action (<paramref name="action"/>) on the thread that owns the control's underlying window handle.
    /// </summary>
    /// <typeparam name="T">The type of the parameter.</typeparam>
    /// <param name="control">The control to invoke the action on.</param>
    /// <param name="action">The action to invoke.</param>
    /// <param name="param">The parameter of the action.</param>
    public static void InvokeAction<T>(this Control control, Action<T> action, T param)
    {
        control.Invoke(action, param);
    }

    /// <summary>
    /// Executes the specified action (<paramref name="action"/>) on the thread that owns the control's underlying window handle.
    /// </summary>
    /// <typeparam name="T1">The type of the first parameter of the action.</typeparam>
    /// <typeparam name="T2">The type of the second parameter of the action.</typeparam>
    /// <param name="control">The control to invoke the action on.</param>
    /// <param name="action">The action to invoke.</param>
    /// <param name="param1">The first parameter of the action.</param>
    /// <param name="param2">The second parameter of the action.</param>
    public static void InvokeAction<T1, T2>(this Control control, Action<T1, T2> action, T1 param1, T2 param2)
    {
        control.Invoke(action, param1, param2);
    }

    /// <summary>
    /// Executes the specified action (<paramref name="action"/>) on the thread that owns the control's underlying window handle.
    /// </summary>
    /// <typeparam name="T1">The type of the first parameter of the action.</typeparam>
    /// <typeparam name="T2">The type of the second parameter of the action.</typeparam>
    /// <typeparam name="T3">The type of the third parameter of the action.</typeparam>
    /// <param name="control">The control to invoke the action on.</param>
    /// <param name="action">The action to invoke.</param>
    /// <param name="param1">The first parameter of the action.</param>
    /// <param name="param2">The second parameter of the action.</param>
    /// <param name="param3">The third parameter of the action.</param>
    public static void InvokeAction<T1, T2, T3>(this Control control, Action<T1, T2, T3> action, T1 param1, T2 param2, T3 param3)
    {
        control.Invoke(action, param1, param2, param3);
    }

    /// <summary>
    /// Executes the specified action (<paramref name="action"/>) on the thread that owns the control's underlying window handle.
    /// </summary>
    /// <typeparam name="T1">The type of the first parameter of the action.</typeparam>
    /// <typeparam name="T2">The type of the second parameter of the action.</typeparam>
    /// <typeparam name="T3">The type of the third parameter of the action.</typeparam>
    /// <typeparam name="T4">The type of the forth parameter of the action.</typeparam>
    /// <param name="control">The control to invoke the action on.</param>
    /// <param name="action">The action to invoke.</param>
    /// <param name="param1">The first parameter of the action.</param>
    /// <param name="param2">The second parameter of the action.</param>
    /// <param name="param3">The third parameter of the action.</param>
    /// <param name="param4">The forth parameter of the action.</param>
    public static void InvokeAction<T1, T2, T3, T4>(this Control control, Action<T1, T2, T3, T4> action, T1 param1, T2 param2, T3 param3, T4 param4)
    {
        control.Invoke(action, param1, param2, param3, param4);
    }
    /// <summary>
    /// Executes the specified function (<paramref name="func"/>) on the thread that owns the control's underlying window handle.
    /// </summary>
    /// <typeparam name="TResult">The type of the result.</typeparam>
    /// <param name="control">The control to BeginInvoke the function on.</param>
    /// <param name="func">The function to BeginInvoke.</param>
    /// <returns>An System.IAsyncResult that represents the result of the operation.</returns>
    public static IAsyncResult BeginInvokeFunc<TResult>(this Control control, Func<TResult> func)
    {
        return control.BeginInvoke(func);
    }

    /// <summary>
    /// Executes the specified function (<paramref name="func"/>) on the thread that owns the control's underlying window handle.
    /// </summary>
    /// <typeparam name="T1">The type of the parameter of the function.</typeparam>
    /// <typeparam name="TResult">The type of the result.</typeparam>
    /// <param name="control">The control to BeginInvoke the function on.</param>
    /// <param name="func">The function to BeginInvoke.</param>
    /// <param name="param1">The parameter of the action.</param>
    /// <returns>An System.IAsyncResult that represents the result of the operation.</returns>
    public static IAsyncResult BeginInvokeFunc<T1, TResult>(this Control control, Func<T1, TResult> func, T1 param1)
    {
        return control.BeginInvoke(func, param1);
    }

    /// <summary>
    /// Executes the specified function (<paramref name="func"/>) on the thread that owns the control's underlying window handle.
    /// </summary>
    /// <typeparam name="T1">The type of the first parameter of the function.</typeparam>
    /// <typeparam name="T2">The type of the second parameter of the function.</typeparam>
    /// <typeparam name="TResult">The type of the result.</typeparam>
    /// <param name="control">The control to BeginInvoke the function on.</param>
    /// <param name="func">The function to BeginInvoke.</param>
    /// <param name="param1">The first parameter of the function.</param>
    /// <param name="param2">The second parameter of the function.</param>
    /// <returns>An System.IAsyncResult that represents the result of the operation.</returns>
    public static IAsyncResult BeginInvokeFunc<T1, T2, TResult>(this Control control, Func<T1, T2, TResult> func, T1 param1, T2 param2)
    {
        return control.BeginInvoke(func, param1, param2);
    }

    /// <summary>
    /// Executes the specified function (<paramref name="func"/>) on the thread that owns the control's underlying window handle.
    /// </summary>
    /// <typeparam name="T1">The type of the first parameter of the function.</typeparam>
    /// <typeparam name="T2">The type of the second parameter of the function.</typeparam>
    /// <typeparam name="T3">The type of the third parameter of the function.</typeparam>
    /// <typeparam name="TResult">The type of the result.</typeparam>
    /// <param name="control">The control to BeginInvoke the function on.</param>
    /// <param name="func">The function to BeginInvoke.</param>
    /// <param name="param1">The first parameter of the function.</param>
    /// <param name="param2">The second parameter of the function.</param>
    /// <param name="param3">The third parameter of the function.</param>
    /// <returns>An System.IAsyncResult that represents the result of the operation.</returns>
    public static IAsyncResult BeginInvokeFunc<T1, T2, T3, TResult>(this Control control, Func<T1, T2, T3, TResult> func, T1 param1, T2 param2, T3 param3)
    {
        return control.BeginInvoke(func, param1, param2, param3);
    }

    /// <summary>
    /// Executes the specified function (<paramref name="func"/>) on the thread that owns the control's underlying window handle.
    /// </summary>
    /// <typeparam name="T1">The type of the first parameter of the function.</typeparam>
    /// <typeparam name="T2">The type of the second parameter of the function.</typeparam>
    /// <typeparam name="T3">The type of the third parameter of the function.</typeparam>
    /// <typeparam name="T4">The type of the forth parameter of the function.</typeparam>
    /// <typeparam name="TResult">The type of the result.</typeparam>
    /// <param name="control">The control to BeginInvoke the function on.</param>
    /// <param name="func">The function to BeginInvoke.</param>
    /// <param name="param1">The first parameter of the function.</param>
    /// <param name="param2">The second parameter of the function.</param>
    /// <param name="param3">The third parameter of the function.</param>
    /// <param name="param4">The forth parameter of the function.</param>
    /// <returns>An System.IAsyncResult that represents the result of the operation.</returns>
    public static IAsyncResult BeginInvokeFunc<T1, T2, T3, T4, TResult>(this Control control, Func<T1, T2, T3, T4, TResult> func, T1 param1, T2 param2, T3 param3, T4 param4)
    {
        return control.BeginInvoke(func, param1, param2, param3, param4);
    }

    /// <summary>
    /// Executes the specified action (<paramref name="action"/>) on the thread that owns the control's underlying window handle.
    /// </summary>
    /// <param name="control">The control to BeginInvoke the action on.</param>
    /// <param name="action">The action to BeginInvoke.</param>
    /// <returns>An System.IAsyncResult that represents the result of the operation.</returns>
    public static IAsyncResult BeginInvokeAction(this Control control, Action action)
    {
        return control.BeginInvoke(action);
    }

    /// <summary>
    /// Executes the specified action (<paramref name="action"/>) on the thread that owns the control's underlying window handle.
    /// </summary>
    /// <typeparam name="T">The type of the parameter.</typeparam>
    /// <param name="control">The control to BeginInvoke the action on.</param>
    /// <param name="action">The action to BeginInvoke.</param>
    /// <param name="param">The parameter of the action.</param>
    /// <returns>An System.IAsyncResult that represents the result of the operation.</returns>
    public static IAsyncResult BeginInvokeAction<T>(this Control control, Action<T> action, T param)
    {
        return control.BeginInvoke(action, param);
    }

    /// <summary>
    /// Executes the specified action (<paramref name="action"/>) on the thread that owns the control's underlying window handle.
    /// </summary>
    /// <typeparam name="T1">The type of the first parameter of the action.</typeparam>
    /// <typeparam name="T2">The type of the second parameter of the action.</typeparam>
    /// <param name="control">The control to BeginInvoke the action on.</param>
    /// <param name="action">The action to BeginInvoke.</param>
    /// <param name="param1">The first parameter of the action.</param>
    /// <param name="param2">The second parameter of the action.</param>
    /// <returns>An System.IAsyncResult that represents the result of the operation.</returns>
    public static IAsyncResult BeginInvokeAction<T1, T2>(this Control control, Action<T1, T2> action, T1 param1, T2 param2)
    {
        return control.BeginInvoke(action, param1, param2);
    }

    /// <summary>
    /// Executes the specified action (<paramref name="action"/>) on the thread that owns the control's underlying window handle.
    /// </summary>
    /// <typeparam name="T1">The type of the first parameter of the action.</typeparam>
    /// <typeparam name="T2">The type of the second parameter of the action.</typeparam>
    /// <typeparam name="T3">The type of the third parameter of the action.</typeparam>
    /// <param name="control">The control to BeginInvoke the action on.</param>
    /// <param name="action">The action to BeginInvoke.</param>
    /// <param name="param1">The first parameter of the action.</param>
    /// <param name="param2">The second parameter of the action.</param>
    /// <param name="param3">The third parameter of the action.</param>
    /// <returns>An System.IAsyncResult that represents the result of the operation.</returns>
    public static IAsyncResult BeginInvokeAction<T1, T2, T3>(this Control control, Action<T1, T2, T3> action, T1 param1, T2 param2, T3 param3)
    {
        return control.BeginInvoke(action, param1, param2, param3);
    }

    /// <summary>
    /// Executes the specified action (<paramref name="action"/>) on the thread that owns the control's underlying window handle.
    /// </summary>
    /// <typeparam name="T1">The type of the first parameter of the action.</typeparam>
    /// <typeparam name="T2">The type of the second parameter of the action.</typeparam>
    /// <typeparam name="T3">The type of the third parameter of the action.</typeparam>
    /// <typeparam name="T4">The type of the forth parameter of the action.</typeparam>
    /// <param name="control">The control to BeginInvoke the action on.</param>
    /// <param name="action">The action to BeginInvoke.</param>
    /// <param name="param1">The first parameter of the action.</param>
    /// <param name="param2">The second parameter of the action.</param>
    /// <param name="param3">The third parameter of the action.</param>
    /// <param name="param4">The forth parameter of the action.</param>
    /// <returns>An System.IAsyncResult that represents the result of the operation.</returns>
    public static IAsyncResult BeginInvokeAction<T1, T2, T3, T4>(this Control control, Action<T1, T2, T3, T4> action, T1 param1, T2 param2, T3 param3, T4 param4)
    {
        return control.BeginInvoke(action, param1, param2, param3, param4);
    }
}


Use them if you need to.

.NET Framework 2.0 Service Pack 1 and .NET Framework Service Pack 1 available as a standalone download

For those who can’t (or don’t want to) deploy .NET Framework 3.5, the service packs included for the 2.0 and 3.0 versions of the framework are available as standalone downloads.

Visual Studio 2008 and .NET Framework 3.5 shipped!

Visual Studio 2008 and .NET Framework 3.5 has finally shipped.

MSDN subscribers can download the final version of Visual Studio 2008 from MSDN Subscription Downloads, but anyone can get a trial version or an Express Edition.

The .NET Framework 3.5 contains many new features building incrementally upon .NET Framework 2.0 and 3.0, and includes .NET Framework 2.0 service pack 1 and .NET Framework 3.0 service pack 1. and is also available for download.

You can read all about it from various teams and team member’s blogs:

WebBrowserControl for the .NET Framework 1.1 Updated

“My” WebBrowserControl for the .NET Framework 1.1 has been updated.

A few bugs were fixed and a few changes were made to the API (still thinking of a .NET 2.0 version).

I managed to solve all the problems with the design time but, unfortunately, the PropertyGrid throws an exception when the WebBrowserControl is bound to it:

System.NullReferenceException: Object reference not set to an instance of an object.
   at System.Windows.Forms.PropertyGridInternal.GridEntry.Create(PropertyGridView view, Object[] rgobjs, IServiceProvider baseProvider, IDesignerHost currentHost, PropertyTab tab, PropertySort initialSortType)
   at System.Windows.Forms.PropertyGrid.UpdateSelection()
   at System.Windows.Forms.PropertyGrid.RefreshProperties(Boolean clearCached)
   at System.Windows.Forms.PropertyGrid.Refresh(Boolean clearCached)
   at System.Windows.Forms.PropertyGrid.set_SelectedObjects(Object[] value)
   at System.Windows.Forms.PropertyGrid.set_SelectedObject(Object value)

Does anyone have a clue?

Smart Client Software Factory – May 2007 Release is Live

(From Blaine Wastell‘s post and Mariano Szklanny‘s post)

You can now download the SCSF – May 2007 release. The new release provides support for .NET 3.0. The release is propagating to the download servers and should be available when you read this. If not, be patient and try a little later.

The release provides:

  • Windows Presentation Foundation interoperability CAB extensions  and View with presenter recipe (don’t miss this post from Miguel Saez for more details)
  • Offline application blocks and recipes; the application blocks support asynchronous calls to WCF web services.
  • Richer ClickOnce Deployment capabilities
  • Enhanced guidance packages which includes code generation Visual Basic .NET 2005 (don’t miss this post from Juan Arguello for more details)
  • Improved installation with a new dependency checker
  • Compatibility with Enterprise Library 3.1.

Here are instructions to install the factory. The team has created a new Getting Starting topic on Codeplex. This topic includes instructions to create a Hello World Application with the factory.

Check it out and let them know how you like it.

And this means that the team is going to start it’s work on the Web Client Software Factory.

Culture and Region Information tool for .NET 2.0

Defining custom culture and region information is a common practice in many enterprise environments.

In the .NET Framework 2.0, we can use the CultureAndRegionInfoBuilder class build a custom culture that is new or based on an existing culture and region. The custom culture can be installed on a computer and subsequently used by any application running on that computer.

Using this class I’ve built a small command line tool to extract, register and unregister culture and region information.

Scoped Context Store

Sometimes I need to store data scoped by some context and isolated from the other scopes.

If I’m building a library that is to be used in both Windows client and Web server enviroments, I have different isolation/scope needs: for a Web server environment, the scope is the current HTTP context; for a Windows client environment, the scope is the current process.

Having that in mind, I just published an article in CodeProject.