Showing posts with label C#. Show all posts
Showing posts with label C#. Show all posts

Wednesday, January 15, 2014

Interface level validations of DataObjects

Purpose

I was recently working on a project where I wanted to create the most granular interfaces possible and then group them into usable objects. My intent was to pass these objects around to shared utilities and services that would focus on the interfaces and thus be reusable by intent instead of specific implementation. For example, we would create an interface each for phone number, email and street address. These interfaces could be used on a customer, vendor, or employee object to ensure a standard implementation of the fields. Then, we could build our communications services to work off the interfaces for communication types and thus be generic to the entity being contacted. By doing this, I would be able to build singularly focused services that dealt with small tasks on data objects with a disregard for their specific implementation beyond the interface.

Validation

Being a big fan of data contracts with ability to run self-aware validations(e.g. validations that can only consider the scope of the contract itself without any relationships), I found myself needing a way to have all objects validate based on the requirements of the smaller interfaces, within the CRUD services of the manifested object. I also wanted to ensure the ability to dynamically add validation routines and have them picked up by the calling services without having to couple them together.

Solution

By creating a custom attribute and applying it to methods in the interface, I would be able to reflect through the methods of any object and trigger it to self validate using any and all methods that were added to the object from the implemented interfaces. Next, we simply call a data contract extension method that to invoke all validations. Here are the examples.
Custom Method Atribute

[AttributeUsage(AttributeTargets.Method, Inherited = false)]
public class InterfaceValidation : Attribute
{
    //...
}
Data Contract Extension

public static class DataContractExtensions
{
    public static T CallInterfaceValidations<T>(this T obj)
    {
        var methods = obj.GetType().GetMethods();
        object[] parameters = null;
        foreach (var method in methods)
        {
            var attributes = method.GetCustomAttributes(typeof(InterfaceValidation), true);
            if (attributes != null && attributes.Length > 0)
            {
                try
                {
                    method.Invoke(obj, parameters);
                }
                catch (Exception)
                {

                    throw;
                }

            }
        }
        return obj;
    }
}
Assign the attribute to a method

[InterfaceValidation]
void ValidateSomething();




Friday, December 27, 2013

Inversion of Control Pattern

Dependency Inversion Principle

The DIP states that high level classes should not depend on low level classes.  Both should depend on abstractions.  Details should depend on abstractions.  Abstractions should not depend on details.  The DIP is about reversing the direction of dependencies from higher level components to lower level components such that lower level components are dependent upon only the interfaces owned by the higher level components.  This is a method for moving to a more loosely coupled architecture.  Basically, you have to depend on a standard interface used by objects and not depend on their details.  This one might be best illustrated by example. 

In the following example, the BadCar class is tightly coupled to the actual implementation of the BadMotor function.  This means that these two objects are married, and changes to one directly impact the other.

public class BadMotor
{
    public Boolean Start()
    {
        Console.Write("Starting");
        return true;
    }
}
 
//tightly coupled to details.
public class BadCar
{
    public BadMotor Motor {get;set;}
 
    public Boolean Start(BadMotor badMotor)
    {
        Motor = badMotor;
        return Motor.Start();
    }
}
 
 
While this does function, it creates a dependency relationship between two objects at their implementation level.   This creates hardships for maintenance and scalability long term.   The proper way to build this relationship would be to invert dependencies onto interfaces to ensure no object has knowledge or visibility into implementation of any other object. Consider the following examples:
public interface IEngine
{
    bool Start();
}
 
public interface IGreenEngine : IEngine
{
    bool IsCharged ();
}
 
public class FourCylEngine : IEngine
{
    public bool Start()
    {
        Console.WriteLine("4Cyl Starting");
        return true;
    }
}
 
public class V8Engine : IEngine
{
    public bool Start()
    {
        Console.WriteLine("V8 Starting");
        return true;
    }
}
 
public class HybridEngine : IGreenEngine
{
    public bool Start()
    {
        if (IsCharged())
            Console.WriteLine("Hybrid Starting");
        return true;
    }
    public bool  IsCharged()
    {
        Console.WriteLine("Hybrid is charged");
        return true;
    }
}
 
public class Car
{
    public Car(IEngine engine)
    {
        Engine = engine;
    }
    public IEngine Engine{get ; set ; }
    public Boolean Start()
    {
            
        return Engine.Start();
    }
}
 
