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.

Friday, March 29, 2013

iOS home screen icons for web apps

Since a lot of us are trying to create more dynamic web content for consumption on mobile devices, we find ourselves moving away from native applications and toward responsive design in web applications. One of the small items that can make these web applications feel more like the native app that users download from the iOS store is to create a proper home screen icon.  This is the icon that stays on the home screen of the iOS device when a user creates a shortcut. This is easily handled and can actually be designed for specific devices using nothing more than your markup.  This is accomplished by creating icons of differing resolutions using a standardized naming convention that will be natively referenced and leveraged by the iOS device as part of the shortcut making process.  

One of the cool things that iOS does for you is add rounded corners, shine and drop shadows to your icon in order to ensure some level of short cut consistency. All you need to do there is create you icon without making an attempt at any of those effects.  If you consider yourself a graphic artist and want to do your own effects, just append append the -precomposed keyword to the end of the file name when you create your icon.  This will instruct the iOS device to not apply the native effects it has.  The only thing left at this point is to copy the files to the root directory of your web applications domain with the following naming scheme intact.

File Name Size Device iOS adds effects
apple-touch-icon.png Any Any Yes
apple-touch-icon-precomposed.png Any Any No
apple-touch-icon-57x57.png 57x57 Touch Yes
apple-touch-icon-57x57-precomposed.png 57x57 Touch No
apple-touch-icon-72x72.png 72x72 iPad Yes
apple-touch-icon-72x72-precomposed.png 72x72 iPad No
apple-touch-icon-114x114.png 114x114 Retina Yes
apple-touch-icon-114x114-precomposed.png 114x114 Retina No
apple-touch-icon-144x144.png 144x144 Retina Yes
apple-touch-icon-144x144-precomposed.png 144x144 Retina No

This mechanism is flexible enough to allow individual pages to set their own icons via markup as well. Here is an example of targeted icons per device with the following code added to the individual page(s).

 <link rel="apple-touch-icon" href="/icon.png"/>  
 <link rel="apple-touch-icon" href="iphone-icon.png" />  
 <link rel="apple-touch-icon" sizes="72x72" href="ipad-icon.png" />  
 <link rel="apple-touch-icon" sizes="114x114" href="iphone4-icon.png" />  
 <link rel="apple-touch-icon" sizes="144x144" href="ipad144-icon.png" />  


Now, when a user on an iOS device creates a shortcut to this web application or a specific page, they will get a nice looking, branded icon that represents the application well and gives the user a native feel for launching their application.

Tuesday, March 26, 2013

Parse claim from STS in .net 4.5

When creating an asp.net 4.5 web application that is acting as an RP to an STS system, you may be fine checking the User.IsInRole("WtEv") functionality provided from WIF. If you find yourself needing to parse an individual value for some other reason, the code is a bit more sketchy. Following is a snippet to parse individual claims from a ClaimsPrinicpal inside of an RP using STS.

ClaimsPrincipal claimsPrincipal = HttpContext.Current.User as ClaimsPrincipal;
if (claimsPrincipal != null && claimsPrincipal.Identity.IsAuthenticated)
{
  try
  {
       string CustomerID = (from c in claimsPrincipal.Claims where 
           c.Type == "http://devstorm.blogspot.com/claims/CustomerID" 
           select c.Value).Single(); 
 
       string Protocol = (from c in claimsPrincipal.Claims where 
           c.Type == "http://devstorm.blogspot.com/claims/Protocol" 
           select c.Value).Single(); 
 
       string ApplicationServer = (from c in claimsPrincipal.Claims where 
           c.Type == "http://devstorm.blogspot.com/claims/ApplicationServer" 
           select c.Value).Single();
  }
  catch (InvalidOperationException)
  {
    // handle claims not existing
  }
} 

Tuesday, March 12, 2013

The argument for coding standards



