Wednesday, October 24, 2012

.NET 4.5 - Simplified WCF Configuration

A WCF configuration file is basically a markup file used to communicate to the hosting environment how a WCF service is configured and should behave.  The configuration files have historically required an exhaustive explanation of each aspect of configuration and behavior.  To illustrate this, consider a standard config file.  Notice that the file contains a <system.serviceModel> section which contains a <service> element for each service hosted.  The <service> element contains a listing of <endpoint> elements that outline the endpoints for each service and a set of service behaviors.  The <endpoint> elements specify the address, binding and contract exposed by the endpoint, and optional binding and endpoint configuration.  The <system.serviceModel> section also contains a <behaviors> element that allows you to specify service or endpoint behaviors.  The following example shows the <system.serviceModel> section of a configuration file.
<system.serviceModel>
  <behaviors>
    <serviceBehaviors>
      <behavior name="MyServiceBehavior">
        <serviceMetadata httpGetEnabled="true">
        <serviceDebug includeExceptionDetailInFaults="false">
      </behavior>
    </serviceBehaviors>
  </behaviors>
  <bindings>
   <basicHttpBinding>
      <binding name=MyBindingConfig"
               maxBufferSize="100"
               maxReceiveBufferSize="100" />
   </basicHttpBinding>
   </bindings>   <services>
    <service behaviorConfiguration="MyServiceBehavior"
             name="MyService">
      <endpoint address=""
                binding="basicHttpBinding"
                contract="ICalculator"
                bindingConfiguration="MyBindingConfig" />
      <endpoint address="mex"
                binding="mexHttpBinding"
                contract="IMetadataExchange"/>
    </service>
  </services>
</system.serviceModel>
In 4.5, the configuration has been simplified by no longer requiring a <service> element.  When the <service> section is absent, or a <service> section defines no endpoints (and your service does not programmatically define any endpoints), default endpoints with default configurations are automatically added to each service.  These defaults are added for each service base address and for each contract implemented by the service.  In the default endpoints, the endpoint address relates the base address, the binding is determined by the base address scheme and the contract is the one implemented by the service.

To take this further, if you have no need to specify endpoints, modify behaviors or customize the binding, The config file is not needed at all.  For example, if a service implements x contracts and the host enables both HTTP and TCP, the service host creates x*2 default endpoints as a straight contract:endpoint.  To create default endpoints the service host must know what bindings to use.  These settings are specified in a <protocolMappings> section within the <system.serviceModel> section.  The <protocolMappings> section contains a list of transport protocol schemes mapped to binding types.  The service host uses the base addresses passed to it to determine which binding to use.  The following example uses the <protocolMappings> element.

<protocolMapping>
  <add scheme="http"     binding="basicHttpBinding" bindingConfiguration="MyBindingConfiguration"/>
  <add scheme="net.tcp"  binding="netTcpBinding"/>
  <add scheme="net.pipe" binding="netNamedPipeBinding"/>
  <add scheme="net.msmq" binding="netMSMQBinding"/>
</protocolMapping>

Service behaviors are configured for the default endpoints by using anonymous <behavior> sections within <serviceBehaviors> sections.  Any unnamed <behavior> elements within <serviceBehaviors> are used to configure service behaviors.  For example, the following configuration file enables service metadata publishing for all services within the host.

<system.serviceModel>
    <behaviors>
      <serviceBehaviors>
        <behavior>
          <serviceMetadata httpGetEnabled="True"/>
        </behavior>
      </serviceBehaviors>
    </behaviors>    
 </system.serviceModel>

Here is the configuration file from the top of this post modified to use the simplified model.

<system.serviceModel>
    <behaviors>
      <serviceBehaviors>
        <behavior>
          <serviceMetadata httpGetEnabled="True"/>
          <serviceDebug includeExceptionDetailInFaults="false"/>
        </behavior>
      </serviceBehaviors>
    </behaviors>
   <bindings>
     <basicHttpBinding>
          <binding maxBufferSize="100"
                   maxReceiveBufferSize="100" />
     </basicHttpBinding>
   </bindings>   
   <protocolMapping>
      <add scheme="http" binding="basicHttpBinding" />
   </protocolMapping>
  </system.serviceModel>

Thursday, October 11, 2012

Async in C#

