<?xml version="1.0" encoding="UTF-8" ?>
<?xml-stylesheet type="text/xsl" href="http://weblogs.asp.net/utility/FeedStylesheets/atom.xsl" media="screen"?><feed xmlns="http://www.w3.org/2005/Atom" xml:lang="en"><title type="html">Pablo M. Cibraro (aka Cibrax) </title><subtitle type="html">My thoughts on Web Services and .NET development</subtitle><id>http://weblogs.asp.net/cibrax/atom.aspx</id><link rel="alternate" type="text/html" href="http://weblogs.asp.net/cibrax/default.aspx" /><link rel="self" type="application/atom+xml" href="http://weblogs.asp.net/cibrax/atom.aspx" /><generator uri="http://communityserver.org" version="3.0.20510.895">Community Server</generator><updated>2012-04-20T11:10:00Z</updated><entry><title>Giving temporary access to your ASP.NET Web API with Hawk</title><link rel="alternate" type="text/html" href="http://weblogs.asp.net/cibrax/archive/2013/03/08/giving-temporary-access-to-your-asp-net-web-api-with-hawk.aspx" /><id>http://weblogs.asp.net/cibrax/archive/2013/03/08/giving-temporary-access-to-your-asp-net-web-api-with-hawk.aspx</id><published>2013-03-08T15:00:12Z</published><updated>2013-03-08T15:00:12Z</updated><content type="html">&lt;p&gt;One of the features supported by Hawk, an HTTP authentication protocol based on HMAC, is to provide read-only access to a Web API for a short period time.&amp;#160; That’s performed through a token called “bewit” that a Web API can provide to a client. That token is only valid for Http GET calls and it can be used for a limited period of time.&lt;/p&gt;  &lt;p&gt;I already implemented this feature in my &lt;a href="https://github.com/pcibraro/hawknet"&gt;Hawk port for .NET&lt;/a&gt;. A bewit token can be generated as it is shown below,&lt;/p&gt;  &lt;pre class="csharpcode"&gt;var credential = &lt;span class="kwrd"&gt;new&lt;/span&gt; HawkCredential
{
     Id = &lt;span class="str"&gt;&amp;quot;dh37fgj492je&amp;quot;&lt;/span&gt;,
     Key = &lt;span class="str"&gt;&amp;quot;werxhqb98rpaxn39848xrunpaw3489ruxnpa98w4rxn&amp;quot;&lt;/span&gt;,
     Algorithm = &lt;span class="str"&gt;&amp;quot;hmacsha256&amp;quot;&lt;/span&gt;,
     User = &lt;span class="str"&gt;&amp;quot;steve&amp;quot;&lt;/span&gt;
 };

var bewit = Hawk.GetBewit(&lt;span class="str"&gt;&amp;quot;localhost&amp;quot;&lt;/span&gt;, 
  &lt;span class="kwrd"&gt;new&lt;/span&gt; Uri(&lt;span class="str"&gt;&amp;quot;http://localhost:8091/Api/HelloWorld&amp;quot;&lt;/span&gt;), 
  credential, 
  60000);&lt;/pre&gt;

&lt;p&gt;The GetBewit method expects the following arguments,&lt;style type="text/css"&gt;
.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }&lt;/style&gt;&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;The host name&lt;/li&gt;

  &lt;li&gt;The complete request URI&lt;/li&gt;

  &lt;li&gt;The Hawk credentials with information about the key and algorithm to use&lt;/li&gt;

  &lt;li&gt;A time-to-live setting in seconds for the token&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;That token is an string representation that you can add as a additional query string in the Web API call.&lt;/p&gt;

&lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;new&lt;/span&gt; HttpRequestMessage(HttpMethod.Get, 
  &lt;span class="str"&gt;&amp;quot;http://localhost:8091/Api/HelloWorld?bewit=&amp;quot;&lt;/span&gt; + bewit);&lt;/pre&gt;

&lt;p&gt;In that way, you can share a link to your Web API with a limited access for a period of time to someone without having to share any security credentials. &lt;/p&gt;

&lt;p&gt;On the service side is as simple as configuring the HawkMessageHandler as part of the Web API configuration,&lt;/p&gt;

&lt;pre class="csharpcode"&gt;var handler = &lt;span class="kwrd"&gt;new&lt;/span&gt; HawkMessageHandler((id) =&amp;gt;
{
     &lt;span class="kwrd"&gt;return&lt;/span&gt; &lt;span class="kwrd"&gt;new&lt;/span&gt; HawkCredential
     {
           Id = id,
           Key = &lt;span class="str"&gt;&amp;quot;werxhqb98rpaxn39848xrunpaw3489ruxnpa98w4rxn&amp;quot;&lt;/span&gt;,
           Algorithm = &lt;span class="str"&gt;&amp;quot;hmacsha256&amp;quot;&lt;/span&gt;,
           User = &lt;span class="str"&gt;&amp;quot;steve&amp;quot;&lt;/span&gt;
       };
 });

config.MessageHandlers.Add(handler);&lt;/pre&gt;
&lt;style type="text/css"&gt;
.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }&lt;/style&gt;

&lt;p&gt;The handler will automatically detect a bewit token in the query string, and it will performed all the required validations.&lt;style type="text/css"&gt;
.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }&lt;/style&gt;&lt;/p&gt;&lt;img src="http://weblogs.asp.net/aggbug.aspx?PostID=9961047" width="1" height="1"&gt;</content><author><name>cibrax</name><uri>http://weblogs.asp.net/members/cibrax.aspx</uri></author><category term="ASP.NET" scheme="http://weblogs.asp.net/cibrax/archive/tags/ASP.NET/default.aspx" /><category term=".NET" scheme="http://weblogs.asp.net/cibrax/archive/tags/.NET/default.aspx" /><category term="Web API" scheme="http://weblogs.asp.net/cibrax/archive/tags/Web+API/default.aspx" /></entry><entry><title>ASP.NET Web API Logging and Troubleshooting</title><link rel="alternate" type="text/html" href="http://weblogs.asp.net/cibrax/archive/2013/03/01/asp-net-web-api-logging-and-troubleshooting.aspx" /><id>http://weblogs.asp.net/cibrax/archive/2013/03/01/asp-net-web-api-logging-and-troubleshooting.aspx</id><published>2013-03-01T14:48:00Z</published><updated>2013-03-01T14:48:00Z</updated><content type="html">&lt;p&gt;ASP.NET ships with two built-in mechanisms for doing logging and troubleshooting.&amp;#160; Chasing errors without knowing these two mechanisms might be a daunting task, specially if they happen in the runtime pipeline much before a message gets to a handler or a controller. &lt;/p&gt;  &lt;p&gt;The first mechanism is the error policy. You can configure the error policy preferences as part of the configuration object (HttpConfiguration) in the IncludeErrorDetailPolicy property. This is just an enum that instructs Web API about how to deal with exceptions. &lt;/p&gt;  &lt;p&gt;The possible values for this enum are,&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;Default: It’s uses the customErrors configuration settings if you are using ASP.NET as host or LocalOnly for self-host.&lt;/li&gt;    &lt;li&gt;LocalOnly: Only includes error details for local requests&lt;/li&gt;    &lt;li&gt;Always: Always includes error details&lt;/li&gt;    &lt;li&gt;Never: Never includes error details&lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;When an exception happens, Web API will check the value on this setting for including details about the exception in the response message or not. For example, if Always is enabled, Web API will serialize the exception details as part of the message that you get as response.&lt;/p&gt;  &lt;p&gt;The second mechanism is Tracing. Tracing is a service that you can inject as part of the configuration object as well. The default implementation does do anything. &lt;/p&gt;  &lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;static&lt;/span&gt; &lt;span class="kwrd"&gt;void&lt;/span&gt; Register(HttpConfiguration config)
{
    config.Services.Replace(&lt;span class="kwrd"&gt;typeof&lt;/span&gt;(ITraceWriter), &lt;span class="kwrd"&gt;new&lt;/span&gt; MyTracer());
}&lt;/pre&gt;
&lt;style type="text/css"&gt;
.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }&lt;/style&gt;

&lt;p&gt;MyTracer is a custom implementation of the ITraceWriter service, which Web API uses for tracing purposes. This is a general tracing mechanism, so Web API will call it for logging everything and not just errors. &lt;/p&gt;

&lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;class&lt;/span&gt; MyTracer : ITraceWriter
{
    &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;void&lt;/span&gt; Trace(HttpRequestMessage request, &lt;span class="kwrd"&gt;string&lt;/span&gt; category, TraceLevel level, 
        Action&amp;lt;TraceRecord&amp;gt; traceAction)
    {
        TraceRecord rec = &lt;span class="kwrd"&gt;new&lt;/span&gt; TraceRecord(request, category, level);
        traceAction(rec);
        WriteTrace(rec);
    }

    &lt;span class="kwrd"&gt;protected&lt;/span&gt; &lt;span class="kwrd"&gt;void&lt;/span&gt; WriteTrace(TraceRecord rec)
    {
        var message = &lt;span class="kwrd"&gt;string&lt;/span&gt;.Format(&lt;span class="str"&gt;&amp;quot;{0};{1};{2}&amp;quot;&lt;/span&gt;, 
            rec.Operator, rec.Operation, rec.Message);
        System.Diagnostics.Trace.WriteLine(message, rec.Category);
    }
}&lt;/pre&gt;

&lt;p&gt;If any of these two work for you, you can still use an Error Filter.&amp;#160; Tugberk has written a blog post about how to integrate ELMAH with an Error Filter in Web API &lt;a href="http://www.tugberkugurlu.com/archive/asp-net-web-api-and-elmah-integration"&gt;here&lt;/a&gt;.&lt;style type="text/css"&gt;
.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }&lt;/style&gt;&lt;/p&gt;&lt;img src="http://weblogs.asp.net/aggbug.aspx?PostID=9930247" width="1" height="1"&gt;</content><author><name>cibrax</name><uri>http://weblogs.asp.net/members/cibrax.aspx</uri></author><category term="ASP.NET" scheme="http://weblogs.asp.net/cibrax/archive/tags/ASP.NET/default.aspx" /><category term=".NET" scheme="http://weblogs.asp.net/cibrax/archive/tags/.NET/default.aspx" /><category term="Web API" scheme="http://weblogs.asp.net/cibrax/archive/tags/Web+API/default.aspx" /></entry><entry><title>Message Handlers per Route in ASP.NET Web API</title><link rel="alternate" type="text/html" href="http://weblogs.asp.net/cibrax/archive/2013/02/25/message-handlers-per-route-in-asp-net-web-api.aspx" /><id>http://weblogs.asp.net/cibrax/archive/2013/02/25/message-handlers-per-route-in-asp-net-web-api.aspx</id><published>2013-02-25T14:35:34Z</published><updated>2013-02-25T14:35:34Z</updated><content type="html">&lt;p&gt;Message Handlers are one of the core components for message processing in Web API. They use an asynchronous model for processing messages, so they receive a request message and returns a Task with the corresponding response. &lt;/p&gt;  &lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;protected&lt;/span&gt; &lt;span class="kwrd"&gt;internal&lt;/span&gt; &lt;span class="kwrd"&gt;abstract&lt;/span&gt; Task&amp;lt;HttpResponseMessage&amp;gt; SendAsync(HttpRequestMessage request,
 CancellationToken cancellationToken);&lt;/pre&gt;
&lt;style type="text/css"&gt;
.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }&lt;/style&gt;

&lt;p&gt;In most cases, a message handler does something and delegates some other work to the rest of the handlers configured in the pipeline. For example, a handler for security checks the Auth Http header, and delegates the call the handlers configured out of the box by Web API, which eventually will call a controller method. The framework also provides a base class to make delegation implicit, DelegatingHandler, which receives the next handler to call as part of the constructor.&lt;/p&gt;

&lt;p&gt;The following example shows a message handler implementation for basic authentication,&lt;/p&gt;

&lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;class&lt;/span&gt; BasicAuthHandler : DelegatingHandler
{
   Func&amp;lt;&lt;span class="kwrd"&gt;string&lt;/span&gt;, &lt;span class="kwrd"&gt;string&lt;/span&gt;, IPrincipal&amp;gt; auth;

   &lt;span class="kwrd"&gt;public&lt;/span&gt; BasicAuthHandler(HttpMessageHandler innerHandler, Func&amp;lt;&lt;span class="kwrd"&gt;string&lt;/span&gt;, &lt;span class="kwrd"&gt;string&lt;/span&gt;, IPrincipal&amp;gt; auth)
       : &lt;span class="kwrd"&gt;base&lt;/span&gt;(innerHandler)
   {
       &lt;span class="kwrd"&gt;this&lt;/span&gt;.auth = auth;
    }

    &lt;span class="kwrd"&gt;protected&lt;/span&gt; &lt;span class="kwrd"&gt;override&lt;/span&gt; System.Threading.Tasks.Task&amp;lt;HttpResponseMessage&amp;gt; SendAsync(HttpRequestMessage request, &lt;/pre&gt;

&lt;pre class="csharpcode"&gt;System.Threading.CancellationToken cancellationToken)
    {
         &lt;span class="kwrd"&gt;if&lt;/span&gt; (request.Headers.Authorization != &lt;span class="kwrd"&gt;null&lt;/span&gt; &amp;amp;&amp;amp;
             !&lt;span class="kwrd"&gt;string&lt;/span&gt;.Equals(request.Headers.Authorization.Scheme, &lt;span class="str"&gt;&amp;quot;basic&amp;quot;&lt;/span&gt;, &lt;/pre&gt;

&lt;pre class="csharpcode"&gt;StringComparison.InvariantCultureIgnoreCase))
         {
              &lt;span class="kwrd"&gt;return&lt;/span&gt; &lt;span class="kwrd"&gt;base&lt;/span&gt;.SendAsync(request, cancellationToken);
          }

          &lt;span class="kwrd"&gt;if&lt;/span&gt; (request.Headers.Authorization == &lt;span class="kwrd"&gt;null&lt;/span&gt; ||
              &lt;span class="kwrd"&gt;string&lt;/span&gt;.IsNullOrWhiteSpace(request.Headers.Authorization.Scheme))
          {
              &lt;span class="kwrd"&gt;return&lt;/span&gt; ChallengeResponse(request);
           }

          var authToken = request.Headers.Authorization.Parameter;
          var decodedToken = Encoding.UTF8.GetString(Convert.FromBase64String(authToken));

          var username = decodedToken.Substring(0, decodedToken.IndexOf(&lt;span class="str"&gt;&amp;quot;:&amp;quot;&lt;/span&gt;));
          var password = decodedToken.Substring(decodedToken.IndexOf(&lt;span class="str"&gt;&amp;quot;:&amp;quot;&lt;/span&gt;) + 1);

          var principal = &lt;span class="kwrd"&gt;this&lt;/span&gt;.auth(username, password);
            
          &lt;span class="kwrd"&gt;if&lt;/span&gt; (principal == &lt;span class="kwrd"&gt;null&lt;/span&gt;)
          {
              &lt;span class="kwrd"&gt;return&lt;/span&gt; ToResponse(request, HttpStatusCode.Unauthorized, &lt;span class="str"&gt;&amp;quot;Invalid credentials&amp;quot;&lt;/span&gt;);
           }

          Thread.CurrentPrincipal = principal;
          &lt;span class="kwrd"&gt;if&lt;/span&gt; (HttpContext.Current != &lt;span class="kwrd"&gt;null&lt;/span&gt;)
             HttpContext.Current.User = principal;
                        
          &lt;span class="kwrd"&gt;return&lt;/span&gt; &lt;span class="kwrd"&gt;base&lt;/span&gt;.SendAsync(request, cancellationToken);
   }

   &lt;span class="kwrd"&gt;private&lt;/span&gt; &lt;span class="kwrd"&gt;static&lt;/span&gt; Task&amp;lt;HttpResponseMessage&amp;gt; ChallengeResponse(HttpRequestMessage request)
   {
       var tsc = &lt;span class="kwrd"&gt;new&lt;/span&gt; TaskCompletionSource&amp;lt;HttpResponseMessage&amp;gt;();

       var response = request.CreateResponse(HttpStatusCode.Unauthorized);
        response.Headers.WwwAuthenticate.Add(&lt;span class="kwrd"&gt;new&lt;/span&gt; AuthenticationHeaderValue(&lt;span class="str"&gt;&amp;quot;basic&amp;quot;&lt;/span&gt;, &lt;span class="str"&gt;&amp;quot;realm=localhost&amp;quot;&lt;/span&gt;));

       tsc.SetResult(response);

       &lt;span class="kwrd"&gt;return&lt;/span&gt; tsc.Task;
     }

     &lt;span class="kwrd"&gt;private&lt;/span&gt; &lt;span class="kwrd"&gt;static&lt;/span&gt; Task&amp;lt;HttpResponseMessage&amp;gt; ToResponse(HttpRequestMessage request, &lt;/pre&gt;

&lt;pre class="csharpcode"&gt;HttpStatusCode code, &lt;span class="kwrd"&gt;string&lt;/span&gt; message)
     {
        var tsc = &lt;span class="kwrd"&gt;new&lt;/span&gt; TaskCompletionSource&amp;lt;HttpResponseMessage&amp;gt;();

         var response = request.CreateResponse(code);
         response.ReasonPhrase = message;

         tsc.SetResult(response);

         &lt;span class="kwrd"&gt;return&lt;/span&gt; tsc.Task;
      }
 }&lt;/pre&gt;