I built this interface dependency and inheritance to ensure that objects are loosely coupled and only share an interface.   This allows for actual base implementations to come and go and even be recognized dynamically without causing lower level objects to update their implementation.   Here is an example of hot swapping and scaling with the previously defined objects and interfaces.
class Program
{
      
    static void Main(string[] args)
    {
        //  Cars are only dependant upon an Engine interface
        Car BigThing = new Car(new V8Engine());
        BigThing.Start();
        //  Cars are only dependant upon an Engine interface
        Car SmallThing = new Car(new FourCylEngine());
        SmallThing.Start();
        // Since we have an interface dependency, it is easy to hot swap.
        BigThing.Engine = new HybridEngine();
        BigThing.Start();
    }
}

The output is as follows:


As you can see, this allows for maintainability and long-term scalability by ensuring that the objects stay out of each other's business. By adhering to the spirit of this principle as well as the previous SOLID principles, you can keep your code base healthy and easy to maintain when the requirement changes come.

Tuesday, July 2, 2013

ASP.NET MVC4 - Mobile Views

In ASP.NET MVC4 you have the ability to easily present a view directed at a mobile display without requiring the use of an add on tools.  Sure, for a good mobile experience, you may choose to implement jQueryMobile or something similar, but the fact remains that it is not required with this functionality.


Mobile Experience

A good portion of visual design for mobile can come from using simple media queries to detect the current size of the users' device and render a visual experience accordingly.   Media queries within CSS are straightforward and can handle the majority of simple user experience changes.  For instance, if you wanted to change any properties of an element based on the screen width and orientation of the users' device, you could simply create some combination of the following code:
/* #### Mobile Phones Portrait #### */
@media screen and (max-device-width: 480px) and (orientation: portrait){
  /* some CSS here */
}

/* #### Mobile Phones Landscape #### */
@media screen and (max-device-width: 640px) and (orientation: landscape){
  /* some CSS here */
}

/* #### Mobile Phones Portrait or Landscape #### */
@media screen and (max-device-width: 640px){
  /* some CSS here */
}

/* #### iPhone 4+ Portrait or Landscape #### */
@media screen and (max-device-width: 480px) and (-webkit-min-device-pixel-ratio: 2){
  /* some CSS here */
}

/* #### Tablets Portrait or Landscape #### */
@media screen and (min-device-width: 768px) and (max-device-width: 1024px){
  /* some CSS here */
}

/* #### Desktops #### */
@media screen and (min-width: 1024px){
  /* some CSS here */
}

That sort of thing will go a long way, but sometimes it can lead to clutter and hard to follow CSS.


Overriding a mobile view in MVC4

With MVC 4, there is a very simple mechanism that lets you override any view for mobile browsers in general.  You can also define your own parameters for a specific mobile override, giving you the ability to build specific views for specific devices or user agents.  To provide a view that overrides for any mobile device, all you have to do is copy the view to a new file and add .Mobile to the file name. For example, to create a mobile Something view, copy Views\Home\Something.cshtml to Views\Home\Something.Mobile.cshtml.  The current context will trigger which view is pulled in a run time for a given client.  Now, you have effectively created a mobile specific view that can be visually altered for an experience geared at a mobile platform.


Custom Override Views

You can create almost any kind of custom mobile view you would like by defining a context condition and inserting into the DisplayModeProvider instance. For example, the following code will create a specific display mode based on check the user agent of the current context against 'iPhone'. Then, you add it to the list of display modes within the ApplicationStart method of the global.asax:

public class MvcApplication : System.Web.HttpApplication 
 {
 protected void Application_Start()
    {
    AreaRegistration.RegisterAllAreas();

     DisplayModeProvider.Instance.Modes.Insert(0, new DefaultDisplayMode("iPhone")
        {
         ContextCondition = (ctx =>
         ctx.Request.UserAgent.IndexOf("iPhone", StringComparison.OrdinalIgnoreCase) >= 0)
        });

    //Add another one specifically for some tablets too 
    DisplayModeProvider.Instance.Modes.Insert(0, new DefaultDisplayMode("Tablet")
        {
         ContextCondition = (ctx =>
         ctx.Request.UserAgent.IndexOf("iPad", StringComparison.OrdinalIgnoreCase) >= 0 ||
         ctx.Request.UserAgent.IndexOf("Android", StringComparison.OrdinalIgnoreCase) >= 0 &&
         ctx.Request.UserAgent.IndexOf("Mobile", StringComparison.OrdinalIgnoreCase) <= 0
        )
        });
    FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
    RouteConfig.RegisterRoutes(RouteTable.Routes);
    BundleConfig.RegisterBundles(BundleTable.Bundles);
    }
 }