Creating and enforcing coding standards, or coding style guidelines, is one method by which software companies can ensure that source code written by a software developer is easily understood, while being maintained by any other software developer in their employ.  Smashing Magazine contributor Nicholas C. Zakas penned an article titled, “Why Coding Style Matters”, illustrating the value realized by creating and adhering to coding standards.  He states that standards ensure individual members of a development team are able to tailor the visual appearance of their source code while still allowing their individual talents to flourish.  Standardized coding style also ensures better communication between team members by allowing the product of work to act as a form of documentation for the creators to leave clues for themselves and for others who come after.  Potential programming errors are more easily identified when a group of programmers adheres to a coding standard since any code that does not comply becomes more visible and draws scrutiny of other developers.  Standardizing the code comment, which is a way for developers to create non-executing code strictly designed for inter-developer communication, is a good way to ensure other engineers are able to understand why code was written in this specific way to accomplish the known task.

Zakas begins the article by discussing his own introduction to coding standards as a student in college.  One of his professors considered the style with which code was written equally as important as the execution of the code.  His definition of coding style is insightful as it illustrates that the standard can be as generalized or granular as the creator desires.  All individual developers inherently have a coding style, whether formalized and forced or inadvertently formed in seclusion over time. The biggest challenge with a standardized style to a creative group, he states, is the undeniably personal nature of any style.  Mr. Zakas created a memorable simile regarding individual musicians in a band.  While all of the musicians have a talent on their instruments, unless they are orchestrated in some fashion beyond their individual creative style, the music they produce will not likely be enjoyable to the listener.  The structure provided by band governance for items such as tempo, key, and lead timing, ensures a quality musical product without forcing the conformance of individual creativity.  That is exactly the marriage of the individual dynamic within a team structure that is required.  Prior to enforcing standards, you have to understand the challenges and resistance will be based on individual styles and creativity being 'standardized'.  It is vital to communicate that coding standards and style guides do not throttle creativity or individualism, they simply channel it into a team effort and ensure forward progress.

Communication is a natural and valuable byproduct of coding standards.  Most communication within a group of developers is resident within the source code itself.  The output of any developer’s daily work is a complete, exhaustive, and readable trail of every task he or she executed.  When one developer reads the source code created by another developer, the original developer’s view of the problem, strategy to correct it, and final solution are communicated to the second via the code itself. Once you reach this realization alone, it indicates the need for standardization.  The code communication is also useful for developers to leave clues for themselves in the future.  It is equally important for the author of the code to understand that he may need to maintain a creation of his own in the distant future.  Intellectual breadcrumbs and standardized formatting will ensure that old code and new code look the same to the maintaining programmer.

Coding standards bring potential software errors into view more easily.  As programmers become more acclimated to specific patterns, they will more naturally notice code that does not adhere.  This ultimately draws the attention of programmers and causes them to consider the segment of code more closely, as it is an anomaly.  Since the coding standard itself is designed to enable consistently stable source code, one must focus on which items to standardize with direct intent.  You will probably not find a coding style guide with too much detail, but can find them with too little detail.  The importance in your level of detail is based on the importance of ensuring items that are standardized are complete and targeted at specific items important to the individual team.  In other words, its not a good idea to standardize every aspect of development, just for the sake of doing it.  You should focus on standards as they align with your business need and allow the developers to leverage their creativity and talent within the style guide.

Monday, March 4, 2013

Websocket Demo

Here is a small sample to illustrate interacting with a websocket service using javascript.  I found the running echo service online at websocket.org.  The functionality of this service is that you send it a message and it sends the data back to you using the websocket events.   This sample code just spins off a few calls to the service (using milliseconds as differentiation) and writes the responses out to the document.  It is pretty straight forward, but does give you a working example.