&lt;style type="text/css"&gt;
.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }&lt;/style&gt;

&lt;p&gt;A good thing about Message Handler is that you can configure them globally or per route. In this case, if you want to enable basic authentication for some routes only, it’s a matter of configuring this handler in the routes you want to have protected.&lt;/p&gt;

&lt;pre class="csharpcode"&gt;config.Routes.MapHttpRoute(
   &lt;span class="str"&gt;&amp;quot;BasicAuth&amp;quot;&lt;/span&gt;,
   &lt;span class="str"&gt;&amp;quot;MyController&amp;quot;&lt;/span&gt;,
   &lt;span class="kwrd"&gt;new&lt;/span&gt; { controller = &lt;span class="str"&gt;&amp;quot;MyController&amp;quot;&lt;/span&gt; },
   &lt;span class="kwrd"&gt;null&lt;/span&gt;,
   &lt;span class="kwrd"&gt;new&lt;/span&gt; BasicAuthHandler(&lt;span class="kwrd"&gt;new&lt;/span&gt; HttpControllerDispatcher(config), (u, p) =&amp;gt; 
   {
      &lt;span class="kwrd"&gt;return&lt;/span&gt; &lt;span class="kwrd"&gt;new&lt;/span&gt; GenericPrincipal(&lt;span class="kwrd"&gt;new&lt;/span&gt; GenericIdentity(u, &lt;span class="kwrd"&gt;new&lt;/span&gt; &lt;span class="kwrd"&gt;string&lt;/span&gt;[] {}));
   }));&lt;/pre&gt;

&lt;p&gt;As you can see, the Inner Handler is a built-in handler provided by Web API, HttpControllerDispatcher, which does all the magic for processing the request and pass it over to the controller action. You can also inject any other dependency as part of the constructor. One thing to consider is that message handlers are singleton if you configure them this way, so make sure to inject the dependencies in the right way for avoiding memory leaks (If you have to use a repository for example, you might want to inject a factory or pass a delegate for resolving the dependencies from a DI container). &lt;/p&gt;&lt;img src="http://weblogs.asp.net/aggbug.aspx?PostID=9912317" width="1" height="1"&gt;</content><author><name>cibrax</name><uri>http://weblogs.asp.net/members/cibrax.aspx</uri></author><category term="ASP.NET" scheme="http://weblogs.asp.net/cibrax/archive/tags/ASP.NET/default.aspx" /><category term=".NET" scheme="http://weblogs.asp.net/cibrax/archive/tags/.NET/default.aspx" /><category term="Web API" scheme="http://weblogs.asp.net/cibrax/archive/tags/Web+API/default.aspx" /></entry><entry><title>Multitenant domain routing with AWS Route 53</title><link rel="alternate" type="text/html" href="http://weblogs.asp.net/cibrax/archive/2013/02/12/multitenant-domain-routing-with-aws-route-53.aspx" /><id>http://weblogs.asp.net/cibrax/archive/2013/02/12/multitenant-domain-routing-with-aws-route-53.aspx</id><published>2013-02-12T15:57:43Z</published><updated>2013-02-12T15:57:43Z</updated><content type="html">&lt;p&gt;A common requirement in SaaS applications is the ability to route requests to different tenants based on a URL routing strategy.&lt;/p&gt;  &lt;p&gt;In most cases, a domain prefix is good enough to identify tenants (e.g. mytenant.xxxxx.com). That approach typically relies on CName records for mapping the prefixes or tenants and the domain name to an URL where the application is actually hosted. Many cloud providers support the idea of mapping custom domains to their web hosted services, so this approach with CName works just fine.&lt;/p&gt;  &lt;p&gt;An evident problem is that you would require a different CName record per prefix or tenant. If you have to create those records manually, this approach simply does not scale as the number of tenants increase.&lt;/p&gt;  &lt;p&gt;An alternative is to use a wildcard CName, and route all the requests that match that wildcard to the hosted application in the cloud. For example, *.xxxxxx.com to your web application url. &lt;/p&gt;  &lt;p&gt;Many DNS servers don’t support wildcards in CName such as the ones offered by free for GoDaddy or NameCheap. However, AWS Route 53 supports wildcards and also an API to manage almost everything in the DNS tables. &lt;/p&gt;  &lt;p&gt;Configuring AWS Route 53 is relatively easy. Assuming that you already have a AWS account, you need to create first a hosted zone, which represents the association of a domain name with a set of name servers provided by Route 53. Once you specified the domain name (e.g cibrax.me), and the hosted zone is created. Route53 will show you a list of name servers you need to use. If you already own a domain in other place like GoDaddy or NameCheap, you need to go there and update the list of name servers associated to that domain. &lt;/p&gt;  &lt;p&gt;Afterwards, you need to create a resource record set, which is basically the CName record containing the wildcard or prefix you want to use. Here, you can specify the CNAme record and the mapped URL. For example, *.cibrax.me goes to &lt;a href="http://www.xxxxxxxx.com"&gt;www.xxxxxxxx.com&lt;/a&gt;. &lt;/p&gt;  &lt;p&gt;That’s all from the point of view of DNS configuration. The rest is part of the implementation of your web application. &lt;/p&gt;&lt;img src="http://weblogs.asp.net/aggbug.aspx?PostID=9865654" width="1" height="1"&gt;</content><author><name>cibrax</name><uri>http://weblogs.asp.net/members/cibrax.aspx</uri></author><category term="AWS" scheme="http://weblogs.asp.net/cibrax/archive/tags/AWS/default.aspx" /><category term="SaaS" scheme="http://weblogs.asp.net/cibrax/archive/tags/SaaS/default.aspx" /></entry><entry><title>Multitenancy in SQL Azure</title><link rel="alternate" type="text/html" href="http://weblogs.asp.net/cibrax/archive/2012/12/06/multitenancy-in-sql-azure.aspx" /><id>http://weblogs.asp.net/cibrax/archive/2012/12/06/multitenancy-in-sql-azure.aspx</id><published>2012-12-06T18:38:48Z</published><updated>2012-12-06T18:38:48Z</updated><content type="html">&lt;p&gt;If you are building a SaaS application in Windows Azure that relies on SQL Azure, it’s probably that you will need to support multiple tenants at database level.&lt;/p&gt;  &lt;p&gt;This is short overview of the different approaches you can use for support that scenario,&lt;/p&gt;  &lt;p&gt;&lt;strong&gt;A different database per tenant&lt;/strong&gt;&lt;/p&gt;  &lt;p&gt;A new database is created and assigned when a tenant is provisioned. &lt;/p&gt;  &lt;p&gt;Pros&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;Complete isolation between tenants. All the data for a tenant lives in a database only he can access. &lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;Cons&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;It’s not cost effective. SQL Azure databases are not cheap, and the minimum size for a database is 1GB.&amp;#160; You might be paying for storage that you don’t really use. &lt;/li&gt;    &lt;li&gt;A different connection pool is required per database. &lt;/li&gt;    &lt;li&gt;Updates must be replicated across all the databases &lt;/li&gt;    &lt;li&gt;You need multiple backup strategies across all the databases &lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;&lt;strong&gt;Multiple schemas in a database shared by all the tenants&lt;/strong&gt;&lt;/p&gt;  &lt;p&gt;A single database is shared among all the tenants, but every tenant is assigned to a different schema and database user.&lt;/p&gt;  &lt;p&gt;Pros&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;You only pay for a single database. &lt;/li&gt;    &lt;li&gt;Data is isolated at database level. If the credentials for one tenant is compromised, the rest of the data for the other tenants is not. &lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;Cons&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;You need to replicate all the database objects in every schema, so the number of objects can increase indefinitely. &lt;/li&gt;    &lt;li&gt;Updates must be replicated across all the schemas. &lt;/li&gt;    &lt;li&gt;The connection pool for the database must maintain a different connection per tenant (or set of credentials) &lt;/li&gt;    &lt;li&gt;A different user is required per tenant, which is stored at server level. You have to backup that user independently. &lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;&lt;strong&gt;Centralizing the database access with store procedures in a database shared by all the tenants&lt;/strong&gt;&lt;/p&gt;  &lt;p&gt;A single database is shared among all the tenants, but nobody can read the data directly from the tables. All the data operations are performed through store procedures that centralize the access to the tenant data. The store procedures contain some logic to map the database user to an specific tenant.&lt;/p&gt;  &lt;p&gt;Pros&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;You only pay for a single database. &lt;/li&gt;    &lt;li&gt;You only have a set of objects to maintain and backup. &lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;Cons&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;There is no real isolation. All the data for the different tenants is shared in the same tables. &lt;/li&gt;    &lt;li&gt;You can not use traditional ORM like EF code first for consuming the data. &lt;/li&gt;    &lt;li&gt;A different user is required per tenant, which is stored at server level. You have to backup that user independently. &lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;&lt;strong&gt;SQL Federations&lt;/strong&gt;&lt;/p&gt;  &lt;p&gt;A single database is shared among all the tenants, but a different federation is used per tenant. A federation in few words, it’s a mechanism for horizontal scaling in SQL Azure, which basically uses the idea of logical partitions to distribute data based on certain criteria. &lt;/p&gt;  &lt;p&gt;Pros&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;You only have a single database with multiple federations.&lt;/li&gt;    &lt;li&gt;You can use filtering in the connections to pick the right federation, so any ORM could be used to consume the data.&lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;Cons&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;There is no real isolation at that database level. The isolation is enforced programmatically with federations. &lt;/li&gt; &lt;/ul&gt;&lt;img src="http://weblogs.asp.net/aggbug.aspx?PostID=9525850" width="1" height="1"&gt;</content><author><name>cibrax</name><uri>http://weblogs.asp.net/members/cibrax.aspx</uri></author><category term=".NET" scheme="http://weblogs.asp.net/cibrax/archive/tags/.NET/default.aspx" /><category term="Azure" scheme="http://weblogs.asp.net/cibrax/archive/tags/Azure/default.aspx" /></entry><entry><title>Using MAC Authentication for simple Web API’s consumption</title><link rel="alternate" type="text/html" href="http://weblogs.asp.net/cibrax/archive/2012/12/05/using-mac-authentication-for-simple-web-api-s-consumption.aspx" /><id>http://weblogs.asp.net/cibrax/archive/2012/12/05/using-mac-authentication-for-simple-web-api-s-consumption.aspx</id><published>2012-12-06T02:44:20Z</published><updated>2012-12-06T02:44:20Z</updated><content type="html">&lt;p&gt;For simple scenarios of Web API consumption where identity delegation is not required, traditional http authentication schemas such as basic, certificates or digest are the most used nowadays. All these schemas rely on sending the caller credentials or some representation of it in every request message as part of the Authorization header, so they are prone to suffer phishing attacks if they are not correctly secured at transport level with https.&lt;/p&gt;  &lt;p&gt;In addition, most client applications typically authenticate two different things, the caller application and the user consuming the API on behalf of that application. For most cases, the schema is simplified by using a single set of username and password for authenticating both, making necessary to store those credentials temporally somewhere in memory. &lt;/p&gt;  &lt;p&gt;The true is that you can use two different identities, one for the user running the application, which you might authenticate just once during the first call when the application is initialized, and another identity for the application itself that you use on every call. &lt;/p&gt;  &lt;p&gt;Some cloud vendors like Windows Azure or Amazon Web Services have adopted an schema to authenticate the caller application based on a Message Authentication Code (MAC) generated with a symmetric algorithm using a key known by the two parties, the caller and the Web API. &lt;/p&gt;  &lt;p&gt;The caller must include a MAC as part of the Authorization header created from different pieces of information in the request message such as the address, the host, and some other headers. The Web API can authenticate the caller by using the key associated to it and validating the attached MAC in the request message. In that way, no credentials are sent as part of the request message, so there is no way an attacker to intercept the message and get access to those credentials. &lt;/p&gt;  &lt;p&gt;Anyways, this schema also suffers from some deficiencies that can generate attacks. For example, brute force can be still used to infer the key used for generating the MAC, and impersonate the original caller. This can be mitigated by renewing keys in a relative short period of time. This schema as any other can be complemented with transport security.&lt;/p&gt;  &lt;p&gt;Eran Rammer, one of the brains behind OAuth, has recently published an specification of a protocol based on MAC for Http authentication called Hawk. The initial version of the spec is available &lt;a href="https://github.com/hueniverse"&gt;here&lt;/a&gt;. A curious fact is that the specification per se does not exist, and the specification itself is the code that Eran initially wrote using node.js. &lt;/p&gt;  &lt;p&gt;In that implementation, you can associate a key to an user, so once the MAC has been verified on the Web API, the user can be inferred from that key. Also a timestamp is used to avoid replay attacks.&lt;/p&gt;  &lt;p&gt;As a pet project, I decided to port that code to .NET using ASP.NET Web API, which is available also in github under &lt;a href="https://github.com/pcibraro/hawknet"&gt;https://github.com/pcibraro/hawknet&lt;/a&gt;&lt;/p&gt;  &lt;p&gt;Enjoy!.&lt;/p&gt;&lt;img src="http://weblogs.asp.net/aggbug.aspx?PostID=9522292" width="1" height="1"&gt;</content><author><name>cibrax</name><uri>http://weblogs.asp.net/members/cibrax.aspx</uri></author><category term="ASP.NET" scheme="http://weblogs.asp.net/cibrax/archive/tags/ASP.NET/default.aspx" /><category term=".NET" scheme="http://weblogs.asp.net/cibrax/archive/tags/.NET/default.aspx" /><category term="Hawk" scheme="http://weblogs.asp.net/cibrax/archive/tags/Hawk/default.aspx" /></entry><entry><title>await, WhenAll, WaitAll, oh my!!</title><link rel="alternate" type="text/html" href="http://weblogs.asp.net/cibrax/archive/2012/11/15/await-whenall-waitall-oh-my.aspx" /><id>http://weblogs.asp.net/cibrax/archive/2012/11/15/await-whenall-waitall-oh-my.aspx</id><published>2012-11-15T15:21:13Z</published><updated>2012-11-15T15:21:13Z</updated><content type="html">&lt;p&gt;If you are dealing with asynchronous work in .NET, you might know that the Task class has become the main driver for wrapping asynchronous calls. Although this class was officially introduced in .NET 4.0, the programming model for consuming tasks was much more simplified in C# 5.0 in .NET 4.5 with the addition of the new async/await keywords. In a nutshell, you can use these keywords to make asynchronous calls as if they were sequential, and avoiding in that way any fork or callback in the code. The compiler takes care of the rest.&lt;/p&gt;  &lt;p&gt;I was yesterday writing some code for making multiple asynchronous calls to backend services in parallel. The code looked as follow,&lt;/p&gt;  &lt;pre&gt;&lt;pre style="font-size: 12px; font-family: consolas,&amp;#39;Courier New&amp;#39;,courier,monospace; margin: 0em; width: 100%; background-color: #ffffff"&gt;var allResults = &lt;span style="color: #0000ff"&gt;new&lt;/span&gt; List&amp;lt;Result&amp;gt;();
&lt;/pre&gt;&lt;pre style="font-size: 12px; font-family: consolas,&amp;#39;Courier New&amp;#39;,courier,monospace; margin: 0em; width: 100%; background-color: #ffffff"&gt;&lt;span style="color: #0000ff"&gt;foreach&lt;/span&gt;(var provider &lt;span style="color: #0000ff"&gt;in&lt;/span&gt; providers)
&lt;/pre&gt;&lt;pre style="font-size: 12px; font-family: consolas,&amp;#39;Courier New&amp;#39;,courier,monospace; margin: 0em; width: 100%; background-color: #ffffff"&gt;{
&lt;/pre&gt;&lt;pre style="font-size: 12px; font-family: consolas,&amp;#39;Courier New&amp;#39;,courier,monospace; margin: 0em; width: 100%; background-color: #ffffff"&gt;  var results = await provider.GetResults();
&lt;/pre&gt;&lt;pre style="font-size: 12px; font-family: consolas,&amp;#39;Courier New&amp;#39;,courier,monospace; margin: 0em; width: 100%; background-color: #ffffff"&gt;  allResults.AddRange(results);
&lt;/pre&gt;&lt;pre style="font-size: 12px; font-family: consolas,&amp;#39;Courier New&amp;#39;,courier,monospace; margin: 0em; width: 100%; background-color: #ffffff"&gt;}
&lt;/pre&gt;&lt;pre style="font-size: 12px; font-family: consolas,&amp;#39;Courier New&amp;#39;,courier,monospace; margin: 0em; width: 100%; background-color: #ffffff"&gt;&lt;/pre&gt;&lt;pre style="font-size: 12px; font-family: consolas,&amp;#39;Courier New&amp;#39;,courier,monospace; margin: 0em; width: 100%; background-color: #ffffff"&gt;&lt;span style="color: #0000ff"&gt;return&lt;/span&gt; allResults;&lt;/pre&gt;&lt;/pre&gt;