C# 5 adds some powerful asynchronous functionality as an expansion to the Task and Task<TResult> aspects of .NET 4.  The old model seemed to focus on the Asynchronous Pattern and the Event-based Asynchronous Pattern but the framework itself didn't bring much to the table for allowing developers with varied levels of knowledge access to an easily adopted methodology.  With the roll out of C# 5, .NET has provided us with a wrapped API for all asynchronous programming via library based method calls.  This is the first building block of the new features for asynchronous programming and it has been said that going forward, all asynchronous operations will work via a method that returns Task or Task<TResult>.

A key change for this version is the addition of the async keyword.  This contextual keyword enables an easy declaration of an asynchronous function. Note that all asynchronous functions must return either void, a Task, or a Task<T>.  When declaring a function with async, it is also required that there must be at least one await expression inside the function itself. 

The await keyword expression does not block the thread on which it is executing. Instead, it causes the compiler to sign up the rest of the async method as a continuation on the awaited task. Control then returns to the caller of the async method. When the task completes, it invokes its continuation, and execution of the async method resumes where it left off. An await expression can occur only in the body of an immediately enclosing method, lambda expression, or anonymous method that is marked by an async modifier. The term await serves as a keyword only in that context. Elsewhere, it is interpreted as an identifier. Within the method, lambda expression, or anonymous method, an await expression cannot occur in the body of a synchronous function, in a query expression, in the catch or finally block of an exception handling statement, in the block of a lock statement, or in an unsafe context.

// Keyword await used with a method that returns a Task&ltresult&gt.
TResult result = await AsyncMethodThatReturnsTaskTResult();

// Keyword await used with a method that returns a Task.
await AsyncMethodThatReturnsTask();

Here is a simple example, suppose we want to download a webpage as a string so we can check to see if it supports XHTML 1.0,. There is a new method added to WebClient: Task<string> WebClient.DownloadStringTaskAsync(Uri).  Since this returns a Task<string> we can use it within an asynchronous function. We could do this entire process with jsut a few lines of code.

private void button1_Click(object sender, RoutedEventArgs e)
{
   String url = "http://devstorm.blogspot.com";
   String content = await new WebClient().DownloadStringTaskAsync(url);
   textBox1.Text = String.Format("Page {0} supports XHTML 1.0: {1}",
      url, content.Contains("XHTML 1.0"));
}

By adding the async contextual keyword to the method definition, we are able to use the await keyword on our WebClient.DownloadStringTaskAsync method call. This means that when the user clicks the new method (Task<string> WebClient.DownloadStringTaskAsync(string)) is called.  By adding the await keyword, the runtime will call this method that returns Task<string> and execution will return to the UI.  This means that our UI is not blocked while the webpage is downloaded.  Instead, the UI thread will “await” at this point, and let the WebClient do it’s thing asynchronously.  When the WebClient finishes downloading the string, the user interface’s synchronization context will automatically be used to “pick up” where it left off, and the Task<string> returned from DownloadStringTaskAsync is automatically unwrapped and set into the content variable, thus allowing us to report it in the text box.

Notice how the code is obviously shorter and simpler because the initial synchronization context is used to continue the execution of this function.  Meaning,  we don’t have to explicitly marshal the call that sets textbox1.Text back to the UI thread, it is just picked up via the framework.  This sort of abstraction of the difficulty is a strong step toward enabling a wide range of developers the ability to leverage asynchronous programming.  The will ultimately, as always, result in better software for the users.

Thursday, September 13, 2012

Windows Azure Mobile Services

On August 28th, Microsoft announced an addition to the Azure platform, Windows Azure Mobile Services.  The capabilities seem very powerful and target easy development and deployment of mobile applications with a cloud-based backend service hosted on Azure.  While this is targeted at Windows 8 applications exclusively, it appears to scale very well into using a mobile-first approach to all of your Windows 8 applications, desktop or mobile.  The backend framework allows for direct access to SQLAzure data via the mobile service.  In fact, when you create a Windows Azure Mobile Service, it is automatically associated with a SQL Database inside Windows Azure.  This all happens without creating any custom server code.   The management portal includes the ability to create new tables, control access, view data and other administrative items.  By leveraging this infrastructure, developers can connect directly to their cloud-based data very easily without having any insight into the server side code.  The data can be automatically accessed and stored via a secure RESTful interface.  This allows a client side developer to quickly and easily connect any Windows 8 application to the new mobile platform and its data.