As you can see, the framework gives you the ability to create as many focused views, with as much device granularity as you see fit for your application. This will help ensure good user experiences on specific devices without having to rework existing CSS or get into switching to mobile sites.

Tuesday, May 28, 2013

C# DateTime to Javascript issues with timezone

I ran into an interesting problem when serializing a C# DateTime object as JSON and returning it via a controller to javascript.  The timezone mechanism was causing my times to shift to a localized time based on the originating timezone offset to the local timezone of the web host.  Normally, that might not be a huge issue, but since my application was displaying appointments which were being pulled from a localized data store to a user in that same region, the server timezone is irrelevant and the time for the appointment has to be the same time regardless of the timezone.  After much digging around, I found this little snippet that seems to answer the problem.


function parseJsonDate(jsonDate) {
    var offset = new Date().getTimezoneOffset() * 60000;
    var parts = /\/Date\((-?\d+)([+-]\d{2})?(\d{2})?.*/.exec(jsonDate);

    if (parts[2] == undefined) parts[2] = 0;
    if (parts[3] == undefined) parts[3] = 0;

    return new Date(+parts[1] + offset + parts[2] * 3600000 + parts[3] * 60000);
};

Thursday, April 18, 2013

Extension Methods

I recently saw an email where a development manager was reminding his team of the value of extension methods.  This is a great method for adding base class type functionality to objects without introducing dependencies and utility classes for simple functions.

Extension methods are an easy way  to "add" functionality to existing types without having to create derived types, recompile, or otherwise modify the original type. Extension methods are a static method, but they are called as if they were methods on the target type. Using C#, there is no apparent difference between calling an extension method and the methods that are actually part of the defined type.

Here is an example extension method.  This method will extend the object string to break apart camel cased names and return a human readable name.  This can be very useful for populating drop down lists with all values of an Enumeration and other such activities.  First, we create the static method as follows.

public static string SplitCamelCase(this String input)
{
    return Regex.Replace(input, "([A-Z])", " $1", RegexOptions.Compiled).Trim();
}
This simply create a method (SplitCamelCase) and adds it to the methods available to any String variable in namepace scope with this class.

Then, this method can be called in the same format as any other method on the type String.


static void Main(string[] args)
{
    String testValue = "ThisIsACamelCasedSentence";
    Console.WriteLine(testValue.SplitCamelCase());
} 

These methods are quite simple to create and yet are a very powerful replacement for utility classes.  They can be used on native types as well as complex types.

Thursday, April 4, 2013

Inversion of Control (IoC) Pattern

I have been involved in many architectural discussion lately, where groups of people have been throwing around ideas on the correct way to build systems.  I am always coming from a position of loosely coupling and making sure that all aspects of your system are interchangeable and have the ability to be dynamically changed or replaced without system wide impact.  One topic that I find myself mentioning over and over again is the pattern known as Inversion of Control. Inversion of control (IoC) is a OOP technique by which  object coupling is bound at run time by an another object that is typically not known at compile time using static analysis.  The basic idea of this pattern is separate the creation of an object from the class which is trying to consume it.

The problem

As with every design pattern, the reasoning behind IoC is to avoid the possibility of design related problems.  For example, let's create an Appointment class which contains a Person class object. The biggest issue with the code below is tight the coupling between classes. In other words the Appointment class depends on the Person object. This main seem innocuous enough at a glance.  But, the byproduct of this design is that  if for any reason Person class changes, it will lead to a compile of the Appointment class. Then, in our world any object compilation leads to regression testing of the recompiled object, even though there was not an actual change. 
public class Person
{
}

public class Appointment
{
    private Person person;

    public Appointment()
    {
        person = new Person();
    }
}
The biggest problem with the sample code is that the appointment class controls the creation of Person object.  The patient class is directly referenced in the Appointment class which leads to tight coupling between these two objects.The Appointment class is aware of the Person class type. So if we add new Person types (like patient, sales person, employee, or pet), it will lead to changes in the Appointment class also as Appointment class is exposed to the actual Person implementation.  This also means that the creation of the Appointment class is dependent upon the successful creation of the Patient object within it's constructor.

The solution

If we are able to shift this task / control of object creation from the Appointment class to some other entity we have solved our problem. This means we are able to invert the control to a third party object and thus have found the solution. Some people call the IoC pattern the 'Hollywood' pattern because the simplest explanation of it's purpose is summed up the in phrase "Don't call us, we'll call you." This is a good summary of the idea of this pattern. There are many ways to accommodate this pattern with varying degrees of overhead. In my opinion, the simplest implementation of an IoC Container. IoC containers are used to simplify the provision of a dependant class's dependencies. In the most basic form, an IoC container is an implementation of the service locator design pattern that permits pre-instantiated objects to be registered with the container and later extracted. To substitute a new class and modify the operation of an entire solution, only the initial registration of the type need be changed.

IoC Container

Some IoC containers allow you to register types, rather than objects, and instantiate the type when requested, possibly using parameters. Others allow the registrations to be deserialised from an XML file, which could be modified in a text editor. In this article we will create a basic IoC container that does not include these additional features. This will demonstrate the use of IoC containers with the simplest possible code. You may decide to enhance the code to add extra features for your own use. However, you should also consider obtaining one of the many alternative IoC container solutions that are currently available. Following is the code to create a very a basic IoC container.
public static class IoC
{
    static Dictionary<Type, object> _registeredTypes = new Dictionary<Type, object>();

    public static void Register<T>(T toRegister)
    {
        _registeredTypes.Add(typeof(T), toRegister);
    }

    public static T Resolve<T>()
    {
        return (T)_registeredTypes[typeof(T)];
    }
}

Using the IoC Container

To illustrate the usage of the IoC container we first need to create an interface and a class that implements it. We will later register an instance of the class for the interface's type. The code for a simple interface and class that is used to grab a value are as follows:
public interface IPerson
{
    void SayYourName(string name);
}


public class Person : IPerson
{
    public void SayYourName(string name)
    {
        Console.WriteLine(name);
    }
}
We can now register the interface's type and provide a new Person object, which will be returned whenever the type is resolved. You would usually do this when your application is first started. In this example we will only register one type. In a real solution you can register as many types as are required for the operation of your software.
static void Main(string[] args)
{
    IoC.Register<IPerson>(new Person());
    IPerson person = IoC.Resolve<IPerson>();
    person.SayYourName("Jim Garrett");  
}
Once registered, any code that has access to the IoC class can resolve the type. In the sample the first line requests the object from the IoC container that implements IPerson. This returns the previous registered Person object. The object is then used to output a message to the console.

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.

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.

Tuesday, August 7, 2012

JQueryMobile List Item Helper

I have been working through some mobile web prototypes recently using jQueryMobile.  The mobile web application itself is a client of WCF services.  As part of the application I wanted to use the basic linked list format with some additional information.  Since these have to be attached to the DOM and rendered on the client side, I found myself wanting to retrieve a list of data contracts on the server side and have the DocumentReady function turn them into a linked list. Since the server side page_load code executes prior to the DocumentReady code on the client side, it gives us the opportunity to retrieve the data needed and place items in the DOM for linked list creation.  I found a viable solution for accomplishing this task and thought it seemed like a good item to walk through.

jQueryMobile list anatomy
The list markup is fairly straightforward and has additional attributes for data-role to drive jQueryMobile.  Here is a snippet for a small sample list:

<div data-role="content">
  <div class="content-primary">
    <ul data-role="listview">
    <li><a href="index.html">Acura</a></li>
    <li><a href="index.html">Audi</a></li>
    <li><a href="index.html">BMW</a></li>
    <li><a href="index.html">Cadillac</a></li>
    <li><a href="index.html">Chrysler</a></li>
    <li><a href="index.html">Dodge</a></li>
    <li><a href="index.html">Ferrari</a></li>   
    </ul>
  </div>
</div>

This all works really well if you can hard-code the items in your list, which in this case I could not.  The number of items had to be dynamic as well as the href attribute.  In order to accomplish this, I made the following modifications to the snippet:
<div data-role="content">
  <div class="content-primary">
    <ul runat="server" id="carList" data-role="listview">
    </ul>
  </div>
</div>

In short, I made the control run at the server, gave it an id and removed all of the items from the list.  So my next step is to dynamically add the items to the list from the C# code behind.  The first thing to do was create a helper object to create items for me.  I wanted to be able to dynamically format these items to have a header, details and possibly a thumbnail image.  In order to accomplish this, I had this class take a title, a list of strings, the href location and an image if one was required.  Here is the helper code I used:
public static class jQueryMobileHelper
{
public static HtmlGenericControl buildListItem(String headerDescription, 
    List<String>items, String urlLocation)
{
  HtmlGenericControl li = new HtmlGenericControl("li");
  HtmlGenericControl anchor = new HtmlGenericControl("a");
  HtmlGenericControl h3 = new HtmlGenericControl("h3");
  anchor.Controls.Add(h3);
  h3.InnerText = headerDescription;
  foreach (String detail in items)
  {
    HtmlGenericControl p = new HtmlGenericControl("p");
    p.InnerText = detail;
    anchor.Controls.Add(p);
  }
  anchor.Attributes.Add("href", urlLocation);
  anchor.Attributes.Add("target", "_self");            
  li.Controls.Add(anchor);
  return li;
}

public static HtmlGenericControl buildListItemWithThumbnail(String headerDescription, 
     List<String>items, String urlLocation, String imageLocation)
{
  HtmlGenericControl li = new HtmlGenericControl("li");
  HtmlGenericControl anchor = new HtmlGenericControl("a");
  HtmlGenericControl h3 = new HtmlGenericControl("h3");
  HtmlGenericControl img = new HtmlGenericControl("img");

  img.Attributes.Add("src", imageLocation);
  img.Attributes.Add("style", "height: 70px; width: 70px");
  img.Attributes.Add("display", "inline-block");
  img.Attributes.Add("alt", "image");

  anchor.Controls.Add(img);
  anchor.Controls.Add(h3);
  h3.InnerText = headerDescription;
  foreach (String detail in items)
  {
    HtmlGenericControl p = new HtmlGenericControl("p");
    p.InnerText = detail;
    anchor.Controls.Add(p);
  }
  anchor.Attributes.Add("href", urlLocation);
  anchor.Attributes.Add("target", "_self");
  li.Controls.Add(anchor);
  return li;
}
Next I looped through the items I had in my collection and created the list items.  As part of this routine, I just appended the items to the list control as follows:

List<String>items = new List<String>();
foreach (CarInfo car in cars)
{
   items.Add(car.Make);
   items.Add(car.ModelYear);
   items.Add(car.Price.ToString("C"));
   carList.Controls.Add(jQueryMobileHelper.buildListItemWithThumbnail(car.Model,items,
          String.Format("carDetail.aspx?carId={0}",car.ID),
          car.ThumbnailLocation ));
}
This gives you a list formatted similarly to the examples on the jQueryMobile site.  But, allows you to build them dynamically from the server side based on your existing services.

Friday, July 27, 2012

Ordinals vs Column Names - Part Deux

Since the first post turned into a discussion of readability versus performance, maintainability versus speed and other very worthwhile topics, I decided to put this entire process to a road test.  I created unit tests that called a DAL services basically retrieving an entire table in each of the three presented methodologies.  To get the output, I enabled our handy-dandy unit test timer to trap the performance of the DAL list functions. In order for this to be good science, I restarted the database 3 times over the course of the testing and ran the tests in different orders each time. For retrieving just under 17000 rows consisting of 38 columns, here are the results and averages for the test run (values in Milliseconds).


Run  String  Dictionary Ordinal String Order Dictionary Order Ordinal Order Difference
1 2705 2469 2505 1 3 2 236
2 2648 2575 2506 2 3 1 142
3 2669 2520 2501 2 1 3 168
4 2570 2648 2445 3 1 2 203
5 2577 2566 2397 3 1 2 180
6 2450 2646 2575 3 1 2 196
7 2555 2606 2479 2 1 3 127
8 2843 2621 2446 1 2 3 397
9 2628 2485 2388 1 2 3 240
10 2580 2525 2400 3 1 2 180
Total 2622.50 2566.10 2464.20 0.21

So, at the end of the day, here is what I learned.  It really doesn't matter enough to worry about it.  Sure, the ordinals are consistently faster than the dictionary and the dictionary is faster than string, but the variance is hardly worth worrying about.  When retrieving 17000 rows, the average difference from the best performance to the worst performance was a matter of 2/10 of one second.  I think I got wrapped up in a common distraction know as micro-optimization, where we spend a ton of mental energy and rewrite code to gain a millisecond on a routine. Yes, you should care about performance, and yes, faster code should always be your goal, but there comes a point in time where it stops being worth the development time.  Yes, we should avoid the blatantly poor performing code mistakes that everyone knows about. But after that, we should be equally worried about the scalability, portability, maintainability and readability of our code. We should ask if saving 2/10 second while retrieving 17000 rows is the matter to discuss, or should we be discussing why we would ever be retrieving 17000 often enough in our application to have 2/10 second be an issue.  Yes, I started the discussion, thinking it was a creative way to gain performance.  Honestly, I enjoy trying to work through things like this too, which fed the distraction.  I believe now that these mental exercises should always be framed with realistic improvement potential weighed against the time and effort of the pursuit. At that point, only pursue until it starts becoming a net loss of productivity.  On this particular subject, after doing this research, count me firmly in the "It really doesn't matter, aim at code readability and object design" camp.

Tuesday, July 24, 2012

Synchronization Context and Callbacks

SynchronizationContext 
The SynchronizationContext behavior is basically a configuration that allows the asynchronous and synchronization operations of the CLR to act appropriately while being used within various synchronization models. It also allows for a simple configuration of applications to work correctly under the different synchronization environments. This gives a service a quick way of associating itself with a particular synchronization context and then allowing WCF to detect that context and automatically marshal the call from the worker thread to the service synchronization context. The default value of UseSynchronizationContext is true. Affinity between the service, host and synchronization context is set when the host is opened. If the thread opening the host has a synchronization context and UseSynchronizationContext is true, WCF will establish an affinity between that synchronization context and all instances of the service hosted by that host. WCF will automatically marshal all incoming calls to the synchronization context. If UseSynchronizationContext is false, regardless of any synchronization context the opening thread might have, the service will have no affinity to any synchronization context. Interestingly enough, if UseSynchronizationContext is true but the opening thread has no synchronization context, the service will still not have one. By default, when executing the code below the client thread will be blocked while the return value is received from the service.

serviceProxy = new SomeService(new InstanceContext(this));
serviceProxy.Open();
MyObject = serviceProxy.CreateMyObject(new MyObject(1));

This is all fine on the surface. But, what would happen if the CreateMyObject function sends a callback? The client thread would be blocked. We can handle this with the callback behavior aspect of WCF. CallbackBehaviorAttribute.

UseSynchronizationContext
As a refresher, the CallbackContract property of a ServiceContract specifies the interface to define callback operations. This will create a dependent relationship between the interfaces. Once a CallbackContract is specified, the client will have to implement the callback functions in order to interact with the service at all. The CallbackBehavior setting for UseSynchronizationContext basically governs the affinity between the service and the client. You can easily override the automatic association of synchronization contexts with a simple decoration. By setting the UseSynchronizationContext property of the CallbackBehavior attribute to false, WCF will no longer guarantee a particular thread to be responsible for processing service requests. Instead, the operations will be automatically delegated to worker threads.

[CallbackBehavior(UseSynchronizationContext = false)]

When not using synchronization context on callback behavior, you may run into issues trying to directly update the UI, since those callbacks will no longer be on the UI thread.  One way around that would be to use a SendOrPostCallback delegate.

Monday, July 9, 2012

REST WCF Feed Service with Dynamic Response

Much like the project in which we built a WCF dynamic response service allowing for JSON, XML or DataContract serialization, this project is based on dynamic response capabilities.  In this project, we will continue with the Album services created previously and extend them to dynamic response as a syndicated feed.  This RESTful service will dynamically respond with either ATOM or RSS syndication based on the request type.

I will accomplish this using two different examples of response, one with a return type of System.ServiceModel.Channels.Message and another with a return type of SyndicationFeedFormatter.  First, we need to syndicate a feed based on our data repository.  I am including the ability to filter our feed based on genre and artist so we can access virtual sub-feeds with a uri.


private SyndicationFeed CreateAlbumFeed(String genre = "all", String artist = "all")
{
    SyndicationFeed feed = new SyndicationFeed
    {
        Title = SyndicationContent.CreatePlaintextContent("The album listing"),
        Description = SyndicationContent.CreatePlaintextContent("Dynamic feed response from single WCF"),
        LastUpdatedTime = DateTime.Now,
        Items = from a in DataRepository.Albums()
                where ((genre.ToLower().CompareTo("all") == 0)||(a.Genre == genre)) &&
                ((artist.ToLower().CompareTo("all") == 0) || (a.Artist == artist))
                select new SyndicationItem
                {
                    LastUpdatedTime = DateTime.Now,
                    Title = SyndicationContent.CreatePlaintextContent(a.Artist+": "+a.Name),
                    Content = SyndicationContent.CreateXmlContent(a)
                }
 
    };
    return feed;
}
 
 
This function will do nothing more than create a syndication feed from our album listing based on a couple of parameters.  Next, we need to add interface options for retrieving the feed.

 [OperationContract]
 [WebGet(UriTemplate = "/Feeds/Albums"), 
         Description("Returns an Atom or RSS feed of albums")]
 System.ServiceModel.Channels.Message GetAlbumFeed();
 
 [OperationContract]
 [WebGet(UriTemplate = "/Feeds/Genre/{genre}"), 
         Description("Returns an Atom or RSS feed of albums by genre")]
 SyndicationFeedFormatter GetGenreFeed(String genre);
 
 [OperationContract]
 [WebGet(UriTemplate = "/Feeds/Artist/{artist}"), 
         Description("Returns an Atom or RSS feed of albums by artist")]
 SyndicationFeedFormatter GetArtistFeed(String artist);

The return type of System.ServiceModel.Channels.Message is very generic and allows for you to simply build the response of a web request.  While generic and flexible, it does limit you by not allowing parameters on the REST uri.  In order to allow a SyndicationFeedFormatter return type, we must ensure that the service can serialize it as a result.  This is achieved by making it a known type for the service by decorating the interface as follows.

[ServiceKnownType(typeof(Atom10FeedFormatter))]
[ServiceKnownType(typeof(Rss20FeedFormatter))]

At this point, it comes down to dynamically formatting your response.  We do this by implicitly checking the Content-Type value of the request header in the body of our service methods.  Here is one example:

public SyndicationFeedFormatter GetGenreFeed(String genre)
{
    SyndicationFeed feed = CreateAlbumFeed(genre: genre);
    if (WebOperationContext.Current.IncomingRequest.Headers.Get("Content-Type") != null)
    {
        if (WebOperationContext.Current.IncomingRequest.Headers.Get("Content-Type").ToLower().Contains("application/atom"))
            return new Atom10FeedFormatter(feed);
        else
            return new Rss20FeedFormatter(feed);
    }
    return new Rss20FeedFormatter(feed);
}
 
 
This dictates how the feed will be formatted upon return from the function.  You can check the output using fiddler to see the message itself, as well as configure the content type for dynamism.



 Now we are able to browse to our URI and see a feed for all albums, albums by artist and albums by genre. 



The added ability to select the method in which the client consumes your feed is valuable to ensure all consumers are included.  Download the project here

Friday, June 29, 2012

Combo RESTful WCF with Windows Service Hosting and Dynamic Response Format

The Goal
I have been working through the plausibility of multipurpose WCF services that are hosted in a windows hosting environment.  As part of my research, I wanted to prove that you could host a single service as a standard service to be consumed by a client proxy and scale it out from there to webHTTP and RESTful behavior.  The biggest goal I had was to make the service dynamically reply in the same format in which it was consumed without having a drawn out implementation to handle the messaging.

The Project
After some reading and messing around I have completed the following project which does exactly what I had hoped.  This single WCF implementation will allow for a straight service call, a RESTful call and respond dynamically with xml or json to the REST query based on the content type value of the request header.  All while being hosted in a windows service that can be dynamically deployed.  I came up with a very simple project that allows for interaction with a listing of albums.  The example is simple, but the devil of this was not in the actual data elements, so I flagged the scalability of that as irrelevant to the goal of illustrating the mechanism.

The Services
I created a basic WCF service to perform CRUD on my album repository. You will notice the service decorations on the interface indicating both an operation contract and a WebInvoke/WebGet behavior and template.


[ServiceContract(Name = "AlbumContract", 
     Namespace = "RESTCombo.Services", 
     SessionMode = SessionMode.Allowed)]
public interface IAlbumSvc:IMetadataExchange
{
    [OperationContract]
    [WebGet(UriTemplate = "/Albums/{id}"), 
        Description("Returns the album with the passed ID")]
    Album GetAlbum(String id);
 
    [OperationContract]
    [WebGet(UriTemplate = "/Albums"), 
        Description("Returns the entire list of albums")]
    List<Album> GetAlbums();
 
    [OperationContract]
    [WebInvoke(Method = "POST", UriTemplate = "/Albums"), 
         Description("Adds a new album to list of albums")]
    void AddAlbum(Album album);
 
    [OperationContract]
    [WebInvoke(Method = "PUT", UriTemplate = "/Albums"), 
         Description("Updates an existing album")]
    void UpdateAlbum(Album album);
 
    [OperationContract]
    [WebInvoke(Method = "DELETE", UriTemplate = "/Albums/{id}"), 
         Description("Removes an album from list of albums")]
    void DeleteAlbum(String id);
}
 
The WebGet and WebInoke decoration allows the services to respond as a RESTful WCF service based on the URI template.  The service implementation should be decorated as follows:


[ServiceBehavior(Name = "RESTCombo.Services.AlbumSvc", 
    ConcurrencyMode = ConcurrencyMode.Single, 
    InstanceContextMode = InstanceContextMode.Single,
    IncludeExceptionDetailInFaults = true)]    
[AspNetCompatibilityRequirements(
    RequirementsMode=AspNetCompatibilityRequirementsMode.Allowed)]
public class AlbumSvc : IAlbumSvc

I'm going to skip posting the implementation of the services themselves as they are actually irrelevant to the discussion.  The entire project is attached at the end of the post if you would like to review the code.

The Configuration
While most of the configuration is fairly straight-forward, there are a couple of items worth pointing out.  Notice the multiple bindings for the single service.  Each must respond on its own port.  You can have as many bindings as needed up to one per protocol.  The webHttp endpoint behavior is vital to this mechanism.  helpEnabled allows users to use the '/help' switch at the end of a query to get a service overview page as shown here.


defaultOutgoingResponseFormat is our selection for the default response to a webHttp request. automaticFormatSelectionEnabled allows the response to dynamically detect the request format and respond in kind.

<?xml version="1.0"?>
<configuration>
  
  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/>
  </startup>
  <system.serviceModel>
    <services>
      <service name="RESTCombo.Services.AlbumSvc">
        <host>
          <baseAddresses>
            <add baseAddress="http://localhost:8080/AlbumSvc/" />
            <add baseAddress="net.tcp://localhost:2122" />
          </baseAddresses>
        </host>
        <endpoint  binding="webHttpBinding" contract="RESTCombo.Services.IAlbumSvc"
                  bindingConfiguration="RESTBindingConfiguration" 
                   behaviorConfiguration="RESTEndpointBehavior"/>      
        <endpoint address="net.tcp://localhost:2122/AlbumSvc/" binding="netTcpBinding"
                  contract="RESTCombo.Services.IAlbumSvc"/>
      </service>
    </services>    
    <bindings>
     <webHttpBinding>
        <binding name="RESTBindingConfiguration">
          <security mode="None" />          
        </binding>
      </webHttpBinding>      
      <netTcpBinding>
        <binding name="DefaultBinding">
          <security mode="None"/>
        </binding>        
      </netTcpBinding>
    </bindings>
    <behaviors>      
      <endpointBehaviors>
        <behavior name="RESTEndpointBehavior">           
          <webHttp helpEnabled="true" defaultOutgoingResponseFormat="Xml"
                   automaticFormatSelectionEnabled="true"/>
        </behavior>
      </endpointBehaviors>
      
      <serviceBehaviors>                        
        <behavior name="DefaultBehavior">
          <serviceMetadata httpGetEnabled="true" />
          <serviceDebug includeExceptionDetailInFaults="false"/>
        </behavior>       
      </serviceBehaviors>
    </behaviors>  
    <serviceHostingEnvironment multipleSiteBindingsEnabled="true" 
                               aspNetCompatibilityEnabled="true" />
  </system.serviceModel>
</configuration>

The Testing
We will just fast-forward through the hosting setup and service implementation.  Now that services are configured, built and running, we can perform the response testing and see how it all comes together.  When browsing to the webHttp base address and invoking the services via RESTful queries, I receive the following responses for the list and single respectively.




Then, to prove the JSON / XML switch, I used a fiddler software to create and review requests and responses.  First, I constructed an XML request and trapped the response.



Then, I constructed a JSON request and trapped the response.




As you can see, the service is responding to me in the request format.  For the client proxy implementation, review the source code attached at the end of the post.  The big victory here is the open and scalable approach to an SOA.  By doing dynamic communication in this manner, we are enabling a service to be consumed in the way that an integrator can best leverage.  This allows us to have a single implementation of intelligence and functionality while allowing any integrating software to choose the manner in which it interacts.  This is very powerful and very scalable and should allow your services to be consumer agnostic and focus strictly on intelligence.  For further review, download the entire project here.