&lt;p&gt;You see, I was using the await keyword to make multiple calls in parallel. Something I did not consider was the overhead this code implied after being compiled. I started an interesting discussion with some smart folks in twitter. One of them, &lt;a href="https://twitter.com/tourismgeek"&gt;Tugberk Ugurlu&lt;/a&gt;, had the brilliant idea of actually write some code to make a performance comparison with another approach using Task.WhenAll. &lt;/p&gt;

&lt;p&gt;There are two additional methods you can use to wait for the results of multiple calls in parallel, WhenAll and WaitAll. &lt;/p&gt;

&lt;p&gt;WhenAll creates a new task and waits for results in that new task, so it does not block the calling thread. WaitAll, on the other hand, blocks the calling thread. This is the code Tugberk initially wrote, and I modified afterwards to also show the results of WaitAll.&lt;/p&gt;

&lt;pre&gt;&lt;pre style="font-size: 12px; font-family: consolas,&amp;#39;Courier New&amp;#39;,courier,monospace; margin: 0em; width: 100%; background-color: #ffffff"&gt; &lt;span style="color: #0000ff"&gt;class&lt;/span&gt; Program
&lt;/pre&gt;&lt;pre style="font-size: 12px; font-family: consolas,&amp;#39;Courier New&amp;#39;,courier,monospace; margin: 0em; width: 100%; background-color: #ffffff"&gt;    {
&lt;/pre&gt;&lt;pre style="font-size: 12px; font-family: consolas,&amp;#39;Courier New&amp;#39;,courier,monospace; margin: 0em; width: 100%; background-color: #ffffff"&gt;&lt;/pre&gt;&lt;pre style="font-size: 12px; font-family: consolas,&amp;#39;Courier New&amp;#39;,courier,monospace; margin: 0em; width: 100%; background-color: #ffffff"&gt;        &lt;span style="color: #0000ff"&gt;private&lt;/span&gt; &lt;span style="color: #0000ff"&gt;static&lt;/span&gt; Func&amp;lt;Stopwatch, Task&amp;gt;[] funcs = &lt;span style="color: #0000ff"&gt;new&lt;/span&gt; Func&amp;lt;Stopwatch, Task&amp;gt;[] { 
&lt;/pre&gt;&lt;pre style="font-size: 12px; font-family: consolas,&amp;#39;Courier New&amp;#39;,courier,monospace; margin: 0em; width: 100%; background-color: #ffffff"&gt;            async (watch) =&amp;gt; { watch.Start(); await Task.Delay(1000); 
&lt;/pre&gt;&lt;pre style="font-size: 12px; font-family: consolas,&amp;#39;Courier New&amp;#39;,courier,monospace; margin: 0em; width: 100%; background-color: #ffffff"&gt;                Console.WriteLine(&amp;quot;&lt;span style="color: #8b0000"&gt;1000 one has been completed.&lt;/span&gt;&amp;quot;); },
&lt;/pre&gt;&lt;pre style="font-size: 12px; font-family: consolas,&amp;#39;Courier New&amp;#39;,courier,monospace; margin: 0em; width: 100%; background-color: #ffffff"&gt;            async (watch) =&amp;gt; { await Task.Delay(1500); 
&lt;/pre&gt;&lt;pre style="font-size: 12px; font-family: consolas,&amp;#39;Courier New&amp;#39;,courier,monospace; margin: 0em; width: 100%; background-color: #ffffff"&gt;                Console.WriteLine(&amp;quot;&lt;span style="color: #8b0000"&gt;1500 one has been completed.&lt;/span&gt;&amp;quot;); },
&lt;/pre&gt;&lt;pre style="font-size: 12px; font-family: consolas,&amp;#39;Courier New&amp;#39;,courier,monospace; margin: 0em; width: 100%; background-color: #ffffff"&gt;            async (watch) =&amp;gt; { await Task.Delay(2000); 
&lt;/pre&gt;&lt;pre style="font-size: 12px; font-family: consolas,&amp;#39;Courier New&amp;#39;,courier,monospace; margin: 0em; width: 100%; background-color: #ffffff"&gt;                Console.WriteLine(&amp;quot;&lt;span style="color: #8b0000"&gt;2000 one has been completed.&lt;/span&gt;&amp;quot;); watch.Stop(); 
&lt;/pre&gt;&lt;pre style="font-size: 12px; font-family: consolas,&amp;#39;Courier New&amp;#39;,courier,monospace; margin: 0em; width: 100%; background-color: #ffffff"&gt;                Console.WriteLine(watch.ElapsedMilliseconds + &amp;quot;&lt;span style="color: #8b0000"&gt;ms has been elapsed.&lt;/span&gt;&amp;quot;); }
&lt;/pre&gt;&lt;pre style="font-size: 12px; font-family: consolas,&amp;#39;Courier New&amp;#39;,courier,monospace; margin: 0em; width: 100%; background-color: #ffffff"&gt;        };
&lt;/pre&gt;&lt;pre style="font-size: 12px; font-family: consolas,&amp;#39;Courier New&amp;#39;,courier,monospace; margin: 0em; width: 100%; background-color: #ffffff"&gt;&lt;/pre&gt;&lt;pre style="font-size: 12px; font-family: consolas,&amp;#39;Courier New&amp;#39;,courier,monospace; margin: 0em; width: 100%; background-color: #ffffff"&gt;        &lt;span style="color: #0000ff"&gt;static&lt;/span&gt; &lt;span style="color: #0000ff"&gt;void&lt;/span&gt; Main(&lt;span style="color: #0000ff"&gt;string&lt;/span&gt;[] args)
&lt;/pre&gt;&lt;pre style="font-size: 12px; font-family: consolas,&amp;#39;Courier New&amp;#39;,courier,monospace; margin: 0em; width: 100%; background-color: #ffffff"&gt;        {
&lt;/pre&gt;&lt;pre style="font-size: 12px; font-family: consolas,&amp;#39;Courier New&amp;#39;,courier,monospace; margin: 0em; width: 100%; background-color: #ffffff"&gt;            Console.WriteLine(&amp;quot;&lt;span style="color: #8b0000"&gt;Await in loop work starts...&lt;/span&gt;&amp;quot;);
&lt;/pre&gt;&lt;pre style="font-size: 12px; font-family: consolas,&amp;#39;Courier New&amp;#39;,courier,monospace; margin: 0em; width: 100%; background-color: #ffffff"&gt;&lt;/pre&gt;&lt;pre style="font-size: 12px; font-family: consolas,&amp;#39;Courier New&amp;#39;,courier,monospace; margin: 0em; width: 100%; background-color: #ffffff"&gt;            DoWorkAsync().ContinueWith(task =&amp;gt;
&lt;/pre&gt;&lt;pre style="font-size: 12px; font-family: consolas,&amp;#39;Courier New&amp;#39;,courier,monospace; margin: 0em; width: 100%; background-color: #ffffff"&gt;            {
&lt;/pre&gt;&lt;pre style="font-size: 12px; font-family: consolas,&amp;#39;Courier New&amp;#39;,courier,monospace; margin: 0em; width: 100%; background-color: #ffffff"&gt;                Console.WriteLine(&amp;quot;&lt;span style="color: #8b0000"&gt;Parallel work starts...&lt;/span&gt;&amp;quot;);
&lt;/pre&gt;&lt;pre style="font-size: 12px; font-family: consolas,&amp;#39;Courier New&amp;#39;,courier,monospace; margin: 0em; width: 100%; background-color: #ffffff"&gt;                DoWorkInParallelAsync().ContinueWith(t =&amp;gt;
&lt;/pre&gt;&lt;pre style="font-size: 12px; font-family: consolas,&amp;#39;Courier New&amp;#39;,courier,monospace; margin: 0em; width: 100%; background-color: #ffffff"&gt;                    {
&lt;/pre&gt;&lt;pre style="font-size: 12px; font-family: consolas,&amp;#39;Courier New&amp;#39;,courier,monospace; margin: 0em; width: 100%; background-color: #ffffff"&gt;                        Console.WriteLine(&amp;quot;&lt;span style="color: #8b0000"&gt;WaitAll work starts...&lt;/span&gt;&amp;quot;);
&lt;/pre&gt;&lt;pre style="font-size: 12px; font-family: consolas,&amp;#39;Courier New&amp;#39;,courier,monospace; margin: 0em; width: 100%; background-color: #ffffff"&gt;&lt;/pre&gt;&lt;pre style="font-size: 12px; font-family: consolas,&amp;#39;Courier New&amp;#39;,courier,monospace; margin: 0em; width: 100%; background-color: #ffffff"&gt;                        WaitForAll();
&lt;/pre&gt;&lt;pre style="font-size: 12px; font-family: consolas,&amp;#39;Courier New&amp;#39;,courier,monospace; margin: 0em; width: 100%; background-color: #ffffff"&gt;&lt;/pre&gt;&lt;pre style="font-size: 12px; font-family: consolas,&amp;#39;Courier New&amp;#39;,courier,monospace; margin: 0em; width: 100%; background-color: #ffffff"&gt;                    });
&lt;/pre&gt;&lt;pre style="font-size: 12px; font-family: consolas,&amp;#39;Courier New&amp;#39;,courier,monospace; margin: 0em; width: 100%; background-color: #ffffff"&gt;            });
&lt;/pre&gt;&lt;pre style="font-size: 12px; font-family: consolas,&amp;#39;Courier New&amp;#39;,courier,monospace; margin: 0em; width: 100%; background-color: #ffffff"&gt;            Console.ReadLine();
&lt;/pre&gt;&lt;pre style="font-size: 12px; font-family: consolas,&amp;#39;Courier New&amp;#39;,courier,monospace; margin: 0em; width: 100%; background-color: #ffffff"&gt;        }
&lt;/pre&gt;&lt;pre style="font-size: 12px; font-family: consolas,&amp;#39;Courier New&amp;#39;,courier,monospace; margin: 0em; width: 100%; background-color: #ffffff"&gt;&lt;/pre&gt;&lt;pre style="font-size: 12px; font-family: consolas,&amp;#39;Courier New&amp;#39;,courier,monospace; margin: 0em; width: 100%; background-color: #ffffff"&gt;        &lt;span style="color: #0000ff"&gt;static&lt;/span&gt; async Task DoWorkAsync()
&lt;/pre&gt;&lt;pre style="font-size: 12px; font-family: consolas,&amp;#39;Courier New&amp;#39;,courier,monospace; margin: 0em; width: 100%; background-color: #ffffff"&gt;        {
&lt;/pre&gt;&lt;pre style="font-size: 12px; font-family: consolas,&amp;#39;Courier New&amp;#39;,courier,monospace; margin: 0em; width: 100%; background-color: #ffffff"&gt;            Stopwatch watch = &lt;span style="color: #0000ff"&gt;new&lt;/span&gt; Stopwatch();
&lt;/pre&gt;&lt;pre style="font-size: 12px; font-family: consolas,&amp;#39;Courier New&amp;#39;,courier,monospace; margin: 0em; width: 100%; background-color: #ffffff"&gt;&lt;/pre&gt;&lt;pre style="font-size: 12px; font-family: consolas,&amp;#39;Courier New&amp;#39;,courier,monospace; margin: 0em; width: 100%; background-color: #ffffff"&gt;            &lt;span style="color: #0000ff"&gt;foreach&lt;/span&gt; (var func &lt;span style="color: #0000ff"&gt;in&lt;/span&gt; funcs)
&lt;/pre&gt;&lt;pre style="font-size: 12px; font-family: consolas,&amp;#39;Courier New&amp;#39;,courier,monospace; margin: 0em; width: 100%; background-color: #ffffff"&gt;            {
&lt;/pre&gt;&lt;pre style="font-size: 12px; font-family: consolas,&amp;#39;Courier New&amp;#39;,courier,monospace; margin: 0em; width: 100%; background-color: #ffffff"&gt;                await func(watch);
&lt;/pre&gt;&lt;pre style="font-size: 12px; font-family: consolas,&amp;#39;Courier New&amp;#39;,courier,monospace; margin: 0em; width: 100%; background-color: #ffffff"&gt;            }
&lt;/pre&gt;&lt;pre style="font-size: 12px; font-family: consolas,&amp;#39;Courier New&amp;#39;,courier,monospace; margin: 0em; width: 100%; background-color: #ffffff"&gt;        }
&lt;/pre&gt;&lt;pre style="font-size: 12px; font-family: consolas,&amp;#39;Courier New&amp;#39;,courier,monospace; margin: 0em; width: 100%; background-color: #ffffff"&gt;&lt;/pre&gt;&lt;pre style="font-size: 12px; font-family: consolas,&amp;#39;Courier New&amp;#39;,courier,monospace; margin: 0em; width: 100%; background-color: #ffffff"&gt;        &lt;span style="color: #0000ff"&gt;static&lt;/span&gt; async Task DoWorkInParallelAsync()
&lt;/pre&gt;&lt;pre style="font-size: 12px; font-family: consolas,&amp;#39;Courier New&amp;#39;,courier,monospace; margin: 0em; width: 100%; background-color: #ffffff"&gt;        {
&lt;/pre&gt;&lt;pre style="font-size: 12px; font-family: consolas,&amp;#39;Courier New&amp;#39;,courier,monospace; margin: 0em; width: 100%; background-color: #ffffff"&gt;            Stopwatch watch = &lt;span style="color: #0000ff"&gt;new&lt;/span&gt; Stopwatch();
&lt;/pre&gt;&lt;pre style="font-size: 12px; font-family: consolas,&amp;#39;Courier New&amp;#39;,courier,monospace; margin: 0em; width: 100%; background-color: #ffffff"&gt;            await Task.WhenAll(funcs[0](watch), funcs[1](watch), funcs[2](watch));
&lt;/pre&gt;&lt;pre style="font-size: 12px; font-family: consolas,&amp;#39;Courier New&amp;#39;,courier,monospace; margin: 0em; width: 100%; background-color: #ffffff"&gt;        }
&lt;/pre&gt;&lt;pre style="font-size: 12px; font-family: consolas,&amp;#39;Courier New&amp;#39;,courier,monospace; margin: 0em; width: 100%; background-color: #ffffff"&gt;&lt;/pre&gt;&lt;pre style="font-size: 12px; font-family: consolas,&amp;#39;Courier New&amp;#39;,courier,monospace; margin: 0em; width: 100%; background-color: #ffffff"&gt;        &lt;span style="color: #0000ff"&gt;static&lt;/span&gt; &lt;span style="color: #0000ff"&gt;void&lt;/span&gt; WaitForAll()
&lt;/pre&gt;&lt;pre style="font-size: 12px; font-family: consolas,&amp;#39;Courier New&amp;#39;,courier,monospace; margin: 0em; width: 100%; background-color: #ffffff"&gt;        {
&lt;/pre&gt;&lt;pre style="font-size: 12px; font-family: consolas,&amp;#39;Courier New&amp;#39;,courier,monospace; margin: 0em; width: 100%; background-color: #ffffff"&gt;            Stopwatch watch = &lt;span style="color: #0000ff"&gt;new&lt;/span&gt; Stopwatch();
&lt;/pre&gt;&lt;pre style="font-size: 12px; font-family: consolas,&amp;#39;Courier New&amp;#39;,courier,monospace; margin: 0em; width: 100%; background-color: #ffffff"&gt;            Task.WaitAll(funcs[0](watch), funcs[1](watch), funcs[2](watch));
&lt;/pre&gt;&lt;pre style="font-size: 12px; font-family: consolas,&amp;#39;Courier New&amp;#39;,courier,monospace; margin: 0em; width: 100%; background-color: #ffffff"&gt;        }
&lt;/pre&gt;&lt;pre style="font-size: 12px; font-family: consolas,&amp;#39;Courier New&amp;#39;,courier,monospace; margin: 0em; width: 100%; background-color: #ffffff"&gt;    }&lt;/pre&gt;&lt;/pre&gt;