Here is a code snippet showing the mechanism for directly consuming mobile cloud based data.  The native interface supports LINQ based queries of POCO objects (strongly typed) via the RESTful interface.  This code will populate a presentation layer asynchronously without creating ANY server side code to handle it.

private void RefreshTodoItems()
{
    items = App.MobileService.GetTable< TodoItem >()
       .Where(todoItem => todoItem.Complete == false)
       .ToCollectionView();

    ListItems.ItemsSource = items;
}

At this point, you have built a data driven SOA that is able to be consumed directly by any windows 8 presentation layer.

Other items that are directly supported via the Azure Mobile Services are: push notifications, user authentication and  paged queries -- all with the native services provided.  It seems to be quite easy to directly connect your Windows 8 application to the mobile services in Azure.  The upside being that it makes developing a Windows 8 client based on a cloud solution very quick and easy.  The unanswered question is still how easily you can use this to consume data in cloud style without using a Windows 8 application.  It appears that it would be possible to directly hit this service from any application able to read JSON from a REST service, but all of the supporting documentation is focused on a Windows 8 client.  Either way, this is an exciting addition that should be investigated by those of us using Azure. 

Friday, August 24, 2012

Web API in ASP.NET MVC4

In the new version of ASP.NET, Microsoft has introduced some framework extension that has exciting possibilities.  Google, FaceBook, and the like have been exposing web API in some fashion for a while now, but it has always seemed limited to certain platforms.  It appears at a glance that we will be able to provide the same functionality with native ASP.NET and MVC4 applications.  This basically allows you to expose web service over straight up HTTP instead of traditional service hosting/messaging.

The gain is that you can create web-based integration points by leveraging  a native ASP.NET architecture at the same time.  This allows you to provide a user-story-based integration routine (ala FaceBook, Twitter) as a wrapper of /or in addition to any service layer integrations that may be exposed.  

Here are some points I read from Scott Gu's Blog on the topic.  He outlines the highlights and additions to the framework.  I think the real excitement is in the realization of the walls that are coming down on platform dependence and ease of developing rich client experiences with web services in a Windows environment.

Our new ASP.NET Web API support enables you to easily create powerful Web APIs that can be accessed from a broad range of clients (ranging from browsers using JavaScript, to native apps on any mobile/client platform).  It provides the following support:
  • Modern HTTP programming model: Directly access and manipulate HTTP requests and responses in your Web APIs using a clean, strongly typed HTTP object model.  In addition to supporting this HTTP programming model on the server, we also support the same programming model on the client with the new HttpClient API that can be used to call Web APIs from any .NET application.
  • Content negotiation: Web API has built-in support for content negotiation – which enables the client and server to work together to determine the right format for data being returned from an API.  We provide default support for JSON, XML and Form URL-encoded formats, and you can extend this support by adding your own formatters, or even replace the default content negotiation strategy with one of your own.
  • Query composition: Web API enables you to easily support querying via the OData URL conventions.  When you return a type of IQueryable<T> from your Web API, the framework will automatically provide OData query support over it – making it easy to implement paging and sorting.
  • Model binding and validation: Model binders provide an easy way to extract data from various parts of an HTTP request and convert those message parts into .NET objects which can be used by Web API actions.  Web API supports the same model binding and validation infrastructure that ASP.NET MVC supports today.
  • Routes: Web APIs support the full set of routing capabilities supported within ASP.NET MVC and ASP.NET today, including route parameters and constraints. Web API also provides smart conventions by default, enabling you to easily create classes that implement Web APIs without having to apply attributes to your classes or methods.  Web API configuration is accomplished solely through code – leaving your config files clean.
  • Filters: Web APIs enables you to easily use and create filters (for example: [authorization]) that enable you to encapsulate and apply cross-cutting behavior.
  • Improved testability: Rather than setting HTTP details in static context objects, Web API actions can now work with instances of HttpRequestMessage and HttpResponseMessage – two new HTTP objects that (among other things) make testing much easier. As an example, you can unit test your Web APIs without having to use a Mocking framework.
  • IoC Support: Web API supports the service locator pattern implemented by ASP.NET MVC, which enables you to resolve dependencies for many different facilities.  You can easily integrate this with an IoC container or dependency injection framework to enable clean resolution of dependencies.
  • Flexible Hosting: Web APIs can be hosted within any type of ASP.NET application (including both ASP.NET MVC and ASP.NET Web Forms based applications).  We’ve also designed the Web API support so that you can also optionally host/expose them within your own process if you don’t want to use ASP.NET/IIS to do so.  This gives you maximum flexibility in how and where you use it.

