Wednesday, December 5, 2012

Windows Azure Mobile Services

The Azure Mobile Services platform has some great new functionality that works toward making this a total solution for a mobile / web application hosting environment.  Some of the new features include:
  • iOS support – enabling you to connect iPhone and iPad apps to mobile services
  • iOS Push Notifications via APNS (Apple Push Notification Services)
  • Facebook, Twitter, and Google authentication support with mobile services
  • Blob, Table, Queue, and Service Bus support from within your mobile service
  • Sending emails from your mobile service (in partnership with SendGrid)
  • Sending SMS messages from your mobile service (in partnership with Twilio)
  • Ability to deploy mobile services in the west US region
Scott Gu had an article on his blog this morning outlining the expanded support for iOS on the Windows Azure Mobile Services platform. This post runs through how to create a web service that sends push notifications to iOS devices using a native Objective-C SDK within Azure.

This will go a long way toward making Azure the gold standard platform for hosting a web application that interacts with all devices.  By combining this technology with the Windows 8 mobile platform to leverage your Azure-hosted RESTful services, you are able to offer a wide range of device support with a large amount of shared infrastructure and service instance.

If you would like to walk through a tutorial using the push notifications, Microsoft has published one that covers all of the basics. You can view the first tutorial here and follow it up with this one. 

Monday, November 26, 2012

WCF REST with multiple DataContract parameters

When you are creating a RESTful WCF service that requires multiple DataContract parameters, there are a couple of different options for handling this requirement and staying true to a RESTful uri implementation. I think that each are valid and really depend more upon your view of the experience you want to provide the consumers and / or integrators of your SOA.

Wrapped Body 
By decorating the method within the service interface with the wrapped body attribute, this informs the method that all parameters will be wrapped within a single object during transport.  This allows you to keep your DataContracts separated and singularly implemented, while allowing for execution of complex methods.  Here is an example of using the wrapped request attribute.

[DataContract]
public class Label
{
   [DataMember]
   public Int64 ID { get; set; }      
   [DataMember]
   public String Name { get; set; }        
}

[DataContract]
public class Album
{
   [DataMember]
   public Int64 ID { get; set; }
   [DataMember]
   public String Artist { get; set; }
   [DataMember]
   public String Name { get; set; }
   [DataMember]
   public String Genre { get; set; }
}

[OperationContract]
[WebInvoke(Method = "POST", UriTemplate = "/AlbumAndLabel",
    BodyStyle = WebMessageBodyStyle.WrappedRequest),
    Description("Adds a new album and label to the corresponding list")]
void AddAlbumAndLabel(Album album, Label label);

This will require the consumer of your service to serialize both of the contracts into a container object as part of the message interaction with the service.  So, the integrator would have to manually create and post a message body that resembled this:

<AddAlbumAndLabel>
   <Album>
      <ID></ID>
      <Artist>Nine Lashes</Artist>
      <Name>World We View</Name>
      <Genre>Hard Rock</Genre>
   </Album>
   <Label>
       <ID></ID>
       <Name>Tooth And Nail</Name>
   </Label>
</AddAlbumAndLabel>

This is entirely effective and will result in the ability to have multiple parameters.  This will give you the ability as well to migrate all functionality away from QueryString parameters and into a single wrapped message body.  The downside to this method is that your consuming developers will have to manually serialize multiple objects into a non-existent wrapper object.  The upside is that you will have less DataContracts to manage and maintain.

Method-Specific Complex Types
While less dynamic and more manual on the service side, this give you the ability to abstract the 'difficulty' in serializing multiple types into a wrapped body away from the user of your services.  In this model, you would create a new DataContract specific to your complex method.  Basically, you are taking the step of creating a wrapper object for transport on the service side. This approach will force you to design a user story focused service wherein each detailed user story has a single associated service method.  In this case, a new DataContract would be created as follows:

[DataContract]
public class AlbumAndLabel

{
   [DataMember]
   public Label Label{ get; set; }      
   [DataMember]
   public Album Album { get; set; }        
}