&lt;p&gt;After running this code, the results were very concluding. &lt;/p&gt;

&lt;p&gt;Await in loop work starts...
  &lt;br /&gt;1000 one has been completed.

  &lt;br /&gt;1500 one has been completed.

  &lt;br /&gt;2000 one has been completed.

  &lt;br /&gt;4532ms has been elapsed.&lt;/p&gt;

&lt;p&gt;
  &lt;br /&gt;Parallel work starts...

  &lt;br /&gt;1000 one has been completed.

  &lt;br /&gt;1500 one has been completed.

  &lt;br /&gt;2000 one has been completed.

  &lt;br /&gt;2007ms has been elapsed.

  &lt;br /&gt;&lt;/p&gt;

&lt;p&gt;WaitAll work starts...
  &lt;br /&gt;1000 one has been completed.

  &lt;br /&gt;1500 one has been completed.

  &lt;br /&gt;2000 one has been completed.

  &lt;br /&gt;2009ms has been elapsed.&lt;/p&gt;

&lt;p&gt;The await keyword in a loop does not really make the calls in parallel. &lt;/p&gt;&lt;img src="http://weblogs.asp.net/aggbug.aspx?PostID=9395026" width="1" height="1"&gt;</content><author><name>cibrax</name><uri>http://weblogs.asp.net/members/cibrax.aspx</uri></author><category term=".NET" scheme="http://weblogs.asp.net/cibrax/archive/tags/.NET/default.aspx" /></entry><entry><title>Unit testing ASP.NET Web API controllers that rely on the UrlHelper</title><link rel="alternate" type="text/html" href="http://weblogs.asp.net/cibrax/archive/2012/10/10/unit-testing-asp-net-web-api-controllers-that-rely-on-the-urlhelper.aspx" /><id>http://weblogs.asp.net/cibrax/archive/2012/10/10/unit-testing-asp-net-web-api-controllers-that-rely-on-the-urlhelper.aspx</id><published>2012-10-10T18:34:33Z</published><updated>2012-10-10T18:34:33Z</updated><content type="html">&lt;p&gt;UrlHelper is the class you can use in ASP.NET Web API to automatically infer links from the routing table without hardcoding anything. For example, the following code uses the helper to infer the location url for a new resource,&lt;/p&gt;&lt;pre&gt;&lt;pre style="font-size: 12px; font-family: consolas,'Courier New',courier,monospace; margin: 0em; width: 100%; background-color: #ffffff"&gt;&lt;span style="color: #0000ff"&gt;public&lt;/span&gt; HttpResponseMessage Post(User model)
&lt;/pre&gt;&lt;pre style="font-size: 12px; font-family: consolas,'Courier New',courier,monospace; margin: 0em; width: 100%; background-color: #ffffff"&gt;{
&lt;/pre&gt;&lt;pre style="font-size: 12px; font-family: consolas,'Courier New',courier,monospace; margin: 0em; width: 100%; background-color: #ffffff"&gt;  var response = Request.CreateResponse(HttpStatusCode.Created, user);
&lt;/pre&gt;&lt;pre style="font-size: 12px; font-family: consolas,'Courier New',courier,monospace; margin: 0em; width: 100%; background-color: #ffffff"&gt;  var link = Url.Link("&lt;span style="color: #8b0000"&gt;DefaultApi&lt;/span&gt;", &lt;span style="color: #0000ff"&gt;new&lt;/span&gt; { id = id, controller = "&lt;span style="color: #8b0000"&gt;Users&lt;/span&gt;" });
&lt;/pre&gt;&lt;pre style="font-size: 12px; font-family: consolas,'Courier New',courier,monospace; margin: 0em; width: 100%; background-color: #ffffff"&gt;  response.Headers.Location = &lt;span style="color: #0000ff"&gt;new&lt;/span&gt; Uri(link);
&lt;/pre&gt;&lt;pre style="font-size: 12px; font-family: consolas,'Courier New',courier,monospace; margin: 0em; width: 100%; background-color: #ffffff"&gt;  &lt;span style="color: #0000ff"&gt;return&lt;/span&gt; response;
&lt;/pre&gt;&lt;pre style="font-size: 12px; font-family: consolas,'Courier New',courier,monospace; margin: 0em; width: 100%; background-color: #ffffff"&gt;}&lt;/pre&gt;&lt;/pre&gt;
&lt;p&gt;That code uses a previously defined route “DefaultApi”, which you might configure in the HttpConfiguration object (This is the route generated by default when you create a new Web API project). &lt;/p&gt;
&lt;p&gt;The problem with UrlHelper is that it requires from some initialization code before you can invoking it from a unit test (for testing the Post method in this example). If you don’t initialize the HttpConfiguration and Request instances associated to the controller from the unit test, it will fail miserably.&lt;/p&gt;
&lt;p&gt;After digging into the ASP.NET Web API source code a little bit, I could figure out what the requirements for using the UrlHelper are. It relies on the routing table configuration, and a few properties you need to add to the HttpRequestMessage. The following code illustrates what’s needed,&lt;/p&gt;&lt;pre&gt;&lt;pre style="font-size: 12px; font-family: consolas,'Courier New',courier,monospace; margin: 0em; width: 100%; background-color: #ffffff"&gt;var controller = &lt;span style="color: #0000ff"&gt;new&lt;/span&gt; UserController();
&lt;/pre&gt;&lt;pre style="font-size: 12px; font-family: consolas,'Courier New',courier,monospace; margin: 0em; width: 100%; background-color: #ffffff"&gt;controller.Configuration = &lt;span style="color: #0000ff"&gt;new&lt;/span&gt; HttpConfiguration();
&lt;/pre&gt;&lt;pre style="font-size: 12px; font-family: consolas,'Courier New',courier,monospace; margin: 0em; width: 100%; background-color: #ffffff"&gt;var route = controller.Configuration.Routes.MapHttpRoute(
&lt;/pre&gt;&lt;pre style="font-size: 12px; font-family: consolas,'Courier New',courier,monospace; margin: 0em; width: 100%; background-color: #ffffff"&gt;         name: "&lt;span style="color: #8b0000"&gt;DefaultApi&lt;/span&gt;",
&lt;/pre&gt;&lt;pre style="font-size: 12px; font-family: consolas,'Courier New',courier,monospace; margin: 0em; width: 100%; background-color: #ffffff"&gt;         routeTemplate: "&lt;span style="color: #8b0000"&gt;api/{controller}/{id}&lt;/span&gt;",
&lt;/pre&gt;&lt;pre style="font-size: 12px; font-family: consolas,'Courier New',courier,monospace; margin: 0em; width: 100%; background-color: #ffffff"&gt;         defaults: &lt;span style="color: #0000ff"&gt;new&lt;/span&gt; { id = RouteParameter.Optional }
&lt;/pre&gt;&lt;pre style="font-size: 12px; font-family: consolas,'Courier New',courier,monospace; margin: 0em; width: 100%; background-color: #ffffff"&gt;);
&lt;/pre&gt;&lt;pre style="font-size: 12px; font-family: consolas,'Courier New',courier,monospace; margin: 0em; width: 100%; background-color: #ffffff"&gt;&lt;/pre&gt;&lt;pre style="font-size: 12px; font-family: consolas,'Courier New',courier,monospace; margin: 0em; width: 100%; background-color: #ffffff"&gt;var routeData = &lt;span style="color: #0000ff"&gt;new&lt;/span&gt; HttpRouteData(route, 
&lt;/pre&gt;&lt;pre style="font-size: 12px; font-family: consolas,'Courier New',courier,monospace; margin: 0em; width: 100%; background-color: #ffffff"&gt;       &lt;span style="color: #0000ff"&gt;new&lt;/span&gt; HttpRouteValueDictionary 
&lt;/pre&gt;&lt;pre style="font-size: 12px; font-family: consolas,'Courier New',courier,monospace; margin: 0em; width: 100%; background-color: #ffffff"&gt;       { 
&lt;/pre&gt;&lt;pre style="font-size: 12px; font-family: consolas,'Courier New',courier,monospace; margin: 0em; width: 100%; background-color: #ffffff"&gt;          { "&lt;span style="color: #8b0000"&gt;id&lt;/span&gt;", "&lt;span style="color: #8b0000"&gt;1&lt;/span&gt;" },
&lt;/pre&gt;&lt;pre style="font-size: 12px; font-family: consolas,'Courier New',courier,monospace; margin: 0em; width: 100%; background-color: #ffffff"&gt;          { "&lt;span style="color: #8b0000"&gt;controller&lt;/span&gt;", "&lt;span style="color: #8b0000"&gt;Users&lt;/span&gt;" } 
&lt;/pre&gt;&lt;pre style="font-size: 12px; font-family: consolas,'Courier New',courier,monospace; margin: 0em; width: 100%; background-color: #ffffff"&gt;       }
&lt;/pre&gt;&lt;pre style="font-size: 12px; font-family: consolas,'Courier New',courier,monospace; margin: 0em; width: 100%; background-color: #ffffff"&gt;);
&lt;/pre&gt;&lt;pre style="font-size: 12px; font-family: consolas,'Courier New',courier,monospace; margin: 0em; width: 100%; background-color: #ffffff"&gt;&lt;/pre&gt;&lt;pre style="font-size: 12px; font-family: consolas,'Courier New',courier,monospace; margin: 0em; width: 100%; background-color: #ffffff"&gt;controller.Request = &lt;span style="color: #0000ff"&gt;new&lt;/span&gt; HttpRequestMessage(HttpMethod.Post, "&lt;span style="color: #8b0000"&gt;http://localhost:9091/&lt;/span&gt;");
&lt;/pre&gt;&lt;pre style="font-size: 12px; font-family: consolas,'Courier New',courier,monospace; margin: 0em; width: 100%; background-color: #ffffff"&gt;controller.Request.Properties.Add(HttpPropertyKeys.HttpConfigurationKey, controller.Configuration);
&lt;/pre&gt;&lt;pre style="font-size: 12px; font-family: consolas,'Courier New',courier,monospace; margin: 0em; width: 100%; background-color: #ffffff"&gt;controller.Request.Properties.Add(HttpPropertyKeys.HttpRouteDataKey, routeData);&lt;/pre&gt;&lt;/pre&gt;&lt;pre&gt;&amp;nbsp;&lt;/pre&gt;
&lt;p&gt;The HttpRouteData instance should be initialized with the route values you will use in the controller method (“id” and “controller” in this example). Once you have correctly setup all those properties, you shouldn’t have any problem to use the UrlHelper. There is no need to mock anything else.&lt;/p&gt;
&lt;p&gt;Enjoy!!.&lt;/p&gt;&lt;img src="http://weblogs.asp.net/aggbug.aspx?PostID=9085876" width="1" height="1"&gt;</content><author><name>cibrax</name><uri>http://weblogs.asp.net/members/cibrax.aspx</uri></author><category term="ASP.NET" scheme="http://weblogs.asp.net/cibrax/archive/tags/ASP.NET/default.aspx" /><category term=".NET" scheme="http://weblogs.asp.net/cibrax/archive/tags/.NET/default.aspx" /><category term="Web API" scheme="http://weblogs.asp.net/cibrax/archive/tags/Web+API/default.aspx" /></entry><entry><title>Doing unit and integration tests with the Web API HttpClient</title><link rel="alternate" type="text/html" href="http://weblogs.asp.net/cibrax/archive/2012/09/12/unit-and-integration-testing-with-the-web-api-httpclient.aspx" /><id>http://weblogs.asp.net/cibrax/archive/2012/09/12/unit-and-integration-testing-with-the-web-api-httpclient.aspx</id><published>2012-09-12T19:23:01Z</published><updated>2012-09-12T19:23:01Z</updated><content type="html">&lt;p&gt;One of the nice things about the new HttpClient in System.Net.Http is the support for mocking responses or handling requests in a http server hosted in-memory. While the first option is useful for scenarios in which we want to test our client code in isolation (unit tests for example), the second one enables more complete integration testing scenarios that could include some more components in the stack such as model binders or message handlers for example.&amp;#160;&amp;#160; &lt;/p&gt;  &lt;p&gt;The HttpClient can receive a HttpMessageHandler as argument in one of its constructors. &lt;/p&gt;  &lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;class&lt;/span&gt; HttpClient : HttpMessageInvoker
{
   &lt;span class="kwrd"&gt;public&lt;/span&gt; HttpClient();
   &lt;span class="kwrd"&gt;public&lt;/span&gt; HttpClient(HttpMessageHandler handler);
   &lt;span class="kwrd"&gt;public&lt;/span&gt; HttpClient(HttpMessageHandler handler, &lt;span class="kwrd"&gt;bool&lt;/span&gt; disposeHandler);&lt;/pre&gt;
&lt;style type="text/css"&gt;
.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }&lt;/style&gt;

&lt;p&gt;For the first scenario, you can create a new HttpMessageHandler that fakes the response, which you can use in your unit test. The only requirement is that you somehow inject an HttpClient with this custom handler in the client code.&lt;/p&gt;

&lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;class&lt;/span&gt; FakeHttpMessageHandler : HttpMessageHandler
{
  HttpResponseMessage response;

  &lt;span class="kwrd"&gt;public&lt;/span&gt; FakeHttpMessageHandler(HttpResponseMessage response)
  {
       &lt;span class="kwrd"&gt;this&lt;/span&gt;.response = response;
   }

   &lt;span class="kwrd"&gt;protected&lt;/span&gt; &lt;span class="kwrd"&gt;override&lt;/span&gt; Task&amp;lt;HttpResponseMessage&amp;gt; SendAsync(HttpRequestMessage request, 
System.Threading.CancellationToken cancellationToken)
   {
      var tcs = &lt;span class="kwrd"&gt;new&lt;/span&gt; TaskCompletionSource&amp;lt;HttpResponseMessage&amp;gt;();
            
      tcs.SetResult(response);

      &lt;span class="kwrd"&gt;return&lt;/span&gt; tcs.Task;
    }
}&lt;/pre&gt;
&lt;style type="text/css"&gt;
.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }&lt;/style&gt;

&lt;p&gt;In an unit test, you can do something like this.&lt;/p&gt;

&lt;pre class="csharpcode"&gt;var fakeResponse = &lt;span class="kwrd"&gt;new&lt;/span&gt; HttpResponse();
var fakeHandler = &lt;span class="kwrd"&gt;new&lt;/span&gt; FakeHttpMessageHandler(fakeResponse);
var httpClient = &lt;span class="kwrd"&gt;new&lt;/span&gt; HttpClient(fakeHandler);

var customerService = &lt;span class="kwrd"&gt;new&lt;/span&gt; CustomerService(httpClient);

&lt;span class="rem"&gt;// Do something&lt;/span&gt;

// Asserts&lt;/pre&gt;
&lt;style type="text/css"&gt;
.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }&lt;/style&gt;

&lt;p&gt;CustomerService in this case is the class under test, and the one that receives an HttpClient initialized with our fake handler. &lt;/p&gt;

&lt;p&gt;For the second scenario in integration tests, there is a In-Memory host “System.Web.Http.HttpServer” that also derives from HttpMessageHandler and you can use with a HttpClient instance in your test. This has been discussed already in these two great posts from &lt;a href="http://pfelix.wordpress.com/2012/03/05/asp-net-web-api-in-memory-hosting/"&gt;Pedro&lt;/a&gt; and &lt;a href="http://www.strathweb.com/2012/06/asp-net-web-api-integration-testing-with-in-memory-hosting/"&gt;Filip&lt;/a&gt;.&amp;#160; &lt;/p&gt;&lt;img src="http://weblogs.asp.net/aggbug.aspx?PostID=8914578" width="1" height="1"&gt;</content><author><name>cibrax</name><uri>http://weblogs.asp.net/members/cibrax.aspx</uri></author><category term="ASP.NET" scheme="http://weblogs.asp.net/cibrax/archive/tags/ASP.NET/default.aspx" /><category term=".NET" scheme="http://weblogs.asp.net/cibrax/archive/tags/.NET/default.aspx" /><category term="Web API" scheme="http://weblogs.asp.net/cibrax/archive/tags/Web+API/default.aspx" /></entry><entry><title>Consuming the Amazon S3 service from a Win8 Metro Application</title><link rel="alternate" type="text/html" href="http://weblogs.asp.net/cibrax/archive/2012/09/10/consuming-the-amazon-s3-service-from-a-win8-metro-application.aspx" /><id>http://weblogs.asp.net/cibrax/archive/2012/09/10/consuming-the-amazon-s3-service-from-a-win8-metro-application.aspx</id><published>2012-09-10T15:58:27Z</published><updated>2012-09-10T15:58:27Z</updated><content type="html">&lt;p&gt;As many of the existing Http APIs for Cloud Services, AWS also provides a set of different platform SDKs for hiding many of complexities present in the APIs. While there is a platform SDK for .NET, which is open source and available in C#, that SDK does not work in Win8 Metro Applications for the changes introduced in WinRT. WinRT offers a complete different set of APIs for doing I/O operations such as doing http calls or using cryptography for signing or encrypting data, two aspects that are absolutely necessary for consuming AWS. All the I/O APIs available as part of WinRT are asynchronous, and uses the TPL model for .NET applications (HTML and JavaScript Metro applications use a model based in promises, which is similar concept).&amp;#160; &lt;/p&gt;  &lt;p&gt;In the case of S3, the http Authorization header is used for two purposes, authenticating clients and make sure the messages were not altered while they were in transit. For doing that, it uses a signature or hash of the message content and some of the headers using a symmetric key (That's just one of the available mechanisms). Windows Azure for example also uses the same mechanism in many of its APIs.&lt;/p&gt;  &lt;p&gt;There are three challenges that any developer working for first time in Metro will have to face to consume S3, the new WinRT APIs, the asynchronous nature of them and the complexity introduced for generating the Authorization header. Having said that, I decided to write this post with some of the gotchas I found myself trying to consume this Amazon service.&lt;/p&gt;  &lt;p&gt;1. Generating the signature for the Authorization header&lt;/p&gt;  &lt;p&gt;All the cryptography APIs in WinRT are available under Windows.Security.Cryptography namespace. Many of operations available in these APIs uses the concept of buffers (IBuffer) for representing a chunk of binary data. As you will see in the example below, these buffers are mainly generated with the use of static methods in a WinRT class CryptographicBuffer available as part of the namespace previously mentioned.&lt;/p&gt;  &lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;private&lt;/span&gt; &lt;span class="kwrd"&gt;string&lt;/span&gt; DeriveAuthToken(&lt;span class="kwrd"&gt;string&lt;/span&gt; resource, &lt;span class="kwrd"&gt;string&lt;/span&gt; httpMethod, &lt;span class="kwrd"&gt;string&lt;/span&gt; timestamp)
{
   var stringToSign = &lt;span class="kwrd"&gt;string&lt;/span&gt;.Format(&lt;span class="str"&gt;&amp;quot;{0}\n&amp;quot;&lt;/span&gt; +
      &lt;span class="str"&gt;&amp;quot;\n&amp;quot;&lt;/span&gt; +
      &lt;span class="str"&gt;&amp;quot;\n&amp;quot;&lt;/span&gt; +
      &lt;span class="str"&gt;&amp;quot;\n&amp;quot;&lt;/span&gt; +
      &lt;span class="str"&gt;&amp;quot;x-amz-date:{1}\n&amp;quot;&lt;/span&gt; +
      &lt;span class="str"&gt;&amp;quot;/{2}/&amp;quot;&lt;/span&gt;, httpMethod, timestamp, resource);

   var algorithm = MacAlgorithmProvider.OpenAlgorithm(&lt;span class="str"&gt;&amp;quot;HMAC_SHA1&amp;quot;&lt;/span&gt;);

   var keyMaterial = CryptographicBuffer.CreateFromByteArray(Encoding.UTF8.GetBytes(&lt;span class="kwrd"&gt;this&lt;/span&gt;.secret));

   var hmacKey = algorithm.CreateKey(keyMaterial);

   var signature = CryptographicEngine.Sign(
                hmacKey,
                CryptographicBuffer.CreateFromByteArray(Encoding.UTF8.GetBytes(stringToSign))
            );

   &lt;span class="kwrd"&gt;return&lt;/span&gt; CryptographicBuffer.EncodeToBase64String(signature);
}&lt;/pre&gt;
&lt;style type="text/css"&gt;

.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }&lt;/style&gt;

&lt;p&gt;The algorithm that determines the information or content you need to use for generating the signature is very well described as part of the AWS documentation. In this case, this method is generating a signature required for creating a new bucket. A HmacSha1 hash is computed using a secret or symetric key provided by AWS in the management console. 
  &lt;br /&gt;

  &lt;br /&gt;2. Sending an Http Request to the S3 service&lt;/p&gt;

&lt;p&gt;WinRT also ships with the System.Net.Http.HttpClient that was first introduced some months ago with ASP.NET Web API. This client provides a rich interface on top the traditional WebHttpRequest class, and also solves some of limitations found in this last one. There are a few things that don't work with a raw WebHttpRequest such as setting the Host header, which is something absolutely required for consuming S3. Also, HttpClient is more friendly for doing unit tests, as it receives a HttpMessageHandler as part of the constructor that can fake to emulate a real http call. This is how the code for consuming the service with HttpClient looks like,&lt;/p&gt;

&lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;public&lt;/span&gt; async Task&amp;lt;S3Response&amp;gt; CreateBucket(&lt;span class="kwrd"&gt;string&lt;/span&gt; name, &lt;span class="kwrd"&gt;string&lt;/span&gt; region = &lt;span class="kwrd"&gt;null&lt;/span&gt;, &lt;span class="kwrd"&gt;params&lt;/span&gt; &lt;span class="kwrd"&gt;string&lt;/span&gt;[] acl)
{
   var timestamp = &lt;span class="kwrd"&gt;string&lt;/span&gt;.Format(&lt;span class="str"&gt;&amp;quot;{0:r}&amp;quot;&lt;/span&gt;, DateTime.UtcNow);

    var auth = DeriveAuthToken(name, &lt;span class="str"&gt;&amp;quot;PUT&amp;quot;&lt;/span&gt;, timestamp);

    var request = &lt;span class="kwrd"&gt;new&lt;/span&gt; HttpRequestMessage(HttpMethod.Put, &lt;span class="str"&gt;&amp;quot;http://s3.amazonaws.com/&amp;quot;&lt;/span&gt;);
    request.Headers.Host = &lt;span class="kwrd"&gt;string&lt;/span&gt;.Format(&lt;span class="str"&gt;&amp;quot;{0}.s3.amazonaws.com&amp;quot;&lt;/span&gt;, name);
    request.Headers.TryAddWithoutValidation(&lt;span class="str"&gt;&amp;quot;Authorization&amp;quot;&lt;/span&gt;, &lt;span class="str"&gt;&amp;quot;AWS &amp;quot;&lt;/span&gt; + &lt;span class="kwrd"&gt;this&lt;/span&gt;.key + &lt;span class="str"&gt;&amp;quot;:&amp;quot;&lt;/span&gt; + auth);
    request.Headers.Add(&lt;span class="str"&gt;&amp;quot;x-amz-date&amp;quot;&lt;/span&gt;, timestamp);

    var client = &lt;span class="kwrd"&gt;new&lt;/span&gt; HttpClient();
    var response = await client.SendAsync(request);

    &lt;span class="kwrd"&gt;return&lt;/span&gt; &lt;span class="kwrd"&gt;new&lt;/span&gt; S3Response
    {
         Succeed = response.StatusCode == HttpStatusCode.OK,
         Message = (response.Content != &lt;span class="kwrd"&gt;null&lt;/span&gt;) ? 
            await response.Content.ReadAsStringAsync() : &lt;span class="kwrd"&gt;null&lt;/span&gt;
     };
 }&lt;/pre&gt;
&lt;style type="text/css"&gt;

.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }&lt;/style&gt;

&lt;p&gt;You will notice a few additional things in this code. By default, HttpClient validates the values for some well-know headers, and Authorization is one of them. It won't allow you to set a value with &amp;quot;:&amp;quot; on it, which is something that S3 expects. However, that's not a problem at all, as you can skip the validation by using the TryAddWithoutValidation method. 
  &lt;br /&gt;Also, the code is heavily relying on the new async and await keywords to transform all the asynchronous calls into synchronous ones. In case you would want to unit test this code and faking the call to the real S3 service, you should have to modify it to inject a custom HttpMessageHandler into the HttpClient. The following implementation illustrates this concept,&lt;/p&gt;

&lt;p&gt;In case you would want to unit test this code and faking the call to the real S3 service, you should have to modify it to inject a custom HttpMessageHandler into the HttpClient. The following implementation illustrates this concept,&lt;/p&gt;

&lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;class&lt;/span&gt; FakeHttpMessageHandler : HttpMessageHandler
{
  HttpResponseMessage response;

  &lt;span class="kwrd"&gt;public&lt;/span&gt; FakeHttpMessageHandler(HttpResponseMessage response)
  {
       &lt;span class="kwrd"&gt;this&lt;/span&gt;.response = response;
   }

   &lt;span class="kwrd"&gt;protected&lt;/span&gt; &lt;span class="kwrd"&gt;override&lt;/span&gt; Task&amp;lt;HttpResponseMessage&amp;gt; SendAsync(HttpRequestMessage request, System.Threading.CancellationToken cancellationToken)
   {
      var tcs = &lt;span class="kwrd"&gt;new&lt;/span&gt; TaskCompletionSource&amp;lt;HttpResponseMessage&amp;gt;();
            
      tcs.SetResult(response);

      &lt;span class="kwrd"&gt;return&lt;/span&gt; tcs.Task;
    }
}&lt;/pre&gt;
&lt;style type="text/css"&gt;

.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }&lt;/style&gt;