Friday, August 17, 2012

.NET Framework 4.5

I've been doing some reading on what's new with the .NET 4.5 framework.  It looks like there are plenty of items to dive into with details in the near future.  I found this poster on a blog outlining some of the items at a very high level.


I am going to dig in deeper on some of these C# 5.0 and WCF changes to see if there are some things worth carrying over into standards and practices.  If there is anything on this poster that you would like to see a deep-dive on, leave a comment or let me know via the contact page and I will try to put something specific together.

Monday, August 13, 2012

Multi-tenant WCF Services

Hosting a multi-tenant application using WCF
While doing some long-term architecture design, the task was given to work through a cloud-based application.  Our business requirements have resulted in the need for a multi-tenant application built on WCF services that can share physical instances for multiple tenants. The first thing that jumps out in this framework for me is that these services must not contain state level variables that would directly relate to any single tenant. In this model, for instance, a BLL type service should not contain a static list of 'droplist' items to be consumed by the software unless the listing was tenant/customer agnostic. This breakdown gives us the ability to scale at any point in the SOA, based on load or any other need that may present itself. The gain is that you are not locked into a 1:1 tenant:service instance relationship which allows for more host cost effective scaling. In our model, based on the type of data stored, we have decided to go with a separate catalog for each tenant. This point works for our model and while I know there are other models that work effectively, this is really not the target of the current post.

Building the flow and responsibilities 
The first obstacle presented was how to point a tenant at the corresponding catalog without having the SOA be inherently aware of the tenant. For our model, we have the user authenticating against a centralized database and service purposed exclusively for housing tenant information. This enables us to assume that a client will be self-aware and could be provided with their tenant information to some degree prior to engaging the full SOA of the application. The idea being that if we can have the service dynamically recognize the tenant based on the tenant self-identifying at the time of messaging, we can achieve a loosely coupled environment for services to perform with a disregard for the actual tenant entity.

Communicating tenant information
While thinking through a means to provide tenant information to the services, there are a couple of possibilities that come to mind. One could simply provide all of the required information as parameters to each service call.  Would it work? Yes. Is it a good idea? No. There are many reasons this is not a good solution. One concern is the added difficulty each client application would encounter trying to consume the SOA. Plus, the SOA would be confusing, difficult to implement and not very readable as a programmer. To me, building your SOA must always consider the consuming applications and the ease with which the services can be consumed as a high priority. Those alone point us directly to the messaging interface for the service. My initial thought was to create custom incoming and outgoing message header properties to allow C# windows clients to attach the properties directly via their client proxy and then dynamically read them out in the service layer. This allows all additional difficulty to be encapsulated within the client proxy/channel factory classes. This also allows non-windows users to dynamically build message headers and attach them to the calls coming into WCF while allowing the service to leverage a single implementation to pull the information out of the message. I needed to create a proof of concept application to illustrate this. I was wrapped up in another project at the time, so ToddM took the project on and delivered an illustrative project. (Thanks, Todd). An overview of the successful prototype is as follows. First, you have to attach the outgoing behavior message header at the channel factory level in C#. This requires the creation of CustomServiceOutgoingBehvaior and CustomServiceIncomingBehvaior classes based on IEndpointBehavior and Attribute, IServiceBehavior respectively. These are then attached to the DataChannel and inspected on either side of the communication. In an effort to make this post shorter and more readable, I have removed code that doesn't directly support the main idea. To be clear, these snippets on their own are not enough.

public class DatabaseInfo
{
  public String Catalog { get; set; }
  public String Instance{ get; set; }
}
public static class Tenant
{
    public static String TenantID { get; set; }
    public static String AuthenticatedUser { get; set; }
}

public class CustomClientOutgoingBehvaior : IEndpointBehavior
{
   void IEndpointBehavior.ApplyClientBehavior(ServiceEndpoint endpoint,
              ClientRuntime clientRuntime)
    {
        clientRuntime.MessageInspectors.Add(new CustomClientOutgoingMessageInspector());
    }

}

public class CustomServiceOutgoingBehvaior : IEndpointBehavior
{
    DatabaseInfo info = null;

