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.

Friday, February 15, 2013

Azure Media Services

Microsoft has added more offerings to the already large catalog of Azure services.  Recently, they announced the launch of Azure Media Services which allows you to upload, encode and deliver streaming media content to a vast array of consuming devices.  Historically, we have had to partner with other vendors to provide the streaming media while leveraging Azure services to deliver our applications.  With this offering, it seems that you could simply partner with Microsoft and allow Azure to fulfill all of the needs you may have to deliver your assets to virtually any device.  While this offering is fairly new, I have gathered the following information.

Answering the Common Questions


1. Protection.  One of the first items people always bring up when building a streaming solution is the protection of assets.  Azure allows you to store and deliver content in a secure fashion by leveraging either Microsoft PlayReady DRM or Apple AES.  

2. User experience.  We are all concerned about ensuring that our content is seen in the best light possible at all times.  Azure Media Services offers the ability to not only encode your media into a large range of standard codecs and adaptive bitrate formats, but to also create an adaptive delivery experience by allowing on-the-fly format conversion.  Your content can be streamed to Windows 8 applications, Windows Phone applications, Browsers (via Silverlight), iOS devices and android devices which covers a large majority of consumer need.

3. Development.  Generally, your streaming partner provides some flavor of SDK for interacting with their service as part of your application development and deployment.  One of the huge by-products by partnering with Azure for this type of application is that their services are native and integrated into the rest of your Azure platform. You can program Media Services using the OData-based REST APIs. You can build an application making REST API calls to Media Services from .NET languages or other programming languages. You can easily deliver your content to devices such as connected TVs, set-top boxes, Blu-Ray players, OTT TV boxes, and mobile devices that have a custom application development framework and a custom media pipeline.  Microsoft provides porting kits (for a fee) that allow you to code to the smooth streaming platform.

4. Ads.  Yes, you can integrate ads into your product using overlays.  This allows you to have both paid and free versions of your application if so desired.

At a glance, this seems pretty powerful.  I am going to dive in and investigate at a more detailed level to see what kind of possibilities this may offer moving forward.

Monday, February 4, 2013

Authorization Using WIF 4.5

I'd like to continue the topic of claims-based security using WIF 4.5, and talk about the authorization model and its options at a deeper level. First, just to ensure we are all using the same terminology when discussing items, I want to clarify "authorization" when I use it in this context. Authorization and authentication are still widely confused when discussing overall security methodology. They are both aspects of security, but they play completely different roles in the process.

Authorization vs. Authentication

Authentication is really just the process of having users log in so you can ensure they have the right to access the application. Authentication is the concept at work when you log in to any web application at all. By having an approved and active user account, and entering the proper credentials, the user is authenticated to use the application. In most cases, users are authenticated prior to authorization.

Authorization is the mechanism by which we evaluate whether an authenticated user has access to a specified modality (url, service, module or data element) within the application to which they are authenticated. For instance, an authenticated user may be an administrator which makes them authorized to change settings, post content, etc. While another authenticated user may be a guest, which makes them authorized to read public content. In its most simple form, authentication is who you are and authorization is what you are allowed to do.

Claims-based Authorization

As we discussed before, claims-based authorization is the approach where you write code to allow or disallow access based on logic that checks data called 'claims'. Remember that in the case of a role-based authorization, the only claim we actually used was the claim a user made about his or her roles. A role claim was used for us to decide if the current user 'is a' specific role. Let's walk through making access decisions using a claims-based authorization approach.
  1. A user arrives at your application and needs to be authenticated.
  2. WIF forwards the user to your identity provider.
  3. Once the user is authenticated, the original request is made again, but now there is a new security token attached to the request which contains data representing the user by using claims representing each granular piece of data. WIF attaches these new claims to the principal that represents the user so it can be referenced quickly and easily.
  4. Your application checks the claims via code to ensure the claims are met. These checks can be made via code, service calls, database, home-grown rules, or the native ClaimsAuthorizationManager.
  5. Your application decides whether or not to allow the request based on the claims:logic check.
  6. Your application grants the request if the outcome of your check is true and denies it if false.
The ClaimsAuthorizationManager is a new tool in WIF 4.5 that seems to be useful for black-boxing the logic for any claims-based authorization in your applications. It allows you to sniff incoming requests and wrap access with a check to custom logic which will then make authorization decisions based on the incoming claims. Much like any other good design principle, abstracting your authorization logic can only add to your applications ability to be dynamically responsive to changing authorization requirements. If you have to customize or change your authorization rules, using ClaimsAuthorizationManager will not affect the core application code base. Anytime you can separate logic into a stand-alone process and create a producer-consumer relationship, I think you are creating dynamism in the application. This is just another means for injecting flexibility to potentially deal with unforeseen changes without degrading the 'meat and potatoes' of your application. The ClaimsAuthorizationManager appears to be a great opportunity to allow authorization to be black-boxed inside a singularly purposed service entity, which can position your application to leverage centralized logic in this area.

Role-based Authorization