&lt;p&gt;You can use this handler for injecting any response while you are unit testing the code. 
  &lt;/p&gt;&lt;img src="http://weblogs.asp.net/aggbug.aspx?PostID=8906801" width="1" height="1"&gt;</content><author><name>cibrax</name><uri>http://weblogs.asp.net/members/cibrax.aspx</uri></author><category term=".NET" scheme="http://weblogs.asp.net/cibrax/archive/tags/.NET/default.aspx" /><category term="AWS" scheme="http://weblogs.asp.net/cibrax/archive/tags/AWS/default.aspx" /><category term="Win8" scheme="http://weblogs.asp.net/cibrax/archive/tags/Win8/default.aspx" /></entry><entry><title>Binding form data in ASP.NET Web API</title><link rel="alternate" type="text/html" href="http://weblogs.asp.net/cibrax/archive/2012/08/10/binding-form-data-in-asp-net-web-api.aspx" /><id>http://weblogs.asp.net/cibrax/archive/2012/08/10/binding-form-data-in-asp-net-web-api.aspx</id><published>2012-08-10T15:34:00Z</published><updated>2012-08-10T15:34:00Z</updated><content type="html">&lt;p&gt;One scenario that is very common in ASP.NET MVC is to bind form data (data posted with the media type application/x-www-form-urlencoded)&amp;nbsp; to individual parameters or a form collection in a controller&amp;nbsp;action. However, that scenario does not work quite the same in ASP.NET Web API as the body content is treated a forward-only stream that can only be read once.&amp;nbsp; &lt;/p&gt;  &lt;p&gt;If you define an action with multiple simple type arguments such as the one shown bellow, the model binding runtime will try to map those by default from the request URI (query string or route data).&amp;nbsp; &lt;/p&gt;  &lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;void&lt;/span&gt; Post(&lt;span class="kwrd"&gt;int&lt;/span&gt; id, &lt;span class="kwrd"&gt;string&lt;/span&gt; &lt;span class="kwrd"&gt;value&lt;/span&gt;)
{
}&lt;/pre&gt;
&lt;style type="text/css"&gt;
.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }&lt;/style&gt;