    public CustomServiceOutgoingBehvaior(DatabaseInfo info)
    {
        this.info = info;
    }

  
    void IEndpointBehavior.ApplyClientBehavior(ServiceEndpoint 
              endpoint, ClientRuntime clientRuntime)
    {
        clientRuntime.MessageInspectors.Add(new CustomServiceOutgoingMessageInspector(info));
    }
}

public class CustomServiceIncomingBehavior : Attribute, IServiceBehavior
{
    void IServiceBehavior.ApplyDispatchBehavior(ServiceDescription
           serviceDescription, ServiceHostBase serviceHostBase)
    {
        foreach (ChannelDispatcher channelDispatcher in 
         serviceHostBase.ChannelDispatchers)
        {
            foreach (var endpointDispatcher in channelDispatcher.Endpoints)
            {
                endpointDispatcher.DispatchRuntime.
                     MessageInspectors.Add(new 
                     CustomServiceIncomingMessageInspector());
            }
        }
    }
}
public class CustomClientOutgoingMessageInspector : IClientMessageInspector
{
   object IClientMessageInspector.BeforeSendRequest(ref Message 
     request, IClientChannel channel)
    {
        var messageHeader = new MessageHeader<String>(Tenant.TenantID);
        var untypedMessageHeader = 
               messageHeader.GetUntypedHeader("TenantID", "Namespace.Shared");
        request.Headers.Add(untypedMessageHeader);

        messageHeader = new MessageHeader<String>(Tenant.AuthenticatedUser);
        untypedMessageHeader = 
              messageHeader.GetUntypedHeader("AuthenticatedUser", "Namespace.Shared");
        request.Headers.Add(untypedMessageHeader);

        return null;
    }
}

public class CustomServiceOutgoingMessageInspector : IClientMessageInspector
{
    public DatabaseInfo DatabaseInfo { get; set; }

    public CustomServiceOutgoingMessageInspector(DatabaseInfo info)
    {
        DatabaseInfo = info;
    }
  
    object IClientMessageInspector.BeforeSendRequest(ref Message request, IClientChannel channel)
    {
        if (DatabaseInfo == null)
            return null;

        var messageHeader = new MessageHeader<String>(DatabaseInfo.Catalog);
        var untypedMessageHeader = 
            messageHeader.GetUntypedHeader("Catalog", "Namespace.Shared");
        request.Headers.Add(untypedMessageHeader);

        messageHeader = new MessageHeader<String>(DatabaseInfo.Instance);
        untypedMessageHeader = 
            messageHeader.GetUntypedHeader("Instance", "Namespace.Shared");
        request.Headers.Add(untypedMessageHeader);

        return null;
    }
}
 
Then, with a simple function added to a base class for your WCF services, you will be able to pull this information back out as follows:

protected Tuple<DatabaseInfo, Tenent> GetInfoFromHeader()
{
    DatabaseInfo dbInfo = new DatabaseInfo();
    Tenant tenantInfo = new Tenant();

    Int32 i = OperationContext.Current.IncomingMessageHeaders.FindHeader("Catalog", "Namespace.Shared");

    if (i != -1)
        dbInfo.Catalog = OperationContext.Current.IncomingMessageHeaders.GetHeader<String>(i);

    i = OperationContext.Current.IncomingMessageHeaders.FindHeader("Instance", "Namespace.Shared");

    if (i != -1)
        dbInfo.Instance = OperationContext.Current.IncomingMessageHeaders.GetHeader<String>(i);

    i = OperationContext.Current.IncomingMessageHeaders.FindHeader("TenantID", "Namespace.Shared");

    if (i != -1)
        tenantInfo.TenantID = OperationContext.Current.IncomingMessageHeaders.GetHeade<String>(i);

    i = OperationContext.Current.IncomingMessageHeaders.FindHeader("AuthenticatedUser", "Namespace.Shared");

    if (i != -1)
        tenantInfo.AuthenticatedUser = OperationContext.Current.IncomingMessageHeaders.GetHeader<String>(i);


    return new Tuple<DatabaseInfo, Tenent>(dbInfo,tenantInfo);
}
 
At this point, you will be able to pull out information from the message header and perform many routines based on a tenant entity without adding state to the server. With this information, you can build connection strings for each DAL method pointing to the correct catalog and instance based on tenant.  You can also perform user security functions based on the AuthenticatedUser passed from the client.  As you can see, this is very flexible and would scale out to any values that needed to be communicated along with the messages to the service.