Role-based authorization is implemented by assigning users to user roles that have been defined for the application. This is the example that I used when talking about an administrator or a guest. Both of those are considered roles. When using this methodology, users are assigned 1:n roles within the system which can be checked at run time for derivation of access rights. You can check the roles of the user in a few different ways to ensure they are authorized for access. 
  • Checking IPrincipal.IsInRole(“RoleToCheck”). This is probably the most straight-forward and widely-used method. Since it returns a boolean indicating membership in the role, you can use it in your conditional statements at any place in your code as a security check.
  • Using PrincipalPermission.Demand(). When you make the Demand() call, the application will throw an exception if the demand is not met by the roles. This flows into standard try-catch-finally blocks and makes authorization just another exception in the block. Be warned that exceptions are much more expensive from a performance standpoint when compared to the IsInRole() method.
  • Using the <authorization> section in web.config. This really only works if you are blocking entire URLs against roles. This is the most strict, blanket level authentication so far. The upside is that it requires no code changes for implementation since it is part of the configuration file.
  • Using [PrincipalPermission(SecurityAction.Demand, Role = “RoleToCheck”)] attributes. The declarative method cannot be used in code blocks or within the service/method implementations as it is an actual attribute of the method itself. The method will throw an exception if the authenticated user doesn't belong to the role being demanded.
As mentioned above, when you call the IsInRole() method, the system checks behind the scenes to see if the current user has that role. In claims-aware applications, the role is expressed by a role claim type that should be available in the token. When a user is authenticated, the role claim can be issued by the identity provider STS or by a federation provider such as the Windows Azure Access Control Service (ACS). You can also turn arbitrary claims into role-type claims using the ClaimsAuthenticationManager component of WIF. This allows requests to be intercepted when an application launches, allowing you to inspect the tokens and even transform them by adding, changing or removing claims.

Monday, January 28, 2013

Claims-Based Identity and Authorization

As a follow-up to the previous post about security, I am examining a claims-based security model within WCF using the Windows Identity Foundation (WIF). In a claims-based application, a user is represented by a set of claims. The basic idea is that an external service is configured to give you any relevant information about the user as part of each request. This also includes some assurance that the identity data you receive comes from a trusted source by using some flavor of cryptography. This really flows into a good SOA design because you are basically decoupling your application from the logic of authentication, the storage and protection of user names, passwords and emails, and forced integration with in-house identity systems. In a claims-based paradigm, your application is making decisions for access and security using information from the authenticating system.

Claims

Claims are really just pieces of data associated with the currently authenticated user. These 'claims' from the authenticating service can consist of items such as the user name, email, security group membership, etc. When your application receives these claims, it enables you to cater the availability of content to the authenticated user. A very important point on which to be clear is that the claims made from the issuing service are only as trustworthy as that service itself. For example, you trust a claim made by your company’s domain controller more than you trust a claim made by, for example, Facebook. In that regard, WIF represents claims with a Claim type, which has an Issuer property that allows you to find out who issued the claim.

Tokens

The user delivers a set of claims to your application along with a request. In a web service, these claims are carried in the security header of the SOAP envelope. In a browser-based web application, the claims arrive through the HTTP request from the browser. The claims, regardless of the arrival method, are serialized, which is where why we need security tokens. A security token is really just a serialized set of claims that is digitally signed by the issuing authority. The signature is needed because it guarantees the issuing authority has generated the attached claims, which validates their authenticity. In other scenarios where that kind of security isn’t needed, you can use unsigned tokens. One of the core features in WIF is the ability to create and read security tokens. WIF and the .NET Framework handle all of the cryptographic work, and present your application with a set of claims that you can read.

Relying Party

When you build an application that relies on claims, you are building a relying party (RP) application. Synonyms for an RP include “claims-aware application” and “claims-based application.” Both web applications and web services can be RPs. An RP is nothing more than a consumer of tokens issued by an STS who reads the claims from tokens for use in security or access as it relates to the identity of the user. WIF offers inherent functionality to help you build RP applications.

Issuing Authority

It seems there are endless types of issuing authorities, but we really want to focus on security tokens that contain claims. This issuing authority is another application or service that is tasked with the issuance security tokens. This logic is responsible for having the insight needed to be able to issue the proper claims given the specific application and the user making the request, and might ultimately just be a pass-through to other services to receive claims and authenticate users.

Security Token Service (STS)

A security token service (STS) is the service that creates, signs, and issues any security tokens based on the WS-Trust and WS-Federation protocols. These protocols are really difficult to implement on a stand-alone basis, but WIF seems to handle the vast majority of this work. It appears that it is much easier to get STS up and running by leveraging WIF. You can use a pre-built STS such as Active Directory® Federation Services (AD FS) 2.0, a cloud STS such as a Windows Azure Access Control Service (ACS), or, if you want to issue custom tokens or provide custom authentication or authorization, you can build your own custom STS using WIF. The following is an example from Microsoft of a claims-based system.

Relying Partner Authentication Flow
This diagram shows a Web site (the relying party application, RP) that has been configured to use WIF for authentication and a client, a web browser, that wants to use that site.
  1. When an unauthenticated user requests a page their browser is redirected to the identity provider (IP) pages.
  2. The IP requires the user to present their credentials, e.g. username/password.
  3. The IP issues a token back to that is returned to the browser.
  4. The browser is now redirected back to the originally requested page where WIF determines if the token satisfies the requirements to access the page. If so a cookie is issued to establish a session so the authentication only needs to occur once, and control is passed to the application.
It seems that leveraging WIF as an STS provider is an easily achievable way to use a secure and standardized methodology of application security.