&lt;p&gt;That data never comes from the body content unless you decorate the argument with the [FromBody] attribute. However, only one argument in the action can be decorated with this attribute, and you get an exception when you try to decorate more than one. Nevertheless, the desired effect is far from what you would expect. &lt;/p&gt;

&lt;p&gt;If you define an action as follow,&lt;/p&gt;

&lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;void&lt;/span&gt; Post([FromBody]&lt;span class="kwrd"&gt;int&lt;/span&gt; id)
{
}&lt;/pre&gt;
&lt;style type="text/css"&gt;
.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }&lt;/style&gt;

&lt;p&gt;And you POST a form with the following data,&lt;/p&gt;

&lt;p&gt;&lt;a href="http://localhost:64561/api/values" mce_href="http://localhost:64561/api/values"&gt;http://localhost:64561/api/values&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;METHOD: POST&lt;/p&gt;

&lt;p&gt;CONTENT-TYPE: application/x-www-form-urlencoded&lt;/p&gt;

&lt;p&gt;BODY: id=4&lt;/p&gt;

&lt;p&gt;Nothing will be mapped. It does not matter you defined a single parameter with the same as the one posted in the body. &lt;/p&gt;

&lt;p&gt;If you really want to have a single type argument mapped to the body content, you have to POST a message with the following content&lt;/p&gt;

&lt;p&gt;&lt;a href="http://localhost:64561/api/values" mce_href="http://localhost:64561/api/values"&gt;http://localhost:64561/api/values&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;METHOD: POST&lt;/p&gt;

&lt;p&gt;CONTENT-TYPE: application/x-www-form-urlencoded&lt;/p&gt;

&lt;p&gt;BODY: =4&lt;/p&gt;

&lt;p&gt;As you can see, no key defined so the whole is mapped to our argument in the action. That’s the default behavior for single types. If you want to change that behavior, the framework is completely extensible and you can replace the whole model binding infrastructure included out of the box for one that you find more useful as it is explained &lt;a href="http://blogs.msdn.com/b/jmstall/archive/2012/04/18/mvc-style-parameter-binding-for-webapi.aspx" mce_href="http://blogs.msdn.com/b/jmstall/archive/2012/04/18/mvc-style-parameter-binding-for-webapi.aspx"&gt;here&lt;/a&gt; by Mike Stalls (which shows how you can replicate the same model used by ASP.NET MVC).&lt;/p&gt;

&lt;p&gt;For complex types, the framework includes two MediaTypeFormatter implementations. The first one is FormUrlEncodedMediaTypeFormatter, which knows how to map every key/value in the form data to a FormDataCollection or a JTokenType (a dynamic type for expressing JSON available as part of the Json.NET library). These two are useful when you want to get access to all the values in form in a generic manner. You define for example a controller that receives a FormDataCollection instance like this,&lt;/p&gt;

&lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;void&lt;/span&gt; Post(FormDataCollection form)
{
}&lt;/pre&gt;
&lt;style type="text/css"&gt;
.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }&lt;/style&gt;

&lt;p&gt;The second one is JQueryMvcFormUrlEncodedFormatter, which derives from the first one and knows how to map the form data to a concrete type representing a model. For example, a model defined as follow will match a body content with the keys “Id” and “Value”&lt;/p&gt;

&lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;class&lt;/span&gt; MyModel
{
   &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;int&lt;/span&gt; Id { get; set; }
   &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;string&lt;/span&gt; Value { get; set; }
}&lt;/pre&gt;

&lt;p&gt;Therefore, your controller action can either receive a generic form collection (or a JTokenType) or a complex model type as any of these two will handle the deserialization of the body content type into the expected model. &lt;/p&gt;&lt;img src="http://weblogs.asp.net/aggbug.aspx?PostID=8831937" width="1" height="1"&gt;</content><author><name>cibrax</name><uri>http://weblogs.asp.net/members/cibrax.aspx</uri></author><category term="ASP.NET" scheme="http://weblogs.asp.net/cibrax/archive/tags/ASP.NET/default.aspx" /><category term=".NET" scheme="http://weblogs.asp.net/cibrax/archive/tags/.NET/default.aspx" /><category term="Web API" scheme="http://weblogs.asp.net/cibrax/archive/tags/Web+API/default.aspx" /></entry><entry><title>Implementing synchronous MediaTypeFormatters in ASP.NET Web API</title><link rel="alternate" type="text/html" href="http://weblogs.asp.net/cibrax/archive/2012/07/09/implementing-synchronous-mediatypeformatters-in-asp-net-web-api.aspx" /><id>http://weblogs.asp.net/cibrax/archive/2012/07/09/implementing-synchronous-mediatypeformatters-in-asp-net-web-api.aspx</id><published>2012-07-09T15:42:51Z</published><updated>2012-07-09T15:42:51Z</updated><content type="html">&lt;p&gt;One of main characteristics of MediaTypeFormatter’s in ASP.NET Web API is that they leverage the Task Parallel Library (TPL) for reading or writing an model into an stream. When you derive your class from the base class MediaTypeFormatter, you have to either implement the WriteToStreamAsync or ReadFromStreamAsync methods for writing or reading a model from a stream respectively.&lt;/p&gt;  &lt;p&gt;These two methods return a Task, which internally does all the serialization work, as it is illustrated bellow. &lt;/p&gt;  &lt;div class="csharpcode"&gt;   &lt;div class="csharpcode"&gt;     &lt;pre class="alt"&gt;&lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;abstract&lt;/span&gt; &lt;span class="kwrd"&gt;class&lt;/span&gt; MediaTypeFormatter&lt;/pre&gt;

    &lt;pre&gt;{&lt;/pre&gt;

    &lt;pre class="alt"&gt;  &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;virtual&lt;/span&gt; Task WriteToStreamAsync(Type type, &lt;span class="kwrd"&gt;object&lt;/span&gt; &lt;span class="kwrd"&gt;value&lt;/span&gt;, &lt;/pre&gt;

    &lt;pre&gt;     Stream writeStream, HttpContent content, TransportContext transportContext);&lt;/pre&gt;

    &lt;pre class="alt"&gt;  &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;virtual&lt;/span&gt; Task&amp;lt;&lt;span class="kwrd"&gt;object&lt;/span&gt;&amp;gt; ReadFromStreamAsync(Type type, Stream readStream, &lt;/pre&gt;

    &lt;pre&gt;     HttpContent content, IFormatterLogger formatterLogger);&lt;/pre&gt;

    &lt;pre class="alt"&gt;}&lt;/pre&gt;

    &lt;pre&gt;&amp;#160;&lt;/pre&gt;
  &lt;/div&gt;
  &lt;style type="text/css"&gt;


.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }&lt;/style&gt;&lt;/div&gt;
&lt;style type="text/css"&gt;


.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }&lt;/style&gt;

&lt;p&gt;However, most of the times, serialization is a safe operation that can be done synchronously. In fact, many of the serializer classes you will find in the .NET framework only provide sync methods. So the question is, how you can transform that synchronous work into a Task ?. &lt;/p&gt;

&lt;p&gt;Creating a new task using the method Task.Factory.StartNew for doing all the serialization work would be probably the typical answer. That would work, as a new task is going to be scheduled. However, that might involve some unnecessary context switches, which are out of our control and might be affect performance on server code specially.&amp;#160;&amp;#160; &lt;/p&gt;

&lt;p&gt;If you take a look at the source code of the MediaTypeFormatters shipped as part of the framework, you will notice that they actually using another pattern, which uses a TaskCompletionSource class. &lt;/p&gt;

&lt;div class="csharpcode"&gt;
  &lt;pre class="alt"&gt;&lt;span class="kwrd"&gt;public&lt;/span&gt; Task WriteToStreamAsync(Type type, &lt;span class="kwrd"&gt;object&lt;/span&gt; &lt;span class="kwrd"&gt;value&lt;/span&gt;, Stream writeStream, &lt;/pre&gt;

  &lt;pre&gt;HttpContent content, TransportContext transportContext)&lt;/pre&gt;

  &lt;pre class="alt"&gt;{&lt;/pre&gt;

  &lt;pre&gt;&amp;#160;&lt;/pre&gt;

  &lt;pre class="alt"&gt;  var tsc = &lt;span class="kwrd"&gt;new&lt;/span&gt; TaskCompletionSource&amp;lt;AsyncVoid&amp;gt;();&lt;/pre&gt;

  &lt;pre&gt;  tsc.SetResult(&lt;span class="kwrd"&gt;default&lt;/span&gt;(AsyncVoid));&lt;/pre&gt;

  &lt;pre class="alt"&gt;&amp;#160;&lt;/pre&gt;

  &lt;pre&gt;  &lt;span class="rem"&gt;//Do all the serialization work here synchronously&lt;/span&gt;&lt;/pre&gt;

  &lt;pre class="alt"&gt;&amp;#160;&lt;/pre&gt;

  &lt;pre&gt;  &lt;span class="kwrd"&gt;return&lt;/span&gt; tsc.Task;&lt;/pre&gt;

  &lt;pre class="alt"&gt;}&lt;/pre&gt;

  &lt;pre&gt;&amp;#160;&lt;/pre&gt;

  &lt;pre class="alt"&gt;&lt;span class="rem"&gt;/// &amp;lt;summary&amp;gt;&lt;/span&gt;&lt;/pre&gt;

  &lt;pre&gt;&lt;span class="rem"&gt;/// Used as the T in a &amp;quot;conversion&amp;quot; of a Task into a Task{T}&lt;/span&gt;&lt;/pre&gt;

  &lt;pre class="alt"&gt;&lt;span class="rem"&gt;/// &amp;lt;/summary&amp;gt;&lt;/span&gt;&lt;/pre&gt;

  &lt;pre&gt;&lt;span class="kwrd"&gt;private&lt;/span&gt; &lt;span class="kwrd"&gt;struct&lt;/span&gt; AsyncVoid&lt;/pre&gt;

  &lt;pre class="alt"&gt;{&lt;/pre&gt;

  &lt;pre&gt;}&lt;/pre&gt;
&lt;/div&gt;
&lt;style type="text/css"&gt;


.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }&lt;/style&gt;

&lt;p&gt;They are basically doing all the serialization work synchronously and using a TaskCompletionSource for returning a task already done. &lt;/p&gt;

&lt;p&gt;To conclude this post, this is another approach you might want to consider when using serializers that are not compatible with an async model.&lt;/p&gt;

