Tuesday, October 30, 2012

Data Triggers with Knockout


Knockout and MVVM

Coming from a Windows application development background, I found the MVVM pattern one of the better UI design patterns. The basic idea is to separate your business logic (the 'M'), your view (the 'V'), and you view logic (the 'VM'). In this pattern, the view model works without every having to reference the view (your buttons and widgets). For example, instead of taking the EmployeeName field from your domain model and setting a label to that value, your view model would simply set a public property called EmployeeName. The view would then see that change and update the appropriate label on the UI. This cleanly separates your presentation layer from your domain layer. In order for this to work, there needs to be some mechanism for watching for changes to the view model, and updating the UI. WPF had that mechanism built in, but what about other technologies? Specifically, what about Javascript and web development? Enter Knockout.

Knockout allows you to declare data bindings between javascript objects and HTML elements. This can clean up your javascript code and allow for better separation between domain and view logic. Instead of taking a JSON object received by the server and writing code to save the domain object properties into the HTML elements, you can declare bindings between the domain object and HTML elements, and instead just set the properties on your domain object. Your javascript doesn't have to know the layout of the HTML or any other view knowledge. Please refer to the Knockout site for examples.

Data Triggers

Let's take this a step further and say you have a style called "Error" that changes a text box to indicate that there's something wrong with the data in it. Sticking with MVVM, a naive approach to solve this would be to have a property on your view model called TextBoxStyle and bind the style of the text box to that property. This isn't a good approach because your view model would have to have knowledge of the specific style needed, which isn't a concern of the view model. Another approach would be to write some custom code that watches for the view model to indicate there's an error with that field, and then set the "Error" style on the text box. This resolves the separation of concerns issue, but leaves us with writing custom code, which defeats the purpose of even using a data binding framework. One of the features that WPF gives you with respect to MVVM are Data Triggers. A Data Trigger is a way to tell the view that you want certain styles to be applied when a data condition is met. Knockout doesn't natively support data triggers, but writing an extension to provide that functionality is straightforward.

The general idea behind my solution is when a condition is met (trigger fired), record the previous HTML attribute values. When the condition is no longer met, (trigger reset) restore the original values. First let me show how one would use the trigger.
<button data-bind="enable: viewModel.canSave" 
  type="button" 
  disabled="disabled">
 <img src="~/Content/normal.gif" style="cursor: pointer;"
  data-bind="trigger: {
   condition: !viewModel.canSave(),
   attr: {
    src: '~/Content/disabled.gif'
   },
   style: {
    cursor: 'default'
   }
  }"/>
</button>


First, you would place your normal HTML attributes on the element. In the above example, we want the normal image to be shown. Then, when declaring the trigger, you specify the condition, and the new attributes and values that should  be set when the condition is met. In this example, we're setting a new disabled image and changing the cursor shown when the user mouses over the image. The script for the extension is shown below.
// trigger
//
ko.bindingHandlers.trigger = {
 update: function (element, valueAccessor, allBindingsAccessor) {
  //
  // First get the latest data that we're bound to and the target html element
  var value = valueAccessor();
  var jElement = $(element);

  // If the condition is met, replace the attributes and styles. Otherwise
  // restore the original values.
  if (value.condition) {
   if (value.attr) {
    for (var prop in value.attr) {
     if (value.attr.hasOwnProperty(prop)) {
      if (!element["_" + prop + "_"])
       element["_" + prop + "_"] = jElement.attr(prop);
      jElement.attr(prop, value.attr[prop]);
     }
    }
   }

   if (value.style) {
    for (var prop in value.style) {
     if (value.style.hasOwnProperty(prop)) {
      if (!element["__" + prop + "_"])
       element["__" + prop + "_"] = jElement.css(prop);
      jElement.css(prop, value.style[prop]);
     }
    }
   }
  }
  else {
   if (value.attr) {
    for (var prop in value.attr) {
     if (value.attr.hasOwnProperty(prop)) {
      jElement.attr(prop, element["_" + prop + "_"]);
     }
    }
   }

   if (value.style) {
    for (var prop in value.style) {
     if (value.style.hasOwnProperty(prop)) {
      jElement.css(prop, element["__" + prop + "_"]);
     }
    }                    
   }
  }
 }
};