The javascript:
   var wsUri = "wss://echo.websocket.org/";  
   var output;  
   function init() {  
     output = document.getElementById("output");  
     testWebSocket();  
   }  
   function testWebSocket() {  
     websocket = new WebSocket(wsUri);  
     websocket.onopen = function (evt) { onOpen(evt) };  
     websocket.onclose = function (evt) { onClose(evt) };  
     websocket.onmessage = function (evt) { onMessage(evt) };  
     websocket.onerror = function (evt) { onError(evt) };  
   }  
   function onOpen(evt) {  
     writeToScreen("CONNECTED");  
     var text = new Date();  
     doSend(text.getMonth() + 1 + '-' + text.getDate() + '-' + text.getFullYear() + ' at ' + text.getMilliseconds());  
   }  
   function onClose(evt) {  
     writeToScreen("DISCONNECTED");  
   }  
   function onMessage(evt) {  
     writeToScreen('<span style="color: blue;">RESPONSE: ' + evt.data + '</span>');  
     setTimeout(onOpen(), 1250);  
   }  
   function onError(evt) {  
     writeToScreen('<span style="color: red;">ERROR:</span> ' + evt.data);  
   }  
   function doSend(message) {  
     writeToScreen("SENT: " + message);  
     websocket.send(message);  
   }  
   function writeToScreen(message) {  
     var pre = document.createElement("p");  
     pre.style.wordWrap = "break-word";  
     pre.innerHTML = message;  
     output.appendChild(pre);  
     if (output.children.length > 20) {  
       websocket.close();  
     }  
   }  
   window.addEventListener("load", init, false);  
The page:
 <h2>WebSocket Test</h2>  
 <div id="output"></div>    

Thursday, February 28, 2013

Using MVC style controllers in ASP.NET WebForms with AJAX

I have been working on a project that is based in ASP.NET web forms recently with the knowledge that a near-future generation of this software will be created using MVC.  Always trying to find a way to share code and create leverage with solid SOA design, I decided to drive the ASP.NET application from controllers interacting with services.  By doing this, I am am assuring that not only the service layers are portable to other platforms, but that the controllers can be reused as well.  This gives us another layer of code reuse and a mechanism to limit the testing requirements on the future application.  The first step is to integrate the MVC references into your ASP application.  In order to do this, you must add the references to your project and include them in your web.config as follows.


Next, we have to make sure that our routes are created using the MVC 'magic'.  This is accomplished with a global.asax file executing the .net map paths functionality.  This is done via a single method call at the start of the application as illustrated below.
Code:
public class Global : HttpApplication
{
    protected void Application_Start(object sender, EventArgs e)
    {
        RouteTable.Routes.MapRoute(
            "Default",
            "{controller}/{action}/{id}",
            new {id = UrlParameter.Optional}
         );
    }
}

At this point, we are able to add controllers to interact with our data. The controller classes must be inherited from the Controller object. Once this class is stubbed in, you are able to simply frame in your methods to interact with the data as needed. Here is an example of a controller class.
Code:
public class TaskController : Controller    
{

    /// <summary>
    /// Completes the task.
    /// </summary>
    /// <param name="taskId">The task id.</param>
    /// <returns></returns>
    public ActionResult CompleteTask(int taskId)
    {
      
        try
        {
            MyTask data = ***service call to complete task and return updated data
            return Json(data, JsonRequestBehavior.AllowGet);
        }
        catch (Exception ex)
        {
            return Json("");
        }
    }

    /// <summary>
    /// Get a list of tasks.
    /// </summary>
    /// <returns></returns>
    public ActionResult TaskList()
    {
       
        try
        {   
            List<MyTask> tasks = *** Service call to get task list.

            return Json(tasks, JsonRequestBehavior.AllowGet);
        }
        catch (Exception ex)
        {
            return Json("");
        }
    }
}

The last step is to simply consume these controllers via AJAX calls in your client.
Code:
function loadTasks() {
    
    $.mobile.showPageLoadingMsg();
    var request = $.ajax({
        url: "/Task/TaskList",
        type: "POST",
        data: {},
        context: this
    });

    request.done(downloadDone).fail(downloadFailed).error(downloadError);
}

function downloadDone(responseData) {

    $.each(responseData, function (i, obj) {
         // do something with each task from the list by using obj.* to reference values.

    $.mobile.hidePageLoadingMsg();

}
function downloadFailed() {
    alert("Could not retrieve task data at this time.");
    $.mobile.hidePageLoadingMsg();
}

function downloadError(error) {
    $.mobile.hidePageLoadingMsg();
    console.log(error);
}

At this point, I can add controllers that represent my service interaction layer, and then simply reuse them when the application is migrated to MVC. This gives us the ability to separate the actual presentation layer from its interaction with the services and target that logic for reuse.