&lt;p&gt;&lt;font style="background-color: #ffff00"&gt;&lt;strong&gt;&lt;font style="style"&gt;Update:&lt;/font&gt;&lt;/strong&gt; Henrik Nielsen from the ASP.NET team pointed out the existence of a built-in media type formatter for writing sync formatters. BufferedMediaTypeFormatter &lt;/font&gt;&lt;a href="http://t.co/FxOfeI5x"&gt;&lt;font style="background-color: #ffff00"&gt;http://t.co/FxOfeI5x&lt;/font&gt;&lt;/a&gt;&lt;/p&gt;&lt;img src="http://weblogs.asp.net/aggbug.aspx?PostID=8715404" width="1" height="1"&gt;</content><author><name>cibrax</name><uri>http://weblogs.asp.net/members/cibrax.aspx</uri></author><category term="ASP.NET" scheme="http://weblogs.asp.net/cibrax/archive/tags/ASP.NET/default.aspx" /><category term=".NET" scheme="http://weblogs.asp.net/cibrax/archive/tags/.NET/default.aspx" /><category term="Web API" scheme="http://weblogs.asp.net/cibrax/archive/tags/Web+API/default.aspx" /></entry><entry><title>HTML 5 para dispositivos mobiles – Proyecto Liike</title><link rel="alternate" type="text/html" href="http://weblogs.asp.net/cibrax/archive/2012/06/06/html-5-para-dispositivos-mobiles-proyecto-liike.aspx" /><id>http://weblogs.asp.net/cibrax/archive/2012/06/06/html-5-para-dispositivos-mobiles-proyecto-liike.aspx</id><published>2012-06-06T18:50:37Z</published><updated>2012-06-06T18:50:37Z</updated><content type="html">&lt;p&gt;La serie de videos que grabe con Miguel Angel Saenz y Ariel Schapiro de Microsoft Argentina acerca del proyecto “Liike” de Patterns &amp;amp; Practices para desarrollos de aplicaciones mobiles con HTML 5 ha sido publicada en channel9. &lt;/p&gt;  &lt;p&gt;Les dejo la lista de videos para que los puedan ir viendo y conociendo un poco mas con este proyecto mas que interesante.&lt;/p&gt;  &lt;p&gt;&lt;a href="http://channel9.msdn.com/posts/1Serie-HTML5-para-dispositivos-mviles-Proyecto-Liike-parte-1-introduccin"&gt;http://channel9.msdn.com/posts/1Serie-HTML5-para-dispositivos-mviles-Proyecto-Liike-parte-1-introduccin&lt;/a&gt;     &lt;br /&gt;&lt;a href="http://channel9.msdn.com/posts/2Serie-HTML5-para-dispositivos-mviles-Proyecto-Liike-parte-2-overview-de-aplicacin-Mileage-Stats"&gt;http://channel9.msdn.com/posts/2Serie-HTML5-para-dispositivos-mviles-Proyecto-Liike-parte-2-overview-de-aplicacin-Mileage-Stats&lt;/a&gt;     &lt;br /&gt;&lt;a href="http://channel9.msdn.com/posts/3Serie-HTML5-para-dispositivos-mviles-Proyecto-Liike-parte-3-determinacin-de-vista-en-html-a-mostrar"&gt;http://channel9.msdn.com/posts/3Serie-HTML5-para-dispositivos-mviles-Proyecto-Liike-parte-3-determinacin-de-vista-en-html-a-mostrar&lt;/a&gt;     &lt;br /&gt;&lt;a href="http://channel9.msdn.com/posts/4Serie-HTML5-para-dispositivos-mviles-Proyecto-Liike-parte-4-Single-Page-application"&gt;http://channel9.msdn.com/posts/4Serie-HTML5-para-dispositivos-mviles-Proyecto-Liike-parte-4-Single-Page-application&lt;/a&gt;     &lt;br /&gt;&lt;a href="http://channel9.msdn.com/posts/5Serie-HTML5-para-dispositivos-mviles-Proyecto-Liike-parte-5-nuevos-controles-HTML5"&gt;http://channel9.msdn.com/posts/5Serie-HTML5-para-dispositivos-mviles-Proyecto-Liike-parte-5-nuevos-controles-HTML5&lt;/a&gt;-     &lt;br /&gt;&lt;a href="http://channel9.msdn.com/posts/6Serie-HTML5-para-dispositivos-mviles-Proyecto-Liike-parte-6-Botn-Switch-to-Desktop-Site"&gt;http://channel9.msdn.com/posts/6Serie-HTML5-para-dispositivos-mviles-Proyecto-Liike-parte-6-Botn-Switch-to-Desktop-Site&lt;/a&gt;     &lt;br /&gt;&lt;a href="http://channel9.msdn.com/posts/7Serie-HTML5-para-dispositivos-mviles-Proyecto-Liike-parte-7-Testing-de-aplicaciones-mviles-en-HTML5"&gt;http://channel9.msdn.com/posts/7Serie-HTML5-para-dispositivos-mviles-Proyecto-Liike-parte-7-Testing-de-aplicaciones-mviles-en-HTML5&lt;/a&gt;&lt;/p&gt;&lt;img src="http://weblogs.asp.net/aggbug.aspx?PostID=8577033" width="1" height="1"&gt;</content><author><name>cibrax</name><uri>http://weblogs.asp.net/members/cibrax.aspx</uri></author></entry><entry><title>Apache Cordova. A new alternative for developing native apps in Win Phone 7</title><link rel="alternate" type="text/html" href="http://weblogs.asp.net/cibrax/archive/2012/05/11/apache-cordova-a-new-alternative-for-developing-native-apps-in-win-phone-7.aspx" /><id>http://weblogs.asp.net/cibrax/archive/2012/05/11/apache-cordova-a-new-alternative-for-developing-native-apps-in-win-phone-7.aspx</id><published>2012-05-11T15:23:22Z</published><updated>2012-05-11T15:23:22Z</updated><content type="html">&lt;p&gt;&lt;a href="http://incubator.apache.org/cordova/"&gt;Apache Cordova&lt;/a&gt; is one of those projects that recently caught my attention for developing applications in mobile. This project previously known as PhoneGap was donated by Adobe to the Apache Foundation to be part of a new and attractive open source alternative for developing mobile applications.&amp;#160; If you haven’t heard of it before, it basically provides the required infrastructure to run native applications in different mobile platforms such as IOS, Android, and Windows Phone 7 using an hybrid approach with an embedded browser. There is a thin native layer that provides access to different native features in phone through an standard object model in JavaScript, so the developers can write their applications using HTML 5 and have access to different features through that model. Therefore, the two most important components in this project are the native layer and the JavaScript component model, which are supported across the different platforms. &lt;/p&gt;  &lt;p&gt;The Microsoft Interoperability team collaborated as part of the project to support Win7 phone as another available platform, which &lt;a href="http://blogs.msdn.com/b/interoperability/archive/2011/12/16/full-support-for-phonegap-on-windows-phone-is-now-complete.aspx"&gt;was announced by Abu Obeida&lt;/a&gt; in December last year. Another major announcement these days was the support for a &lt;a href="http://blogs.msdn.com/b/interoperability/archive/2012/04/26/more-news-from-ms-open-tech-announcing-the-open-source-metro-style-theme.aspx"&gt;Metro theme in JQuery Mobile&lt;/a&gt;, which gives the ability to give applications written in HTML 5 for this platform the same look and feel as a native applications.&lt;/p&gt;  &lt;p&gt;If you want to know more about the platform, there is an excellent introductory article written by Colin Eberhardt for the MSDN Magazine, &lt;a href="http://msdn.microsoft.com/en-us/magazine/hh975345.aspx"&gt;“Develop HTML Windows Phone Apps with Apache Cordova”&lt;/a&gt;&lt;/p&gt;  &lt;p&gt;One the things I noticed in the project, is that there is available a project template in Visual Studio for creating the initial application. However, you need to manually deploy that template in the right folder to make it available in Visual Studio, which might be an error prone task. I decided to make a little contribution to the project and write an Visual Studio extension (a vsix package) to automatically deploy the template, which I am not sure yet if it is going to be approved or not, but I think it is a nice thing to have for easing adoption. This is part of the &lt;a href="https://github.com/pcibraro/incubator-cordova-wp7"&gt;fork associated to my user&lt;/a&gt; in case you want to use it.&lt;/p&gt;&lt;img src="http://weblogs.asp.net/aggbug.aspx?PostID=8467044" width="1" height="1"&gt;</content><author><name>cibrax</name><uri>http://weblogs.asp.net/members/cibrax.aspx</uri></author><category term=".NET" scheme="http://weblogs.asp.net/cibrax/archive/tags/.NET/default.aspx" /><category term="Mobile" scheme="http://weblogs.asp.net/cibrax/archive/tags/Mobile/default.aspx" /><category term="WinPhone" scheme="http://weblogs.asp.net/cibrax/archive/tags/WinPhone/default.aspx" /></entry><entry><title>Increasing your system reliability with the Azure Service Bus Queues</title><link rel="alternate" type="text/html" href="http://weblogs.asp.net/cibrax/archive/2012/04/20/increasing-your-system-reliability-with-the-azure-service-bus-queues.aspx" /><id>http://weblogs.asp.net/cibrax/archive/2012/04/20/increasing-your-system-reliability-with-the-azure-service-bus-queues.aspx</id><published>2012-04-20T15:10:00Z</published><updated>2012-04-20T15:10:00Z</updated><content type="html">&lt;p&gt;A common scenario for many web applications running in the cloud is to integrate with existing systems through web services (no matter the messaging style they use). Although in these scenarios, an SLA is typically used as an agreement between the two parties to assure certain level of availability, many things can still fail. Therefore, it is always a good idea to have a mechanism in place to handle any possible error condition and retry the execution when it is possible.&lt;/p&gt;  &lt;p&gt;As example, you could have a web application that calls an online CRM system (like Salesforce.com or MS Dynamics) for allowing the users to report incidents. In that scenario, we can not assume any possible call to the CRM system will always succeed. On the other hand, this kind of call does not require an immediate response for the user, so it can be scheduled for later execution and retried if something unexpected happens.&lt;/p&gt;  &lt;p&gt;A persistent storage for the messages like a queue is always a good choice for decoupling clients from services, and also accomplish the goal previously discussed. When you move to Windows Azure, there are two different queue offerings, Queues as part of the Storage service, and Queues (or Topics) as part of the Service Bus. &lt;/p&gt;  &lt;p&gt;The Service Bus SDK provides a programming model on top of WCF for consuming or sending messages to the queues, which makes this solution very appealing for this scenario. The Service Bus also provides Topics, which are an specific kind of queues that supports subscriptions. &lt;/p&gt;  &lt;p&gt;By using Service Bus Queues, the calls to any third party service could be eventually wrapped up in WCF services that are invoked by the web application. The following image illustrates the possible architecture,&lt;/p&gt;  &lt;p&gt;&lt;a href="http://weblogs.asp.net/blogs/cibrax/queues_131E8A64.jpg" mce_href="http://weblogs.asp.net/blogs/cibrax/queues_131E8A64.jpg"&gt;&lt;img style="border-width: 0px; padding-top: 0px; padding-right: 0px; padding-left: 0px; display: inline; background-image: none;" title="queues" border="0" alt="queues" src="http://weblogs.asp.net/blogs/cibrax/queues_thumb_6A33755A.jpg" width="644" height="108" mce_src="http://weblogs.asp.net/blogs/cibrax/queues_thumb_6A33755A.jpg"&gt;&lt;/a&gt;&lt;/p&gt;  &lt;p&gt;One of the core classes in the WCF programming model for the Service Bus Queues is BrokeredMessage. This class represents a message that can be sent to/from an existing queue, and contains a lot of&amp;nbsp; standard properties such as MessageId, ReplyTo, SessionId or Label to name a few. It also contain a dictionary for custom properties that an application can assign to the message.&lt;/p&gt;  &lt;p&gt;In the example above, the MessageId property can be used to correlate the input and out messages in the queue and update the corresponding result in the web application. The WCF service can also use the ReplyTo property, which represents the queue name in which the response should go. Sessions is another concept supported in the Service Bus Queues, which are useful for correlating a set of messages as a batch for processing.&amp;nbsp;&amp;nbsp; This is something optional and requires the queue to support sessions when they are created.&lt;/p&gt;  &lt;p&gt;In WCF, the BrokeredMessage is assigned to the service call with a message property BrokeredMessageProperty as it is illustrated bellow,&lt;/p&gt;  &lt;div id="codeSnippetWrapper"&gt;   &lt;div style='padding: 0px; width: 100%; text-align: left; color: black; line-height: 12pt; overflow: visible; font-family: "Courier New", courier, monospace; font-size: 8pt; direction: ltr; background-color: rgb(244, 244, 244);' id="codeSnippet"&gt;     &lt;pre style='margin: 0em; padding: 0px; width: 100%; text-align: left; color: black; line-height: 12pt; overflow: visible; font-family: "Courier New", courier, monospace; font-size: 8pt; direction: ltr; background-color: white;'&gt;var channelFactory = &lt;span style="color: rgb(0, 0, 255);"&gt;new&lt;/span&gt; ChannelFactory&amp;lt;ICRMServiceClient&amp;gt;(&lt;span style="color: rgb(0, 96, 128);"&gt;"crminput"&lt;/span&gt;);&lt;/pre&gt;
&lt;!--CRLF--&gt;

    &lt;pre style='margin: 0em; padding: 0px; width: 100%; text-align: left; color: black; line-height: 12pt; overflow: visible; font-family: "Courier New", courier, monospace; font-size: 8pt; direction: ltr; background-color: rgb(244, 244, 244);'&gt;var clientChannel = channelFactory.CreateChannel();&lt;/pre&gt;
&lt;!--CRLF--&gt;

    &lt;pre style='margin: 0em; padding: 0px; width: 100%; text-align: left; color: black; line-height: 12pt; overflow: visible; font-family: "Courier New", courier, monospace; font-size: 8pt; direction: ltr; background-color: white;'&gt;&amp;nbsp;&lt;/pre&gt;
&lt;!--CRLF--&gt;

    &lt;pre style='margin: 0em; padding: 0px; width: 100%; text-align: left; color: black; line-height: 12pt; overflow: visible; font-family: "Courier New", courier, monospace; font-size: 8pt; direction: ltr; background-color: rgb(244, 244, 244);'&gt;&lt;span style="color: rgb(0, 128, 0);"&gt;// Use the OperationContextScope to create a block within which to access the current OperationScope&lt;/span&gt;&lt;/pre&gt;
&lt;!--CRLF--&gt;

    &lt;pre style='margin: 0em; padding: 0px; width: 100%; text-align: left; color: black; line-height: 12pt; overflow: visible; font-family: "Courier New", courier, monospace; font-size: 8pt; direction: ltr; background-color: white;'&gt;&lt;span style="color: rgb(0, 0, 255);"&gt;using&lt;/span&gt; (var scope = &lt;span style="color: rgb(0, 0, 255);"&gt;new&lt;/span&gt; OperationContextScope((IContextChannel)clientChannel))&lt;/pre&gt;
&lt;!--CRLF--&gt;

    &lt;pre style='margin: 0em; padding: 0px; width: 100%; text-align: left; color: black; line-height: 12pt; overflow: visible; font-family: "Courier New", courier, monospace; font-size: 8pt; direction: ltr; background-color: rgb(244, 244, 244);'&gt;{&lt;/pre&gt;
&lt;!--CRLF--&gt;

    &lt;pre style='margin: 0em; padding: 0px; width: 100%; text-align: left; color: black; line-height: 12pt; overflow: visible; font-family: "Courier New", courier, monospace; font-size: 8pt; direction: ltr; background-color: white;'&gt;    &lt;span style="color: rgb(0, 128, 0);"&gt;// Create a new BrokeredMessageProperty object&lt;/span&gt;&lt;/pre&gt;
&lt;!--CRLF--&gt;

    &lt;pre style='margin: 0em; padding: 0px; width: 100%; text-align: left; color: black; line-height: 12pt; overflow: visible; font-family: "Courier New", courier, monospace; font-size: 8pt; direction: ltr; background-color: rgb(244, 244, 244);'&gt;    var property = &lt;span style="color: rgb(0, 0, 255);"&gt;new&lt;/span&gt; BrokeredMessageProperty();&lt;/pre&gt;
&lt;!--CRLF--&gt;

    &lt;pre style='margin: 0em; padding: 0px; width: 100%; text-align: left; color: black; line-height: 12pt; overflow: visible; font-family: "Courier New", courier, monospace; font-size: 8pt; direction: ltr; background-color: white;'&gt;&amp;nbsp;&lt;/pre&gt;
&lt;!--CRLF--&gt;

    &lt;pre style='margin: 0em; padding: 0px; width: 100%; text-align: left; color: black; line-height: 12pt; overflow: visible; font-family: "Courier New", courier, monospace; font-size: 8pt; direction: ltr; background-color: rgb(244, 244, 244);'&gt;    &lt;span style="color: rgb(0, 128, 0);"&gt;// Use the BrokeredMessageProperty object to set the BrokeredMessage properties&lt;/span&gt;&lt;/pre&gt;
&lt;!--CRLF--&gt;

    &lt;pre style='margin: 0em; padding: 0px; width: 100%; text-align: left; color: black; line-height: 12pt; overflow: visible; font-family: "Courier New", courier, monospace; font-size: 8pt; direction: ltr; background-color: white;'&gt;    property.Label = &lt;span style="color: rgb(0, 96, 128);"&gt;"Incident"&lt;/span&gt;;&lt;/pre&gt;
&lt;!--CRLF--&gt;

    &lt;pre style='margin: 0em; padding: 0px; width: 100%; text-align: left; color: black; line-height: 12pt; overflow: visible; font-family: "Courier New", courier, monospace; font-size: 8pt; direction: ltr; background-color: rgb(244, 244, 244);'&gt;    property.MessageId = Guid.NewGuid().ToString();&lt;/pre&gt;
&lt;!--CRLF--&gt;

    &lt;pre style='margin: 0em; padding: 0px; width: 100%; text-align: left; color: black; line-height: 12pt; overflow: visible; font-family: "Courier New", courier, monospace; font-size: 8pt; direction: ltr; background-color: white;'&gt;    property.ReplyTo = &lt;span style="color: rgb(0, 96, 128);"&gt;"sb://xxx.servicebus.windows.net/input"&lt;/span&gt;;&lt;/pre&gt;
&lt;!--CRLF--&gt;

    &lt;pre style='margin: 0em; padding: 0px; width: 100%; text-align: left; color: black; line-height: 12pt; overflow: visible; font-family: "Courier New", courier, monospace; font-size: 8pt; direction: ltr; background-color: rgb(244, 244, 244);'&gt;&amp;nbsp;&lt;/pre&gt;
&lt;!--CRLF--&gt;

    &lt;pre style='margin: 0em; padding: 0px; width: 100%; text-align: left; color: black; line-height: 12pt; overflow: visible; font-family: "Courier New", courier, monospace; font-size: 8pt; direction: ltr; background-color: white;'&gt;    &lt;span style="color: rgb(0, 128, 0);"&gt;// Add BrokeredMessageProperty to the OutgoingMessageProperties bag provided &lt;/span&gt;&lt;/pre&gt;
&lt;!--CRLF--&gt;

    &lt;pre style='margin: 0em; padding: 0px; width: 100%; text-align: left; color: black; line-height: 12pt; overflow: visible; font-family: "Courier New", courier, monospace; font-size: 8pt; direction: ltr; background-color: rgb(244, 244, 244);'&gt;    &lt;span style="color: rgb(0, 128, 0);"&gt;// by the current Operation Context &lt;/span&gt;&lt;/pre&gt;
&lt;!--CRLF--&gt;

    &lt;pre style='margin: 0em; padding: 0px; width: 100%; text-align: left; color: black; line-height: 12pt; overflow: visible; font-family: "Courier New", courier, monospace; font-size: 8pt; direction: ltr; background-color: white;'&gt;    OperationContext.Current.OutgoingMessageProperties.Add(BrokeredMessageProperty.Name, property);&lt;/pre&gt;
&lt;!--CRLF--&gt;

    &lt;pre style='margin: 0em; padding: 0px; width: 100%; text-align: left; color: black; line-height: 12pt; overflow: visible; font-family: "Courier New", courier, monospace; font-size: 8pt; direction: ltr; background-color: rgb(244, 244, 244);'&gt;    &lt;/pre&gt;
&lt;!--CRLF--&gt;

    &lt;pre style='margin: 0em; padding: 0px; width: 100%; text-align: left; color: black; line-height: 12pt; overflow: visible; font-family: "Courier New", courier, monospace; font-size: 8pt; direction: ltr; background-color: white;'&gt;    &lt;span style="color: rgb(0, 128, 0);"&gt;//Do the service call here&lt;/span&gt;&lt;/pre&gt;
&lt;!--CRLF--&gt;

    &lt;pre style='margin: 0em; padding: 0px; width: 100%; text-align: left; color: black; line-height: 12pt; overflow: visible; font-family: "Courier New", courier, monospace; font-size: 8pt; direction: ltr; background-color: rgb(244, 244, 244);'&gt;&amp;nbsp;&lt;/pre&gt;
&lt;!--CRLF--&gt;

    &lt;pre style='margin: 0em; padding: 0px; width: 100%; text-align: left; color: black; line-height: 12pt; overflow: visible; font-family: "Courier New", courier, monospace; font-size: 8pt; direction: ltr; background-color: white;'&gt;&amp;nbsp;&lt;/pre&gt;
&lt;!--CRLF--&gt;

    &lt;pre style='margin: 0em; padding: 0px; width: 100%; text-align: left; color: black; line-height: 12pt; overflow: visible; font-family: "Courier New", courier, monospace; font-size: 8pt; direction: ltr; background-color: rgb(244, 244, 244);'&gt;}&lt;/pre&gt;