Friday, February 24, 2012

Custom Errors in WCF REST Services - Part I

Support for REST in WCF has improved enough to make it a viable option for those wanting to expose a RESTful API to their services. Error reporting in such an API is something that should be thought through from the beginning. How will users be notified when something doesn't work right? Getting a consistent data contract for error messages that originate from your application isn't all that hard with a little custom behaviors. However, getting the same data contracts respected by IIS and WCF itself can be a bit of a trick. If you don't take care of all 3 (application, WCF, and IIS) layers, then your REST API response would be difficult to parse. I'm sure your API consumers wouldn't appreciate this:

HTTP/1.1 405 Method Not Allowed
Allow: GET, PUT, DELETE, POST
Content-Type: text/html
Server: Microsoft-IIS/7.5
X-Powered-By: ASP.NET
Date: Wed, 11 Jan 2012 02:48:21 GMT
Content-Length: 1293

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"/>
<title>405 - HTTP verb used to access this page is not allowed.</title>
<style type="text/css">
<!--
body{margin:0;font-size:.7em;font-family:Verdana, Arial, Helvetica, sans-serif;background:#EEEEEE;}
fieldset{padding:0 15px 10px 15px;} 
h1{font-size:2.4em;margin:0;color:#FFF;}
h2{font-size:1.7em;margin:0;color:#CC0000;} 
h3{font-size:1.2em;margin:10px 0 0 0;color:#000000;} 
#header{width:96%;margin:0 0 0 0;padding:6px 2% 6px 2%;font-family:"trebuchet MS", Verdana, sans-serif;color:#FFF;
background-color:#555555;}
#content{margin:0 0 0 2%;position:relative;}
.content-container{background:#FFF;width:96%;margin-top:8px;padding:10px;position:relative;}
-->
</style>
</head>
<body>
<div id="header"><h1>Server Error</h1></div>
<div id="content">
 <div class="content-container"><fieldset>
  <h2>405 - HTTP verb used to access this page is not allowed.</h2>
  <h3>The page you are looking for cannot be displayed because an invalid method (HTTP verb) was used to attempt access.</h3>
 </fieldset></div>
</div>
</body>
</html>

Part I - Application Generated Errors
Part II - WCF Generated Errors
Part III - IIS Generated Errors

Application Generated Errors
Making sure all of your services conform to the same error data contract is not difficult. WCF comes out of the box with the IErrorHandler extension interface which allows you the opportunity to handle and translate any faults that occur on a service. IErrorHandler has two methods to implement and mapping any faults to a custom error data contract can be done here.

One approach that I've seen work well is to have all faults in your application inherit from a base Fault that has useful properties for your API consumers. You can then use the different fault classes to convey any exception that your application might throw.
[DataContract]
public class FaultBase
{
    public FaultBase(string message, string code)
    {
        this.Message = message;
        this.Code = code;
    }

    public string Message { get; set; }
    public string Code { get; set; }
}

[DataContract]
public class ItemNotFoundFault : FaultBase
{
    public ItemNotFoundFault()
        : base("The resource item was not found.", "ItemNotFound")
    { }
}

Any exception caught by your IErrorHandler implementation can be translated into one of your faults and sent back to the caller. Nothing special here. I'm not going into a lot of detail on this because there are plenty examples of this on the web.

In Part II, I'll discuss how to handle errors generated inside WCF that don't get handled by the IErrorHandler implementation.

Custom Errors in WCF REST Services - Part II

In Part I, I discussed how to handle errors from your WCF services so that you can give your API users a consistent error result.

In Part II, I'll be discussing how to handle a few of those errors generated by WCF that don't get sent to your IErrorHandler implementation.

WCF Generated Errors
Handling the application errors will get you most of the way there. However, there are two cases where WCF will display that custom blue and white HTTP web page similar to what was shown above; 405 Method Not Allowed, and 404 Endpoint Not Found. These cases arise when WCF can't match the request with a service or a method. Unfortunately these errors don't go through the IErrorHandler interface, so you have to do something else to replace the output with your error data contract. I was pretty stumped on this one and had to resort to using Reflector, breakpoints, and stack trace examination to figure out what to do. There's a property on the DispatchRuntime called UnhandledDispatchOperation that WCF uses to dispatch operations that don't match an operation in your service. It's the IOperationInvoker instance stored in this property that is responsible for the blue and white HTML versions of the 405 and 404 responses.

The solution is to replace this instance with your own implementation that doesn't return HTML. The tricky part in writing the implementation is trying to determine whether to return a 405 or a 404. I'm guessing that it's possible to use the WCF API to figure out at runtime which case applies to the request. Rather than figure this all out, I cheated and just copied what the original IOperationInvoker instance did.
public class UnhandledOperationInvoker : IOperationInvoker
    {
        public object[] AllocateInputs()
        {
            return new object[1];
        }

        public object Invoke(object instance, object[] inputs, out object[] outputs)
        {
            outputs = null;
            bool uriMatch = false;
            Message message = inputs[0] as Message;

            if (message.Properties.ContainsKey("UriMatched"))
            {
                uriMatch = (bool)message.Properties["UriMatched"];
            }

            if (!uriMatch)
            {
                return new ItemNotFoundMessage();
            }
            else
            {
                return new MethodNotAllowedMessage();
            }
        }

        public IAsyncResult InvokeBegin(object instance, object[] inputs, AsyncCallback callback, object state)
        {
            throw new NotImplementedException();
        }

        public object InvokeEnd(object instance, out object[] outputs, IAsyncResult result)
        {
            throw new NotImplementedException();
        }

        public bool IsSynchronous
        {
            get { return true; }
        }
    }


Apparently something in the communication stack figures this out for us and saves this information in the current message's properties. Once you know which case applies to you, just return your standard error response appropriately. In my example, I'm returning an instance of one of my custom classes that inherits from System.ServiceModel.Channels.Message. This way I can control exactly the way the response looks. WARNING! Use the above approach at your own risk. Obviously it will stop working if a new version of .NET starts doing it differently.

In Part III, I'll discuss how to handle errors generated from IIS that don't get handled by WCF at all.

Custom Errors in WCF REST Services - Part III

In Part I, I discussed how to handle errors from your WCF services so that you can give your API users a consistent error result.

In Part II, I discussed how to handle a few of those errors generated by WCF that don't get sent to your IErrorHandler implementation.

Now that we've gotten WCF taken care of, there are even still some situations where an end user can get a bunch of HTML instead of a well formed XML response.

IIS Generated Errors
Now that we've gotten past WCF, there's one more layer that needs to be address. IIS has configuration settings that allow you to control the response that's given to a user for certain HTTP status codes. This might work for you, but if you need finer or programtic control, then you'll need to handle these errors yourself. A good example is the 500 Internal Server Error message. Let's say something in ASP.NET is misconfigured. In this scenario, IIS would give the end user an HTML 500 error. The approach I'm going to show for getting around this is for IIS 7.0. The idea is to write a custom IHttpHandler and tell IIS to route any IIS error to that handler. The handler can then return your custom error data contract to the caller. When IIS routes the request to your handler, it passes the error status code as a query string parameter. So all your handler has to do is parse this out and return the appropriate response.
public class ErrorHttpHandler : IHttpHandler
    {
        public bool IsReusable
        {
            get { return true; }
        }

        public void ProcessRequest(HttpContext context)
        {
            if (context.Request.QueryString.Count == 0)
                return;

            string strStatusCode = context.Request.QueryString[0].Split(';').FirstOrDefault() ?? "500";
            int statusCode = 500;
            int.TryParse(strStatusCode, out statusCode);

            string message = "Unhandled server error.";

            switch (statusCode)
            {
                case 400:
                    message = "Bad request.";
                    break;

                case 404:
                    message = "Item not found.";
                    break;
            }

            context.Response.StatusCode = statusCode;
            context.Response.Write(string.Format("<Error><Message>{0}</Message></Error>", message));
        }
    }

The above implementation is only to get you started. The last step is to configure IIS to forward errors to your handler.

<system.webServer>
    <httpErrors errorMode="Custom">
      <clear/> 
      <error statusCode="404" path="/application/ErrorHandler" responseMode="ExecuteURL"/>
      <error statusCode="400" path="/application/ErrorHandler" responseMode="ExecuteURL"/>
    </httpErrors>
    <handlers>
      <add name="ErrorHandler" path="ErrorHandler" verb="*" type="Your Application.ErrorHttpHandler, FrameworkAssembly"/>
    </handlers>
  </system.webServer>

The worst part of this approach is that you have to explicitly define which HTTP response codes you want to handle in your handler. It is possible to have a catch all, but doing so requires you to override the system configuration for IIS and I didn't have much success getting that to work on my machine.

Friday, January 20, 2012

White Elephant Planning

In a previous post, I discussed an agile estimation method called the White Elephant method. In that post I discussed some concerns that I had on it, but also noted that these concerns were not founded by any actual experiences with the method itself. Now that I've actually been a part of one, I wanted to share some things about it that I noticed.

Background
In my environment, we have 5 teams of approximately 7 people. Our product owner wants to have a single backlog for all teams. In order to fill out the backlog for the next release, we held a story estimation workshop that consisted of a representative from each team, plus the product owner. The product owner (along with some help) prepared by creating around 40 stories with descriptions and acceptance criteria. We time boxed the meeting at 3 hours and had lunch catered so we wouldn't have to stop. We usually went for about 45 minutes at a time with a 15 minute break in between.

The Game
Out of the 3 hours, we probably spent a little over 2 hours actually estimating (we started late, had some issues with lunch, etc). The product owner was hoping to get at least half of the 40 stories estimated. As it turned out, we got them all done! Just based on that alone, I would consider the exercise a complete success.

Moderation
I have to say right off that in order for this to work well, you must have a good moderator. Fortunately, we had someone that had done this before and he did an excellent job. He had a stop watch running on his phone and reset the timer each time a new story was selected. Once the timer reached about 4 minutes, he would let us know and try to push the current player to park his story in the 'Parked' column for later discussion so we could move on. Without this type of moderation, we could have talked on and on and the whole exercise might not have been as successful as it was.

Less Discussion
There were several occasions where a player muttered under his breath when it was his turn that he didn't agree with the placing of a previous story but decided not to use his turn to move it because he didn't want to re-open the discussion again. This only happened when there a one point difference between what the story was currently estimated as, and where the player thought it should be. This was interesting to me because not only did we cut down on more discussion, but the player immediately recognized the cost of such discussions and decided that it wasn't worth it over a one story point difference. I struggle with my own team on this sometimes. I don't like having to remind team members during planning that while the discussion they're having about the story is important, it's not going to make any significant difference in the planned estimate and should be taken offline. I really like seeing the player come to this conclusion on their own with the White Elephant method.

Tuning Out
I'll be the first to admit, that it was easy to tune out. When it wasn't my turn, I caught myself several times paying less attention to the current discussion of a particular story. Once the story was placed on the board, I really didn't know much about the story and therefore wasn't able to contribute to its estimate. It was too easy to just say, "I'll be happy with whatever he thinks it is." Since this was the first workshop for us, it consisted of all team leads, so most of us had strong opinions about the stories. I see the tuning out problem being more wide spread on teams with members that just go with the flow more. Planning Poker requires the team member to decide on a number, and then possibly defend it if it doesn't match the rest of the team.

Conclusions
I was surprised to find that some of the things I thought were going to be issues were not at all. Anchoring wasn't a problem for us. Players regularly took a turn to move an estimate and would confidently say, "No way this is a 3 because...". Then again, that might be due to the combination of personalities in the room. I also didn't find changing the discussion from story to story to be a problem. I never once felt that it impeded my ability to estimate.

Once of the biggest things I took away from this is that most of the positives I saw could be easily applied to Planning Poker. Timing story discussions, parking stories that take too long, visually seeing the stories and where they're placed in relation to each other. I'm definitely going to apply some of those things in my next planning meeting with the team.

Wednesday, January 18, 2012

Code Presentations or Code Reviews

When I sit down and participate in a code review, I get annoyed when the person who's code I'm reviewing just sits back and says "Here you go, have at it." That communicates to me that they are not a participant in the review and they're not taking pride in their work. When someone sits down to review my code, I actually prepare for the review and I think a moment about the best way to present it to them. I almost feel like I'm trying to sell my code to them, although I recognize that it's not about "selling" anything, but sharing knowledge and finding alternative solutions. I am more in the driver seat when someone is reviewing my code because I'm interested in their input and want to know if they see any problems. Part of the problem with poorly executed code reviews may be because they're one sided, and thus the concept of what a code review is and why we have them is not in line.

I'm going to throw myself out there and ask, what if I called it a Code Presentation? That puts more emphasis on the person who wrote the code than the person reviewing it. If someone were to say "Hey, can you come by so I can present my code to you?", they may prepare a little more and think more about how the code looks to an outsider rather than just getting the code to work.

I know, words are words. What you call something doesn't change what it is. I can call the chair you're sitting on an ice-cream cone if I wanted; it's still a chair. However, what you call something may change the perception of what it is, even though it's still the same thing. That change in perception may be enough to close the gap on the reason behind code reviews.

Dumb? Interesting? Pointless? I'd like to know your thoughts on this.

Friday, January 13, 2012

Alternative to Planning Poker

I recently came across an agile estimating method called the White Elephant method that is designed to speed up agile estimation. One of the complaints that new practitioners have when it comes to Agile is that planning takes too long. I definitely agree with this and have seen new teams plan well into 3 days for a 3 week sprint. If your team is having this problem, you might consider the White Elephant method.

Quick Overview
You can read the link above to get a good idea of how this works. In short, you do the following until all of your stories are estimated.
1. Create categories on a white board to represent each of the story point values (0,1,2,3,5,8,etc.).
2. The first person takes a story from the pile and places it on the board in the category that represents their estimate.
3. The next person can either change an existing estimate by moving a sticky on the board to another category, or select a new story from the pile and place it on the board.
4. The next person takes a turn and so on, until all stories are on the board and the team has consensus.
5. If a story is moved too many times (say 3 times), the story goes into a Discuss category.
6. At the end, any stories in the discuss category are discussed and eventually placed on the board.
The main idea is to get points on the stories that don't require much discussion first, then discuss the ones that may require clarification second.

My Thoughts
First off, I have to say that I have not yet taken part in this yet. Anything I have to say on this is really just my hypothesis. 
1. Anchoring - One of the things I like most about Planning Poker is that everything presents their estimate at the same time as to avoid any anchoring that might occur. That's why we do planning poker. I don't want my estimate to anchor the next guys one way or the other. This is especially true in teams where one or two people have stronger personalities than the rest and are more assertive in what they think. The White Elephant method allows one guys estimate to be swayed by what he sees on the board and the quieter folks on the team may be more inclined to just "go with it".

2. Go with the Flow - I have a lot of respect for people that are able to go with the flow. However, I don't like those folks during planning meetings. As a team lead, I make it a point to ask those people what they think because it's all too easy for them to just sit quiet and do what everyone else is doing. The White Elephant method makes it way too easy for quiet, go with the flow types to go along just for the ride.

3. Story Switching - It seems to me that switching back and forth between stories is going to make it more difficult for the team to really figure out what size the story is. Collective thinking on one subject matter is better than everyone thinking separately (which is why the 6 Thinking Hats retrospective is so effective). If the team keeps switching between stories, it seems like it would make it harder for team members to retain the whole picture on a particular story.
I think this type of planning will work, it just depends on what team you have and the mix of personalities on the team. I can see some benefits to this type of planning though:
1. Good Visual - I really like the way the stories are put on the board next to each other. It really reminds the team how relative this type of estimation is. It's hard sometimes to remember that you're really just trying to figure out how big a story is compared to the other stories. Seeing all of the stories together really drives this home. This is something I'm definitely going to go in my next planning poker meeting. After each story is estimated, put it on the board in a category.

2. Reduces Discussion - There's good discussion, and bad discussion. Anything that helps decide if a story is a 5 or a 3 is good discussion. Everything else is bad. I can really see how this type of planning game could reduce the bad discussion and promote the good discussion. Since only the person taking a turn can ask questions, it reduces the amount of cross talk that is prone to happen when playing planning poker.

Once I've actually experienced this approach, I'll let you know how it goes.

UPDATE: I've since experienced this particular estimating method and have written about it here.