[OperationContract]
[WebInvoke(Method = "POST", UriTemplate = "/AlbumAndLabel"),
    Description("Adds a new album and label to the corresponding list")]
void AddAlbumAndLabel(AlbumAndLabel albumAndLabel);

This will allow you to expose a library of user story focused DataContracts and methods to the consumers of your services, allowing them to more easily create complex types to be passed to your methods with a single serialization routine.  The downside to this method is that you have a list of DataContracts that are only needed for a single method.  The upside to this method, is that your consuming developers can leverage your service with a lesser knowledge level.

Friday, November 9, 2012

The Roslyn Project

I found an article about an interesting new project Microsoft is undertaking beginning with VS2012.  The Roslyn Project as it is called will expose the APIs used by Visual Studio to compile code as services for open consumption.  This transition will basically open the door for more openly creating code focused tools and applications. This will undoubtedly lead to new innovation in code generation, transformation and interaction with the C# and VB languages. 

The Roslyn project will expose the following layers as services: the Compiler APIs, the Services APIs, and the Editor Services APIs. By exposing these APIs, IDE development and IDE focused tools will be more widely developed as well as more functional.  Anyone with a good idea will be able to spin up a compiler add-on or IDE.  This will allow many small players to hit home runs on pitches Microsoft would never even swing at. 

We will have the ability to analyze and transform our syntax automatically as well as customize our IDE to specific standards. I have just begun looking into this, but some of the ideas that come to mind immediately are having the ability to enforce, coach and correct our coding guidelines with things like namespace restrictions on developer and build machines.  We would have the ability develop 'standard specific' functionality that mimics other profilers on the market but would be geared to individual team / company standards. 

The concept is very interesting and exciting.  It is a very good read if you have the time.  More information can be found here

Wednesday, October 31, 2012

C# 5: Caller Information

.NET 4.5 has introduced a few new classes that will enable more detailed logging, debugging and tracing through your code.  Today, I will focus on the following classes:

1. The CallerMemberNameAttribute class is used by appending it as an optional parameter on a method.  When the method is called, it will contain the method or property name which made the current call into this method.
2. The CallerFilePathAttribute class is used by appending it as an optional parameter on a method.  When the method is called, it will contain the code file path to the C# source code file that made the current call into this method.
3. The CallerLineNumberAttribute class is used by appending it as an optional parameter on a method.  When the method is called, it will contain the code file line number within the C# source code file that made the current call into this method.

Grabbing all of this information will enable you to create very detailed logging and trace statements.  This will ultimately aid you in trouble-shooting code issues or errors encountered by users running your application.  Below is a usage example of these attributes and the run-time logging potential they make available.

namespace CallerInformation
{
    class Program
    {
        static void Main(string[] args)
        {   
            MethodA();
            MethodB();
            Console.ReadLine();
        }

        static void MethodA([CallerMemberName] string memberName = "",
               [CallerFilePath] string sourceFilePath = "", 
               [CallerLineNumber] int sourceLineNumber = 0)
        {
            InsertLog(memberName, "MethodA", sourceFilePath, sourceLineNumber); 
            MethodB();
        }

        static void MethodB( [CallerMemberName] string memberName = "",
               [CallerFilePath] string sourceFilePath = "",  
               [CallerLineNumber] int sourceLineNumber = 0)
        {
            InsertLog(memberName, "MethodB", sourceFilePath, sourceLineNumber);
        }

        static void InsertLog(string methodName, String calledMethodName, 
               String sourceFilePath, Int32 sourceLineNumber)
        {
            Console.WriteLine("{0} called {1} from file:'{2}' line: {3}",
              methodName, calledMethodName, 
              sourceFilePath, sourceLineNumber.ToString());

        }
    }
}

In the output from this application, notice that the calls to MethodB() both form the Main method as well as MethodA() contains the correct information regarding the source object, file and line number.


While possible to rely upon your exception handling plan to provide call stack information, you are also able to build on the base for your own purposes.  By accessing these values as well as any local data, variable values and session specific information, you can build and handle messages that present you with all of the information needed to troubleshoot user errors, debug intricate processes or supply more complex audit trail logging within your system.

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.