&lt;!--CRLF--&gt;&lt;/div&gt;
&lt;/div&gt;

&lt;p&gt;On the service side, the BrokeredMessageProperty instance can be retrieved in a similar way&lt;/p&gt;

&lt;div id="codeSnippetWrapper"&gt;
  &lt;div style='padding: 0px; width: 100%; text-align: left; color: black; line-height: 12pt; overflow: visible; font-family: "Courier New", courier, monospace; font-size: 8pt; direction: ltr; background-color: rgb(244, 244, 244);' id="codeSnippet"&gt;
    &lt;pre style='margin: 0em; padding: 0px; width: 100%; text-align: left; color: black; line-height: 12pt; overflow: visible; font-family: "Courier New", courier, monospace; font-size: 8pt; direction: ltr; background-color: white;'&gt;var incomingProperties = OperationContext.Current.IncomingMessageProperties;&lt;/pre&gt;
&lt;!--CRLF--&gt;

    &lt;pre style='margin: 0em; padding: 0px; width: 100%; text-align: left; color: black; line-height: 12pt; overflow: visible; font-family: "Courier New", courier, monospace; font-size: 8pt; direction: ltr; background-color: rgb(244, 244, 244);'&gt;var property = incomingProperties[BrokeredMessageProperty.Name] &lt;span style="color: rgb(0, 0, 255);"&gt;as&lt;/span&gt; BrokeredMessageProperty;&lt;/pre&gt;
&lt;!--CRLF--&gt;&lt;/div&gt;
&lt;/div&gt;

&lt;p&gt;Another important feature in the programming model for supporting execution retries in our example is the ReceiveContext. By decorating the WCF service contract with the ReceiveContextEnabled attribute, we can manually specify whether the operation was successfully completed or not. If the operation was not completed, the message will remain in the queue and the operation will be executed again next time.&lt;/p&gt;

&lt;div&gt;
  &lt;div style='padding: 0px; width: 100%; text-align: left; color: black; line-height: 12pt; overflow: visible; font-family: "Courier New", courier, monospace; font-size: 8pt; direction: ltr; background-color: rgb(244, 244, 244);' id="codeSnippet"&gt;
    &lt;pre style='margin: 0em; padding: 0px; width: 100%; text-align: left; color: black; line-height: 12pt; overflow: visible; font-family: "Courier New", courier, monospace; font-size: 8pt; direction: ltr; background-color: white;'&gt;[ServiceContract()]&lt;/pre&gt;
&lt;!--CRLF--&gt;

    &lt;pre style='margin: 0em; padding: 0px; width: 100%; text-align: left; color: black; line-height: 12pt; overflow: visible; font-family: "Courier New", courier, monospace; font-size: 8pt; direction: ltr; background-color: rgb(244, 244, 244);'&gt;&lt;span style="color: rgb(0, 0, 255);"&gt;public&lt;/span&gt; &lt;span style="color: rgb(0, 0, 255);"&gt;interface&lt;/span&gt; ICRMService&lt;/pre&gt;
&lt;!--CRLF--&gt;

    &lt;pre style='margin: 0em; padding: 0px; width: 100%; text-align: left; color: black; line-height: 12pt; overflow: visible; font-family: "Courier New", courier, monospace; font-size: 8pt; direction: ltr; background-color: white;'&gt;{&lt;/pre&gt;
&lt;!--CRLF--&gt;

    &lt;pre style='margin: 0em; padding: 0px; width: 100%; text-align: left; color: black; line-height: 12pt; overflow: visible; font-family: "Courier New", courier, monospace; font-size: 8pt; direction: ltr; background-color: rgb(244, 244, 244);'&gt;    [OperationContract(IsOneWay=&lt;span style="color: rgb(0, 0, 255);"&gt;true&lt;/span&gt;)]&lt;/pre&gt;
&lt;!--CRLF--&gt;

    &lt;pre style='margin: 0em; padding: 0px; width: 100%; text-align: left; color: black; line-height: 12pt; overflow: visible; font-family: "Courier New", courier, monospace; font-size: 8pt; direction: ltr; background-color: white;'&gt;    [ReceiveContextEnabled(ManualControl = &lt;span style="color: rgb(0, 0, 255);"&gt;true&lt;/span&gt;)]&lt;/pre&gt;
&lt;!--CRLF--&gt;

    &lt;pre style='margin: 0em; padding: 0px; width: 100%; text-align: left; color: black; line-height: 12pt; overflow: visible; font-family: "Courier New", courier, monospace; font-size: 8pt; direction: ltr; background-color: rgb(244, 244, 244);'&gt;    &lt;span style="color: rgb(0, 0, 255);"&gt;void&lt;/span&gt; CreateCustomer(Customer customer);&lt;/pre&gt;
&lt;!--CRLF--&gt;

    &lt;pre style='margin: 0em; padding: 0px; width: 100%; text-align: left; color: black; line-height: 12pt; overflow: visible; font-family: "Courier New", courier, monospace; font-size: 8pt; direction: ltr; background-color: white;'&gt;}&lt;/pre&gt;
&lt;!--CRLF--&gt;&lt;/div&gt;
&lt;/div&gt;

&lt;div&gt;&amp;nbsp;&lt;/div&gt;

&lt;div&gt;The following code shows how the operation implementation looks like,&lt;/div&gt;

&lt;div&gt;&amp;nbsp;&lt;/div&gt;

&lt;div id="codeSnippetWrapper"&gt;
  &lt;div style='padding: 0px; width: 100%; text-align: left; color: black; line-height: 12pt; overflow: visible; font-family: "Courier New", courier, monospace; font-size: 8pt; direction: ltr; background-color: rgb(244, 244, 244);' id="codeSnippet"&gt;
    &lt;pre style='margin: 0em; padding: 0px; width: 100%; text-align: left; color: black; line-height: 12pt; overflow: visible; font-family: "Courier New", courier, monospace; font-size: 8pt; direction: ltr; background-color: white;'&gt;var incomingProperties = OperationContext.Current.IncomingMessageProperties;&lt;/pre&gt;
&lt;!--CRLF--&gt;

    &lt;pre style='margin: 0em; padding: 0px; width: 100%; text-align: left; color: black; line-height: 12pt; overflow: visible; font-family: "Courier New", courier, monospace; font-size: 8pt; direction: ltr; background-color: rgb(244, 244, 244);'&gt;var property = incomingProperties[BrokeredMessageProperty.Name] &lt;span style="color: rgb(0, 0, 255);"&gt;as&lt;/span&gt; BrokeredMessageProperty;&lt;/pre&gt;
&lt;!--CRLF--&gt;

    &lt;pre style='margin: 0em; padding: 0px; width: 100%; text-align: left; color: black; line-height: 12pt; overflow: visible; font-family: "Courier New", courier, monospace; font-size: 8pt; direction: ltr; background-color: white;'&gt;&amp;nbsp;&lt;/pre&gt;
&lt;!--CRLF--&gt;

    &lt;pre style='margin: 0em; padding: 0px; width: 100%; text-align: left; color: black; line-height: 12pt; overflow: visible; font-family: "Courier New", courier, monospace; font-size: 8pt; direction: ltr; background-color: rgb(244, 244, 244);'&gt;&lt;span style="color: rgb(0, 128, 0);"&gt;//Complete the Message&lt;/span&gt;&lt;/pre&gt;
&lt;!--CRLF--&gt;

    &lt;pre style='margin: 0em; padding: 0px; width: 100%; text-align: left; color: black; line-height: 12pt; overflow: visible; font-family: "Courier New", courier, monospace; font-size: 8pt; direction: ltr; background-color: white;'&gt;ReceiveContext receiveContext;&lt;/pre&gt;
&lt;!--CRLF--&gt;

    &lt;pre style='margin: 0em; padding: 0px; width: 100%; text-align: left; color: black; line-height: 12pt; overflow: visible; font-family: "Courier New", courier, monospace; font-size: 8pt; direction: ltr; background-color: rgb(244, 244, 244);'&gt;&lt;span style="color: rgb(0, 0, 255);"&gt;if&lt;/span&gt; (ReceiveContext.TryGet(incomingProperties, &lt;span style="color: rgb(0, 0, 255);"&gt;out&lt;/span&gt; receiveContext))&lt;/pre&gt;
&lt;!--CRLF--&gt;

    &lt;pre style='margin: 0em; padding: 0px; width: 100%; text-align: left; color: black; line-height: 12pt; overflow: visible; font-family: "Courier New", courier, monospace; font-size: 8pt; direction: ltr; background-color: white;'&gt;{&lt;/pre&gt;
&lt;!--CRLF--&gt;

    &lt;pre style='margin: 0em; padding: 0px; width: 100%; text-align: left; color: black; line-height: 12pt; overflow: visible; font-family: "Courier New", courier, monospace; font-size: 8pt; direction: ltr; background-color: rgb(244, 244, 244);'&gt;   &lt;span style="color: rgb(0, 128, 0);"&gt;//Do Something                &lt;/span&gt;&lt;/pre&gt;
&lt;!--CRLF--&gt;

    &lt;pre style='margin: 0em; padding: 0px; width: 100%; text-align: left; color: black; line-height: 12pt; overflow: visible; font-family: "Courier New", courier, monospace; font-size: 8pt; direction: ltr; background-color: white;'&gt;   receiveContext.Complete(TimeSpan.FromSeconds(10.0d));&lt;/pre&gt;
&lt;!--CRLF--&gt;

    &lt;pre style='margin: 0em; padding: 0px; width: 100%; text-align: left; color: black; line-height: 12pt; overflow: visible; font-family: "Courier New", courier, monospace; font-size: 8pt; direction: ltr; background-color: rgb(244, 244, 244);'&gt;}&lt;/pre&gt;
&lt;!--CRLF--&gt;

    &lt;pre style='margin: 0em; padding: 0px; width: 100%; text-align: left; color: black; line-height: 12pt; overflow: visible; font-family: "Courier New", courier, monospace; font-size: 8pt; direction: ltr; background-color: white;'&gt;&lt;span style="color: rgb(0, 0, 255);"&gt;else&lt;/span&gt;&lt;/pre&gt;
&lt;!--CRLF--&gt;

    &lt;pre style='margin: 0em; padding: 0px; width: 100%; text-align: left; color: black; line-height: 12pt; overflow: visible; font-family: "Courier New", courier, monospace; font-size: 8pt; direction: ltr; background-color: rgb(244, 244, 244);'&gt;{&lt;/pre&gt;
&lt;!--CRLF--&gt;

    &lt;pre style='margin: 0em; padding: 0px; width: 100%; text-align: left; color: black; line-height: 12pt; overflow: visible; font-family: "Courier New", courier, monospace; font-size: 8pt; direction: ltr; background-color: white;'&gt;   &lt;span style="color: rgb(0, 0, 255);"&gt;throw&lt;/span&gt; &lt;span style="color: rgb(0, 0, 255);"&gt;new&lt;/span&gt; InvalidOperationException(&lt;span style="color: rgb(0, 96, 128);"&gt;"..."&lt;/span&gt;);&lt;/pre&gt;
&lt;!--CRLF--&gt;

    &lt;pre style='margin: 0em; padding: 0px; width: 100%; text-align: left; color: black; line-height: 12pt; overflow: visible; font-family: "Courier New", courier, monospace; font-size: 8pt; direction: ltr; background-color: rgb(244, 244, 244);'&gt;}&lt;/pre&gt;
&lt;!--CRLF--&gt;&lt;/div&gt;
&lt;/div&gt;

&lt;p&gt;As you can see, the ReceiveContext instance is marked as complete or implicitly set as not complete when an exception is thrown.&lt;/p&gt;

&lt;p&gt;The assemblies for the Service Bus SDK are available as part of a Nuget package “Windows Azure Service Bus”. As part of the package registration, all the required configuration extensions for the WCF such as custom bindings and behaviors are also added in the application configuration file. &lt;/p&gt;

&lt;p&gt;NetMessagingBinding is the one you need to use for sending or receiving messages from a queue. That binding is constantly polling the queues for detecting new messages, and activating the WCF service when a new message arrives. For that reason, you need to keep the web application App pool running all the time. This can be accomplished in Windows Azure with a simple approach as this one mentioned by Christian Weyer in this &lt;a href="http://weblogs.thinktecture.com/cweyer/2011/01/poor-mans-approach-to-application-pool-warm-up-for-iis-in-a-windows-azure-web-role.html" mce_href="http://weblogs.thinktecture.com/cweyer/2011/01/poor-mans-approach-to-application-pool-warm-up-for-iis-in-a-windows-azure-web-role.html"&gt;post&lt;/a&gt;.&lt;/p&gt;&lt;img src="http://weblogs.asp.net/aggbug.aspx?PostID=8398997" width="1" height="1"&gt;</content><author><name>cibrax</name><uri>http://weblogs.asp.net/members/cibrax.aspx</uri></author><category term="ASP.NET" scheme="http://weblogs.asp.net/cibrax/archive/tags/ASP.NET/default.aspx" /><category term=".NET" scheme="http://weblogs.asp.net/cibrax/archive/tags/.NET/default.aspx" /><category term="Azure" scheme="http://weblogs.asp.net/cibrax/archive/tags/Azure/default.aspx" /></entry></feed>