DevLink 2012 In Review

This year I had the chance to attend the DevLink conference in Chattanooga, TN.  DevLink is a Codemash like event which brings together developers from all areas for the purpose of knowledge sharing.  I had the chance to attend some amazing sessions, I would like to highlight some of my favorite moments.

XAML vs HTML5

Two of my good friends Michael Eaton and Jason Follas presented a demonstration of creating a blackjack game in both Xaml and HTML5.  This was very interesting, first because I am always amazed at the skill level of my peers and Mike and Jason are no exception.  The way they were able to demonstrate what these two powerful platforms can do in capable hands was exceptional.  Really shows you that Xaml can easily compete with HTML5 in terms of what it can do, the only difference, of course, is HTML is ubiquitous, whereas Xaml is not.

iOS UX Secrets

I am always looking to expand my knowledge in the iOS arena as it is an area that is vital to my future as a mobile programmer.  Regardless of whether or not Windows Phone eventually takes off, iOS will remain a dominant player for many years to come.  Surprisingly though, much of the effects demonstrated here were aimed at helping developers mimic the UI style of Windows Phone on iOS.  I also learned that Apple is continuing to strive to bring Objective-C up to par with existing modern languages, including adding features that other languages have enjoyed for years.

JavaScript Async Patterns

I wont lie, this was my absolute favorite talk on the entire confidence.  Presented by Jim Cowart from @appendTo (the jQuery company) I finally got to see Deferreds and Promises in action with JavaScript and what an absolutely mind-blowing experience.  Along with learning about Event Emitting and Postal.js I finally have tools in my tool-chest to handle the annoying problem of wanting to effectively synchronized threads.  This new approach will totally change the way I write complex Ajax applications.  I was so happy to learn about this.  Combined with Knockout and Node.js I can finally start to dive into real SPAs (Single Page Applications).

RESTful APIs

Another big part of SPAs is the development of REST APIs to serve as the data layer for applications.  The trend seems to be creating small HTML pages and using JavaScript and the myriad of libraries available to bring in content.  This plus the rise of mobile as a competing platform with the traditional desktop is leading to the importance of your content being delivered in ways not tied to your application.  This sessions focused on using ASP .NET Web API to do this.

Entity Framework v5.0

While the prevailing thought of many seems to be that EF is dead, it doesn’t seem that way as Microsoft continues to push forward with developing additional features into the framework and making it better.  I believe that Microsoft will eventually own this domain though, some kinks to work out as the demos for this particular session did not work as expected.

What I learned

As a developer we know that JavaScript and REST are likely the two biggest topics out right now.  No surprise as, along with HTML5 and Node.js, these are important tools for creating the next generation of web applications.  Cloud computing is also becoming huge as a way to quickly deploy simple and moderately complicated applications.

It was nice to see a ton of love for Windows 8 at the conference, but this remains a rather divisive topic even among Microsoft developers.  There are many who believe it will fail and many who believe it can succeed.  Some who view 8 as a stepping stone for 9 which will ultimately lead to the win for Microsoft.  It really is an interesting dynamic and I am constantly amazed at how visceral things have gotten in the mobile computing space between the fans of the three companies (Google, Microsoft, and Apple).  Some great conversations were had, I think the distribution of thought is pretty even among the succeed fail line.  It will be interesting to see what happens.  As for me, I intend to install Windows 8 as soon as possible.

Why Windows Phone will succeed… eventually

I should preface this with two points: 1) I am not referring to any specific version of Windows, so do not assume I am talking about 8 in particular 2) when I say succeed I am referring to it becoming competitive against the two major players Apple and Google.  This is not meant to be troll bait or Apple/Google bashing.  This is also not intended to be a glory post for Microsoft.  This is a serious effort to look, objectively, a the overall situation in the consumer smartphone market for Microsoft.

Attending DevLink I got to have this conversation many times, and I got to hear many people who supported it as well as those who disagreed with this assertion.  Here is my point so long as they can continue to compete Microsoft will try to break into this market and they will eventually succeed. To those who immediately discount their chances, I remind you that people said the same thing about their chances in the gaming console market, where the XBox is #2 in the world behind Nintendo (http://www.vgchartz.com/).

The reason Windows Phone will succeed is because of developers, and Microsoft has more of them and has better tools to support them and make things easier; developers are notoriously more inclined to take the path of least resistance.  What has been lacking for Microsoft is viability and profitability.  Estimates for Windows Phone 7 were around 5.2% worldwide, hardly viable especially against the profitability of iOS and the adoption rate of Android.  iOS has been such a success that developers are willing to step back in time and use Objective-C as a language.  But when the community creates tools like MonoTouch and RubyMotion, it shows that developers are not happy with your programming ecosystem and want something that allows them to be better.  Personally I mark this as one of the attributing factors to the rise in Android’s app count (http://blog.appsfire.com/1-million-apps-ios-android/), among others:

  1. Many of the apps being written are ports from the iPhone
  2. The App Store is far more restrictive in terms of what can be submitted that the Android marketplace
  3. Java provides more aspects to increase developer productivity over Objective-C (this is something Apple is working to address)
  4. The tools (Eclipse, IntelliJ) are simply easier to work with and more welcoming for developers

The simple truth is, and I give Apple credit for make efforts to change this but, Apple is NOT a developer company.  Microsoft is often viewed as giving developers some of the best tools available, this is a huge part of the potential that Windows Phone has.

But again we return to viability, Windows Phone 7 was/is not, no matter how it is spun.  No one bought Windows Phone 7, and there were many reasons for that, but first and foremost, Microsoft continues to showcase that when put up against Apple their marketing simply falls short, though it is getting better.  But lets address a bigger issue Microsoft is battling: perception.

Even now Microsoft dominates the PC operating space with an astounding 84% of all worldwide machines (http://www.statowl.com/operating_system_market_share.php), and this gives Microsoft an incredible potential user install base.  But what Microsoft has to realize is THIS IS NOT THE OS MARKET.  They are not entering a market that they totally dominate, I would even argue its not a market being dictated by enterprise demands; it’s a market ruled and controlled by the consumer, which is Apple’s bread and butter, and Apple is simply not making mistakes.  They must also realize that they have not created the most positive image in the consumer space.  This means it is even more important that whatever is shown is ready, sleek, and smooth; which was not the case with the Surface introduction.  Microsoft also has to watch what it says for the sake of perception.  Even if people are not buying your devices, they are still a highly visible company and consumers are listening and watching.  I believe consumers are more tech aware now than ever before.  Apple realizes this and caters to that point with its releases.

A prime example of this came with the release of latest iOS version which Apple immediately announced will run on the 3GS, but some features will not work due to the older hardware.  Most people understand this, and look forward to getting the full feature set when they upgrade to a new iPhone.  The perception is that Apple is looking out for them and keeping them in mind.  Contrast that to Microsoft.  With the release of Tango (7.8) in December, Microsoft has said they will no longer be doing releases for Windows Phone 7, effectively spitting in the face of the people who invested in the platform.  The tech people understand why they did this, but we are not, and should not be, Microsoft’s target audience, it’s the general consumer, many of whom still remember the Kin.  If I were a general consumer and I went out and bought a shiny new Lumia and then was told 1 month later that my phone (that I will likely keep for two years) is going to be unsupported in 4 months, I would be upset and lose incentive to invest in the platform.  Its this kind of idiocy that hampers Microsoft now as it has in the past.  The difference was, in the past their dominance in the OS space and lack of an alternative choices (before the rise of OSX) offset this.

The sad thing is, it would’ve been so easy to say “The update in December, we call it Tango, is the next version of Windows Phone.  Unfortunately, some features wont work cause of the hardware differences.”  Easy.  I about punched my desk when I read what they said.  Stupid.

Nevertheless, the advantage that Microsoft has in this race is clear, with an army of capable developers who are yearning to work with something other than Objective-C and Java, Microsoft will continue to be primed and ready to explode.  However, unless they can appeal to the AVERAGE consumer and actually sell some phones, the platform will continued to be viewed as unviable.  I think it will succeed because I believe developers ultimately determine the success of a platform.  Without the apps people don’t buy, though without people, developers don’t write that many apps either.  Thanks.

Mapping you ApiControllers with Ninject

I am a big fan of Dependency Injection.  I think it can make your life tremendously easier by automating a lot of the wireup within an application.  For Spotted, I am working on a Web API backend that the mobile applications will talk to.  I wanted to use Ninject for this.

Now, WebAPI still being fairly new, and the fact that Microsoft decided to eliminate the commonly used DefaultControllerFactory in favor of a class implementing the IDependencyResolver interface.  I wanted to search for this and hope I could draw some inspiration for this from work done via MVC3 Controller Factory patterns, since it was roughly the same thing.  Needless to say I could not find much and what I did find scared me.  Stuff like this, which insinuate that you create a bevy of Ninject modules in your application, scares me, because there are people out there who wont know any better.  It frightened me so much that I had to blog my solution.

The purpose of Dependency Injection is NOT to simply look cool, quite the contrary, it is a very useful pattern.  However, I have noticed two anti-patterns cropping up around it.  One is that teams seem to define a variety of fluent configuration files all over their application, instead of centralizing these files.  The other, and in my mind more critical, is that people seem OK with defining a ton of mappings, and the configuration files quickly run long.  This can be a problem for MVC like applications if you start mapping each controller individually; creating interfaces for each controller makes this even worse.  This is where you start to look at convention and realize that the interface to class need NOT be one to one, but can be one to many.  Lets look at how Spotted does this:

Here are the important methods from NinjectDependencyResolver:

        public object GetService(Type serviceType)
        {
            // get the controller name
            string controllerName = serviceType.Name.AsControllerName();
            if (string.IsNullOrEmpty(controllerName))
                return null;
            
            return _ninjectKernel.TryGet(
                                       controllerName, new IParameter[0]);
        }

        public IEnumerable<object> GetServices(Type serviceType)
        {
            try
            {
                var list = _ninjectKernel.GetAll(serviceType);
                return list;
            }
            catch
            {
                return new object[0];
            }
        }

        public IDependencyScope BeginScope()
        {
            return this;
        }

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

The most important method in this sample is GetService(Type type), as this is the method which actually returns the constructor as needed.  The important thing to understand is that most DI frameworks, including Ninject, support “metadata” when defining the mappings.  In this case, we associate a name with the mapping.  This allows us to have multiple mappings to the same type (IHttpController) but still have the ability to distinctly identify them using the name (SpotController becomes ‘Spot’).  I used an extension method here (AsControllerName()) to extract the name regardless of circumstance, returning null if it cannot be done.

Central to the ability to extract types in Ninject is the Kernel.  Think of the Kernel as a special class that replaces new.  Asking the kernel for an instance of a class (TryGet) returns an instance based on the rules defined within the kernel, also called the container.  Containers serve many purposes within Dependency Injection, but chiefly type resolution and lifecycle maintenance.

The Kernel is comprised of a number of modules which define the mappings for the Kernel (container).  Here is my module which maps ALL of my controllers to IHttpController with that “name” which is used above to extract the type:

public override void Load()
{
     var applicableTypes = _targetAssembly.GetTypes()
          .Where(t => t.GetInterfaces().Contains(typeof (IHttpController)))
          .ToList();

     applicableTypes.ForEach(hc =>
     {
          if (!string.IsNullOrEmpty(hc.Name))
          {
               var controllerName = hc.Name.AsControllerName();
               Bind().To(hc).Named(controllerName);
          }
     });
}

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

This is only done once, so its not too much of a performance hit.  By finding all types in the given assembly which implement the IHttpController interface and storing metadata it reduces the amount of code we have to write and maintain.  In addition, adding new controllers to the solution does NOT require any coding changes, just make sure you still write your tests to ensure that your container is returning the right controller.  My first test after creating the controller is to make sure I can get an instance of the controller out of the container.

This concept is part of the “convention over configuration” mentality.  Most every developer defines controllers the same way, in fact frameworks like ASP .NET MVC/WebAPI require controllers be specified in this way, save large amounts of custom code being written.  With that rule in mind, it makes ZERO sense to individually define your mappings.  Do them together as part of a convention, save yourself the time and remove the need to update Ninject modules each time you add new code.

Non-standard binding with CM and MVVM

While working on Spotted I wanted to allow users to associate images with the places they want to remember.  However, the view model that captured this image also has to be responsible for sending it across the wire on the save.  I did not want to keep two properties, one to hold the raw data using byte[] and another that held the BitmapImage which represented the image to display.  This article talks about how I got around this and still held true to MVVM.

My first attempt was to use simple inheritance to create a custom property in a custom Image class (I called it SpottedImage) which would feature my property would result in the fewest amount of changes. Example:

public class SpottedImage : Image
{
     public byte[] ImageData
     {
          get { /* return the byte array from BitmapImage */ }
          set { /* convert the byte[] int BitmapImage */ }
     }
}

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

This attempt did not work, mainly because, for whatever reason, Microsoft has chosen to “seal” many of the Windows Phone 7 control classes, making it impossible to extend.  It perplexes me why they will allow us to modify the control templates to our hearts content, but we cant extend the controls to add a simple property.

Without being able to use simple inheritance the next choice was to wrap the Image control in a UserControl and provide a dependency property which could carry out the conversion.  This worked beautifully, and with a bare minimum of code.  First I had to define the user control, which is about as simple as you think:

<UserControl x:Class="Spotted.Controls.SpottedImage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    
    <Grid>
        <Image x:Name="TheImage" />
    </Grid>
</UserControl>

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

Just a simple Grid containing the image, nothing special.  The real magic is in the code-behind.  Remember, since we are dealing with a “control” we don’t need to worry about binding within the control itself.  The first step in the code behind is to define the dependency property we will bind to externally:

public static readonly DependencyProperty ImageDataProperty =
     DependencyProperty.Register("ImageData", typeof(byte[]), typeof(SpottedImage),
          new PropertyMetadata(ImageDataChanged));

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

This defines a simple static property which we can bind to.  When the property changes, the method ImageDataChanged is fired giving us the ability to handle what the binding means.  In this case, the incoming data type is byte[] but to assign as the Source of the Image we need to convert it to a BitmapImage.  Here is the code for this method:

private static void ImageDataChanged(DependencyObject d,
     DependencyPropertyChangedEventArgs e)
{
     var control = (SpottedImage) d;
     using (var memStream = new MemoryStream((byte[])e.NewValue))
     {
          var image = new BitmapImage();
          image.SetSource(memStream);
          
          control.ImageSource = image;
     }
}

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

Very simple.  Originally, this code was in the view model when I had two properties.  But really, this isn’t data that the view model cares about and its not its responsibility here to convert this.  This is on the control itself.

You notice that I set an ImageSource property after the conversion.  This is purely internal and is never used outside the control.  Here is the code for this property:

public BitmapImage ImageSource
{
    get { return (BitmapImage)TheImage.Source; }
    private set { TheImage.Source = value; }
}

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

Pretty standard for a property.  The set is only every used, but the get is required for purposes of assignment and control validation.

So this is all well and good, and you could use this right now, but you would be unable to take full advantage of the MVVM provided by Caliburn.Micro, which is convention based binding.  This is, effectively, a new control which Caliburn would never know about by default.  Luckily, CM allows you to create new conventions using ConventionManager within your bootstrapper.  Here is my updated convention for SpottedImage:

ConventionManager.AddElementConvention(
     SpottedImage.ImageDataProperty, "ImageData", string.Empty);

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

One line.  Yet it gives you the ability now to do something like this in your View:

<uc:SpottedImage x:Name="SpotPicture" HorizontalAlignment="Center"
     VerticalAlignment="Center" Stretch="Fill" />

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

And this in your View Model:

public byte[] SpotPicture { get; private set; }

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

And have it automatically do the binding for you.  This is tremendously powerful, because now after the users takes a picture, I need only set this property and notify the framework that the property has changed and everything else is taken care of for me, like so:

public void TakePictureCompleted(object sender, PhotoResult photoResult)
{
     // prepare the package for transport (convert to byte[])
     using (var reader = new BinaryReader(photoResult.ChosenPhoto))
     {
          long length = photoResult.ChosenPhoto.Length;
          byte[] imageData = reader.ReadBytes((int) length);
          SpotPicture = imageData;
          NotifyOfPropertyChange("SpotPicture");
     }
}

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

Awesome.  Clean and straightforward and in keeping with MVVM.  This is why I love coding when you get to achieve things like this.

JavaScript Template Method Pattern

During my recent client engagement we have been heavily involved in using JavaScript for our PhoneGap application.  As such, we have had to find ways of doing things heavily dependent on context, that is the state of the application.

I recently discovered a way to implement the “Template Method Pattern” in JavaScript that has served me quite well, so I figured I would share it here.

Android Back Button

During the development of our PhoneGap application we had need to handle the back button.  Our goal was to handle it in such a way so that it felt natural to the end user who would be used to their existing Android applications.  This included a couple of necessary cases:

  • If there is an existing obscurance on the screen, it should be dismissed
  • If allowed the application should “go back” to the most recent available page in the stack.  If none is available, the application should exit

Using the standard way of handling back within a PhoneGap application, we discovered that for system type obscurances (keyboard, system alerts, etc) are handled outside PhoneGap, so the back button event is never raised in this case.

To handle the second case, I implemented a Page Stack type subsystem which tracks history and manages the stack.  Very basic and nothing more than a wrapped array.  Because, in certain cases, a custom obscurance can be visible, that is a dialog or perhaps a datepicker, we want the back button to be able to ask the current page if it should go back in the stack or take other action.

This is where the Template Method Pattern is useful.  If we had to code for all situations inside the back button event handler, the code would quickly spiral out of control.  So we want to use the Template Method Pattern to first allow the page to take action on its own and then to indicate if we should still go back in history.

A Real Template Method

If you are familiar with the template method in OO, you know that generally you define an abstract or virtual method and then call that method from with another.  The idea is that this method gives you a “hook” that allows custom functionality at certain points.  In JavaScript, we have to take a slighty different approach.  Start by defining the structure of your methods name.

In the case of the client project, we elected to go with _handleBackButton.  So if I was on a page called TimeConfirm.html, I would call the method “timeconfirm_handleBackButton”.  This method would need to perform any actions locally and then indicate if the previous page should be loaded.

As is it so happens, all JavaScript methods available are callable through window as if they were in an associative array.  The following code details our method which handles the press of the back button that does not dismiss a system type obscurance.

   1:  function _handleBackButton()
   2:  {
   3:    var currentPageName = $.getCurrentPage().replace(/\.html$/, "");
   4:    var methodName = currentPageName + "_handleBackButton";
   5:   
   6:    if (window[methodName] != undefined)
   7:    {
   8:      var result = window[methodName];
   9:      if (!result)  return;   // stop processing the back button
  10:    }
  11:   
  12:    var previousPage = $.pageStack.pop();
  13:    if (previousPage == null)
  14:    {
  15:      navigator.app.exit();   // exit the app
  16:      return;
  17:    }
  18:    
  19:    $.changePage(previous);
  20:  }

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

The first thing we do is get the current page (which will be the filename with .html at the end) name.  Using this name we build the name of the method (methodName) and check if its available.  Traditionally in Template Method Pattern the method must be defined, though sometimes we can use a default implementation.  In this case, if the method does not exist, we do not use it, the code is simply by passed.

Whats important to note here is how the return of the “special” method is used.  If the method returns true then the back button will continue to function.  This is because in some cases you may want to save page state and continue to go back.  In that case, you still need a “hook” but would want to back button to function as normal.

So that’s it.  I have found this very useful and so far not a detriment to performance.  It certainly beats trying to define the variety of cases in the same method.  Hopefully this can be of use in your applications.

Architecting WCF for Error and Condition Validation

As an architect I am often tasked with understanding how to build operations into a framework so that other developers can focus on the task at hand rather than reconstructing/rebuilding a foundation each time they carry out an action.  This is an essential task in any software system, in particular a large one.  I have seen too often that teams do not want to address these fundamental needs that every system has and end up getting bitten due to lack of vision.  Addressing the role of the code architect for a team is the topic for another post, this one is about handling errors and business logic, and doing so in a very centralized way.

So what is the problem?

The question has always been, how do we efficiently and agnostically get errors back from a web service?  To take that one step further, how do we communicate errors to the caller in a way that is both efficient and understandable regardless of the platform.  I recently had to battle this problem in a WCF REST Service I am writing for a client.  This is a hugely important component of a system, so I thought it made sense to make it available to all:

Your Result

I am not a big fan of error codes, I feel that if you have a large system you can quickly find yourself lost with so many different codes.  With that in mind, I decided to use enumerations for error codes now:

    public enum ResultCode
    {
        Success = 0x0000,
        PlanetaryAlignmentBad = 0x0001,
        NotAuthorized = 0x0002
    }

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

Using this enumeration, I want to define a base class for all of my results.  I don’t know if this approach has a formal pattern, but it was something that a colleague of mine, Chad, proposed to me.  This allows a kind of view model approach with what is being returned to the caller, here is ResultBase:

    [DataContract]
    public abstract class ResultBase
    {
        [DataMember]
        public bool IsSuccess
        {
            get { return ResultCode == ResultCode.Success; }
            private set { }
        }

        [DataMember]
        public string ErrorMessage { get; set; }

        [DataMember]
        public ResultCode ResultCode { get; set; }
    }

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

What I am defining here is a very simple base class that our two classes, SuccessfulResult and FailedResult.  The idea is that, for our example, well return one of these two classes.  In your application you could have a class like UserAuthenticateResult and have it return the necessary information pertaining to the operation.

Inspectors

One of the nice things about WCF is the insane number of extensibility points, you can change just about everything regarding the way the system works.  For our example, we will first define a class the allows us to inspect the outgoing result of a service call:

    public class OutboundResultParameterInspector : IParameterInspector
    {
        #region Implementation of IParameterInspector

        public object BeforeCall(string operationName, object[] inputs)
        {
            return null;
        }

        public void AfterCall(string operationName, object[] outputs,
                               object returnValue, object correlationState)
        {
            var result = returnValue as ResultBase;
            if (result != null)
            {
                if (!result.IsSuccess)
                {
                    // handle the error
                    throw new OperationException(
                           result.ErrorMessage, result.ResultCode);
                }
            }
        }

        #endregion
    }

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

A quick note: the value returned by BeforeCall will be passed as the correlationState to the AfterCall method.

All this code is doing is taking the result of our operation and attempt to cast it to an object of type ResultBase, this will be successful IF the object being returned inherits from ResultBase.  If this isn’t the case, then the operation simply goes on as normal.

Where this really gets interesting is if the operation fails.  In this code we throw an exception.  The reason for this is simple: we need to invoke the global error handler for WCF so we can rewrite the return message.  You see, REST is about relying on what already exists, and that means for errors, using standard HTTP error codes.  Doing this allows the caller to better handle whatever problem occurs and keeps with the true spirit of REST.

But before we can talk about error handling, we have to get WCF to actually invoke this inspector.  That can be done a few ways, for our example we will use an attribute.

    public class InspectOutgoingResultAttribute : Attribute, IOperationBehavior
    {
        #region Implementation of IOperationBehavior

        public void Validate(OperationDescription operationDescription)
        {
            
        }

        public void ApplyDispatchBehavior(OperationDescription operationDescription,
            DispatchOperation dispatchOperation)
        {
            dispatchOperation.ParameterInspectors.Add(
                new OutboundResultParameterInspector());
        }

        public void ApplyClientBehavior(OperationDescription operationDescription,
            ClientOperation clientOperation)
        {
            
        }

        public void AddBindingParameters(OperationDescription operationDescription, 
            BindingParameterCollection bindingParameters)
        {
            
        }

        #endregion
    }

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

The only thing this class is doing is modifying the Dispatcher to add the appropriate inspector.  With this applied, ANY operation that this decorates is subjected to our inspector, for example:

        [InspectOutgoingResult]
        public SuccessfulResult GetSuccessfulResult()
        {
            return new SuccessfulResult();
        }

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

Simple.  With this in place, we can selectively decorate the methods and this will allow us to handle any business logic cases with grace.

You probably noticed that I was throwing an OperationException above if the result failed.  This is a custom class that I have created.  It has two purposes: 1) determine the appropriate HTTP Status code that will represent the error being thrown and 2) invoke the error handling of WCF so we can rewrite the message.  Well talk about this portion next.

Lets Rewrite History

One of the things that I love in statically typed languages like C# is the ability to define a particular type being returned by a method, it adds a certain degree of structure the code.  One of things I hate about statically typed languages is that I have to define a type for the return.

With respect to the tenants of REST its important to use what HTTP provides to return a result, as is done by Twitter, TripIt, Facebook, Foursquare, etc.  Doing this makes things cleaner and relieves us from using special conditions and/or logic for error handling.  We will do this for our example, but first we have to define a global error handler to override the default.  We do this by implementing IErrorHandler:

    public class CustomErrorHandler : IErrorHandler
    {
        public bool HandleError(Exception error)
        {
            return true;
        }

        public void ProvideFault(Exception error, MessageVersion version,
                      ref Message fault)
        {
            var ex = (OperationException) error;
            fault = Message.CreateMessage(version, string.Empty,
                      new ErrorMessage(ex.OutcomeCode, ex.Message)
                , new DataContractJsonSerializer(typeof(ErrorMessage)));

            var wbf = new WebBodyFormatMessageProperty(WebContentFormat.Json);
            fault.Properties.Add(WebBodyFormatMessageProperty.Name, wbf);

            var response = WebOperationContext.Current.OutgoingResponse;
            response.ContentType = "application/json";
            response.StatusCode = ex.StatusCode;
        }
    }

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

The essence of what we are doing here is, if we encounter an error we intercept the response being transmitted (this is not your return result) and re-serialize it using our ErrorMessage class (below):

    [DataContract]
    public class ErrorMessage
    {
        [DataMember]
        public ResultCode ResultCode { get; private set; }

        [DataMember]
        public string Message { get; private set; }

        public ErrorMessage(ResultCode code, string message)
        {
            ResultCode = code;
            Message = message;
        }
    }

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

This class only allows us a template for serializing the error state into JSON form (notice that this code sample relies upon the response format to be JSON, this will not work, without modification, with XML or other transport formats).

With this in place we just have to make sure that WCF is aware of our error handler.  It is also important to understand that error handling is done at the ServiceContract level.  So when we create our attribute, it can only work if applied at the class level.  Here is our attribute:

    [AttributeUsage(AttributeTargets.Class)]
    public class HandleErrorsAttribute : Attribute, IServiceBehavior
    {
        // non implemted method omitted
       
        public void ApplyDispatchBehavior(ServiceDescription description,
                 ServiceHostBase hostBase)
        {
            hostBase.ChannelDispatchers.Cast().ToList().ForEach(
                      (d) => d.ErrorHandlers.Add(new CustomErrorHandler()));
        }
    }

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

I had tinkered with seeing if I could put the error handler on individual operations, but that doesn’t appear to be supported through IOperationBehavior.

Once this is in place, you can play with the service and watch as things are being caught.  Here is the sample code I used while proving the idea:

    // some attributes ommitted for brevity
    // dont forget to disable automatic automaticFormatSelectionEnabled
    // in the web.config
    [ServiceContract]
    [HandleErrors]
    public class Service1
    {
        [WebGet(UriTemplate = "/Success", ResponseFormat=WebMessageFormat.Json)]
        [InspectOutgoingResult]
        public SuccessfulResult GetSuccessfulResult()
        {
            return new SuccessfulResult();
        }

        [WebGet(UriTemplate = "/Fail", ResponseFormat=WebMessageFormat.Json)]
        [InspectOutgoingResult]
        public FailedResult GetFailedResult()
        {
            return new FailedResult();
        }
    }

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

Simplistic I admit, but it proved the point.  If I call /Fail then I see my response totally rewritten with the error message and the appropriate Http Status code.  If I call /Success then things work as they should.

Closing

REST with WCF can be done by hand as it requires only minor config changes and some setup in the Global.asax file, however, I recommend searching “rest” in your online templates, you will find a ready to use template prepared for you. It works out of the box and is easy to modify to fit your desires.

REST is a very useful methodology for designing services because it forces you to thing agnostically so you are not forced to care who is accessing your service and from what platform.  However, it is equally important to be diligent when selecting your REST API structure.  I always tell people I talk with that the URLs should almost speak when they are being called.  The idea of REST is to make the URL look more like an English sentence.  It should express what you are doing.  “I am GETting a Load”, “I am POSTing an Update”, “I am PUTting a new entry in the database”.  Use the various verbs to help make the API more understandable. It will go a long way to helping others understand your service and code

Caliburn.Micro MVVM with Windows Phone 7

So the ThatConference Chicago Hackathon is over and we ended up failing to impress the judges with our idea, though it seemed more about the fact that we couldn’t get Visual Studio to work properly in 5 minutes versus the actual idea which they said they liked an awful lot, enough to give us honorable mention without proof of a working app.

What I learned from this is the idea is solid and that I really should devote more time and energy into developing it.  And so I started this weekend building up the app we call “Spotted” using MVVM via Caliburn.Micro.  Its been an interesting experience with a lot of learning being done.  So I thought I would share what I learned over the course of the weekend.

A quick word about MVVM

People get confused when the read MVVM, mainly because it has the word “Model” in it.  They seem to think MVVM is a variant or, worse, a replacement for MVC.  It is neither.  MVVM is a client side paradigm where by the interaction logic traditionally housed inside the View (JavaScript and Code Behind files) is transferred to a class which is then “bound” to a view and governs interactions with that view.  The “Model” in this case is merely something coming from another area, it could mimic a “model” in the MVC world, but they are not the same.  In fact, MVVM is closer to MVP rather than MVC, merely because VMs tend to be closely coupled with their views.

So, to summarize, MVC is traditionally found on web servers, where as MVVM is traditionally found on the client side.

The Bootstrapper

I will spare walking you through how to acquire the Caliburn.Micro (CM) DLLs as it is merely a simple nuget command as shown on the project homepage here.  The first thing you need to understand is the bootstrapper. The methods of this class tied to lifecycle events within your Silverlight application.  Out of the box, the default bootstrapper (AppBootstrapper) provides enough for you to get started, including some basic IoC management.  However, I am a huge fan of Ninject, so we will be using that in the application.

The first method we are going to look at is the virtual method Configure provided to us by the PhoneBootstrapper class.  Think of this method as the very first chance you get to do whatever initial setup work the application will need.  In our case, we will be instating the Ninject StandardKernel class as our IoC container.

        private IKernel _ninjectContainer;

        protected override void Configure()
        {
            _ninjectContainer = new StandardKernel(
                         new SpottedNinjectModule(RootFrame));
        }

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

To those who are familiar with Ninject, this will make sense.  If you are not familiar, understand that Ninject allows you to specify modules which can then define the mappings for your IoC container.  This is the blueprint for how to fulfill dependencies in your application.  Since this is a Silverlight application, the RootFrame is still used for some purposes even by the underlying CM classes.  This is the source of the SpottedNinjectModule:

        /// 
        /// Loads the module into the kernel.
        /// 
        public override void Load()
        {
            // phone services
            Bind().To().InSingletonScope();
            Bind().ToConstant(
                 new FrameAdapter(_rootFrame)).InSingletonScope();
            Bind().To().InSingletonScope();
            Bind().ToConstant(
                 new PhoneApplicationServiceAdapter(_rootFrame)).InSingletonScope();
        }

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

I should point out that, after much trial and error, these are the REQUIRED mappings in order to get CM to work with Ninject.  Be sure to also note the usage of RootFrame for some of the bindings.  This is because CM must still tap into the native features of the platform to carry out certain operations.

Looking at this you will notice that I did not map any view models.  Why?  The reason is CM uses conventions to find view models and views.  This reduces the clutter you traditionally see in the mapping definitions file for a large IoC project.  In fact, this is part of a bigger movement with respect to IoC to reduce the amount of binding type code developers have to write, using conventions to drive the configuration, much the same way this has happened in MVC world.

This page details how CM finds views and view models, I found it extremely helpful.  Basically, if I ask for the HomeView page/view, CM will look to bind the HomeViewModel as the DataContext.  This is all handled automatically leaving the developer to focus on actually implementing the view model instead of the boiler plate code that no one wants to write.

There are three other movies that should be implemented as part of our Ninject Bootstrapper: GetInstance, GetAllInstances, and BuildUp.  The source for these three methods is shown below:

        protected override object GetInstance(Type service, string key)
        {
            return service == null ? null : _ninjectContainer.Get(service);
        }

        protected override IEnumerable<object> GetAllInstances(Type service)
        {
            return _ninjectContainer.GetAll(service);
        }

        protected override void BuildUp(object instance)
        {
            _ninjectContainer.Inject(instance);
        }

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

Simple enough.  This will handle the majority of the work within the app layer.  I will update it later, via another post, with the mappings for the service layer.  There I intend to feature Injection by Convention.

Lets Bind a Map

The Spotted App deals heavily with locations extracted from Google Places.  That being the case, it would be useful to show our users a map with pushpins for the locations around them that they might be interested in.  For mapping in Windows Phone 7, Microsoft provides a custom Map control which talks to the Bing Maps SDK, provided you give it an API key (get one here).

It is important to understand that when using CM and adhering to MVVM, the VM should NEVER know anything about the view its binding to.  The idea is to rely purely on Actions and Bindings to carry out all operations.  With that in mind, I present the MainPageViewModel class from Spotted:

        public MainPageViewModel(IEventAggregator eventAggregator)
        {
            // instantiate inner view model
            ResultsMap = new LocalResultsMapViewModel(eventAggregator);

            _eventAggregator = eventAggregator;

            _watcher = new GeoCoordinateWatcher(GeoPositionAccuracy.High)
                             {MovementThreshold = 20};
            _watcher.PositionChanged += _coordinateWatcher_PositionChanged;

            _watcher.Start();
        }

        private void watcher_PositionChanged(object sender,  
                          GeoPositionChangedEventArgs e)
        {
            _eventAggregator.Publish(
                      new CenterLocationDeterminedMessage(e.Position.Location));
            _coordinateWatcher.Stop();
        }

        public LocalResultsMapViewModel ResultsMap { get; set; }
    }

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

A few things to point on from this class.  First notice we are receiving a class implementing the IEventAggregator interface.  This is provided by CM and represents the hub of the message processing system, more on this in a bit.

Important is that we are instantiating an instance of the LocalResultsMapViewModel which is the view model for a user control on this main page.  Well cover this in-depth shortly.  The big things to take note of in this class is that we are using the GeoCoordinateWatcher to get the current location via the GPS unit.  Once we have it, we pass it in a message to any class listening for this type of message.

Message Passing

Our goal, with any pattern, is to reduce class coupling and promote high levels of cohesion as per the Law of Demeter.  Within MVVM, we may wish to send messages to distinctly different view models, some of which may not even be referenced within the view model publishing the message.  For this, CM provides a Consumer-Publisher model via the IEventAggregator.  You notice above this code:

_eventAggregator.Publish(new CenterLocationDeterminedMessage(e.Position.Location));

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

This line tells the _eventAggregator to send a message to any consumer which can handle a message of type CenterLocationDeterminedMessage.  The ability to handle this is denoted by implementing IHandle where T is the type of the message being listened for.  For this I present the LocalResultsMapViewModel.

    public class LocalResultsMapViewModel : ViewModelBase,
          IHandle
    {
        public LocalResultsMapViewModel(IEventAggregator eventAggregator)
        {
            eventAggregator.Subscribe(this); 
        }

        #region Implementation of IHandle

        /// 
        /// Handles the message.
        /// 
        /// The message.
        public void Handle(CenterLocationDeterminedMessage message)
        {
            CenterLocation = message.CenterLocation;
            //if (message.ShowPushpin)
            //{
                Locations.Add(message.CenterLocation);
            //}
        }

         // elided
     }

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

Here you can see that we communicate that we intend for this class to subscribe for messages being broadcast and that it can handle message of type CenterLocationDeterminedMessage.  The Handle method is then provided to allow us to respond when the message is received.  In this case, I am doing some assignment to local properties who implementations I have excluded from the code sample.

Binding Isnt as straight forward as you think

The following is the XAML present in the LocalResultsMapView user control:

    <Grid x:Name="LayoutRoot">
        <controls:SpottedMapView ZoomLevel="{Binding ZoomLevel}"
                                 CenterLocation="{Binding CenterLocation}"
                                 Locations="{Binding Locations}" />
    </Grid>

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

This application will make HEAVY use of the map control, thus I decided to wrap it to give me a consistent way to hit its properties.  After learning more about Dependency Properties, I see another avenue that I could have taken with doing this, but it would’ve required some duplication which I do not want.

Before I get into binding, this is the source of SpottedMapView:

    <Grid x:Name="LayoutRoot">
        <map:Map CredentialsProvider="BingAPIKEy"
                 x:Name="theMap" />
    </Grid>

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

Simple right? Well, if you were to run this code, it would not work.  Even if you define traditional properties to represent ZoomLevel, CenterLocation, and Locations it will not work.  As I found out the hard way, you cannot data bind to normal properties that are custom created.  You can only bind to dependency properties.  Microsoft has really done a great job at hiding this fact in this existing controls, you really cannot tell in a control like TextBlock that you are not binding to Text, but rather, I suspect, TextProperty, which is linked to the traditional Text property.

The answer is to define dependency properties for those custom properties you want to bind to.  Below is all parts to the CenterLocation property I am binding to:

        // Dependency Property
        public static readonly DependencyProperty CenterLocationProperty =
            DependencyProperty.Register("CenterLocation", typeof (GeoCoordinate),
                     typeof (SpottedMapView),
                      new PropertyMetadata(CenterLocationChanged));

        // Traditional Property
        public GeoCoordinate CenterLocation
        {
            get { return theMap.Center; }
            set { theMap.Center = value; }
        }

        // Property Changed Event Handler
        private static void CenterLocationChanged(DependencyObject d,
                                              DependencyPropertyChangedEventArgs e)
        {
            var mapView = (SpottedMapView) d;
            mapView.CenterLocation = (GeoCoordinate) e.NewValue;
        }

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

You may look at the direct reference to the control (theMap) and think this is a violation of MVVM.  It is not, we are binding to a custom user control so that we can easily talk to the underlying may.  I could change the mapping system I am using and the external code would be none the wiser.

The part that I learned about is that I can define custom event handling logic when the property changes (via PropertyMetadata).  This allows me to take direct control over the value coming in and how I want to handle it.  For ZoomLevel (not shown) and CenterLocation this is very straightforward and not that interesting.  However, I have a third property which allows me to bind an IEnumerable and have it be translated to Pushpin which are visible on a map:

        private static void LocationsChanged(DependencyObject d,
                     DependencyPropertyChangedEventArgs e)
        {
            var mapView = (SpottedMapView) d;
            mapView.theMap.Children.Clear();
            var style = Application.Current.Resources["userPushpin"] as Style;

            foreach (var location in (IEnumerable)e.NewValue)
            {
                var pp = new Pushpin
                   {
                        Location = location,
                        Content = "You",
                        Style = style
                    };
                mapView.theMap.Children.Add(pp);
            }

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

This is a very powerful concept and allows me to take full advantage of the decoupling abilities provided by an MVVM framework.  Up next, I intend to create derivations of the Location class so I can denote special meanings, such as style and whether to show a pushpin or not.  At some point, I will also need to start building out the repository layer for communicating with the backend service, and that will require more research into how I might use conventions to reduce the amount of coded needed for that.

Conclusion

I believe strongly that the complexities faced by developers in modern applications are real, and required action.  I think if you take Robert Martins SOLID principles and view the View and the Interactions of the view as responsibilities were were having the View do two things which violated the Single Responsibility Principle.  Separating the view from its interaction logic is not a new thing, but the introduction of using declarative syntax as part of the view to “bind” values and actions, is something that is fairly new.  Using binding we can further separate logic from the view and work toward a more discrete system with respect to responsibilities.

Introduction to KnockoutJS

Introduction

Modern applications today tend to be very complex and offer a plethora of features. As such, developers must constantly strive to find a good balance per the separation of concerns to create solid applications and enable good unit testing.  Because of these needs MVC has returned to the forefront in recent years as a way to achieve this separation.  However, with Ajax there is more logic within the view interns of how the view should work for the user.  With traditional MVC this leads to a lot of code being placed in the View to facilitate these interactions.  This leads to a lot of extra code being put in the view and developers asking the question “should there be another layer somewhere?”.

Enter MVVM

As part of the .NET 3.0 release Microsoft began work on the Microsoft Windows Presentation Foundation (WPF).  This new framework used a declarative markup language (XAML) to build user interfaces, this meant that the code previously hidden in Windows Form for creating controls and placing them was removed.  Perhaps once of the most profound things to come out of this framework was the notion of declarative binding.  Whether this was actually invented here is unknown to me, it is simply the first example I saw of it.

Using these declarative bindings we (developers) were able to remove much of the get/set code that had created so much clutter over the years. This formed the basis for the Model View ViewModel pattern (MVVM) where we actually split the V into the View and the ViewModel.  The ViewModel taking on much of the code that had originally cluttered our views, thus becoming the new layer we so desperately sought.

MVVM on the Web

One of the strategies that developers use with MVC on the web to do MVVM is the use of strongly typed views.  Frameworks like ASP .NET MVC and Ruby on Rails, allow developers to base their views on a class passed to the view, often referred to as the View Model in this context.  While not MVVM in the purest sense, the intention is the same, separate out the data from the actual view and provided an automated way to update the values without needing to write tedious plumbing code (see Model Binders in ASP .NET MVC).  While this works for simple applications, it falls well short when used with Ajax heavy applications due to the reliance on JavaScript and the lack of behavioral definitions in the strongly typed “view model”.

Frameworks like JQuery have come to prominence for their ability to make JavaScript easier to use, it has also led to more applications relying on JavaScript as a means of communication and UI enhancement.  And while this is true, it has also led to MORE JavaScript being written to support these interactions.  Thus the same problem began to present itself in the view.  It has become bloated with tedious repetitive code. And since JavaScript, by its nature, does not architect well, the problem gets even worse.  The purpose of JQuery was to allow us to do more but writing less.  While it does achieve that, it also adds a reliance on JavaScript that creates its own set of problems.

KnockoutJS

Thankfully this problem has not gone unnoticed by the community, frameworks already exists to bring the MVVm approach to JavaScript applications.  KnockoutJS (http://www.knockoutjs.com) is one such framework.  It takes the approach that the view should be as clean as possible, devoid of any JavaScript.  To do this, it leverages the new “data-bind” attribute in HTML5, while maintaining backward compatibility with HTML4.  Take a look at the sample code below:

NewImage

This is a very basic example, but what it does is “bind” the FirstName and LastName members of the “viewModel” object.  This example is showing off one way binding, since the user cannot expect to update the text content of a .  So if we want to use two way binding, we would need to use the binding with form elements:

NewImage 

A few things are happening here.  First, we are using a different way of denoting a JavaScript “class” definition.  Since functions in JavaScript can also be treated as object constructors, we can use the new keyword to denote a new instance.  Thus far, I would not take any of the lessons of OO programming with you in JS.  The second thing to notice is the value: binding.  KnockoutJS comes with many of these built in bindings, which will usually be enough for most projects.  A complete list can be found at http://www.knockoutjs.com along with a plethora of examples.

By itself the value: binding will not give you the two way binding you would want on a form textfield, in fact it has very little to do with the two way binding you want.  The key for two way binding is the user of Knockout Observables.  If you notice the definition of our object contains two refers to ko.observable.  Using this makes the member special.  It tells Knockout to watch this binding for changes and update the view model when changes occur.

In the AppViewModel object, we are also defining a “computed” observable.  This will watch a field (or fields) for changes and update accordingly.  There are common used for composed properties which use the data from a variety of other properties (or members).  In the case of this example, any change to the value of firstName or lastName will update the value in fullName and cause the to update its value to display the changed value.  Side note: buy default, for value: the binding update occurs onBlur as opposed to onKeyDown, this is configurable.

With our current example, when you blur out of a textfield the span will update, but what would we have to do for the update to be real time, as they are typing.  Simple, we specify the valueUpdate setting on the binding:

NewImage

As you can see, we specify that the update to the view model should occur after key down.  This will automatically handle everything for us and since we are updating the view model which is using a computed observable this change is then immediately reflected in the tag.  So without writing any JS code, we have achieved this effect.

Conclusion

Lets me realistic, web applications are complicated.  The bar for interactivity is now higher than ever, but JS remains a fragile and fickle language to work with.  The project I am currently on is using utilizing PhoneGap to attempt to deliver a single code base to both iOS and Android.  The approach is heavily reliant on JavaScript.  Already the team has seen value in using Knockout because they get to write less JS code, which is always a good thing.  Furthermore, using a view model approach allows you to write unit tests, yes I said unit tests and JavaScript, which further allows you to ensure that the application works.  JS is one of those languages that is just a bitch to do anything in unless you maintain tight control over the architecture, so it is true on our app as well.

The MVVM approach to View development is something that I highly recommend.  The biggest thing people seem to have trouble with is they want to view it as a replacement for something like MVC.  It isn’t.  Its a augmentation.  The M in MVVM (Model) only refers to the output of a Controller, not a Model from MVC, although it could.  The principle point of emphasis in MVVM in that the ViewModel handles the interactions.  ViewModels handle client validation and view interaction, they don’t do any kind of persistence, although they can be backed by a Model which does provide some level of persistence.

 

Custom Controls in Windows Phone 7

Recently, I gave a talk at the Chicago Windows Phone Developer Group on building custom controls using XAML templates.  The focus of the talk was to understand the importance of the user experience in a mobile application and how using custom controls can greatly augment the experience.

One of the nicest thing about XAML is the ability to deeply customize controls.  Control Templates can be overridden easily and with all matter of design attributes, it practically is a designers dream (Disclaimer: I am not a designer).

This also extends to custom controls.  Creating a custom control is easy, consider the following code:

public class StatePicker : Control
{
    public override void OnApplyTemplate()
    {
    }
}

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

Actually, the OnApplyTemplate method is not required by the Control class, but it will play an important role in our example.  Right now, with this class defined, we can provide the following XAML:

<custom:StatePicker x:Name="StatePicker" />

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

Now, the control isn’t especially useful because it has no visual appearance.  But we can easily give it a visual appearance by defining its control template.

<Style TargetType="custom:StatePicker">
    <Setter Property="Background" Value="{StaticResource PhoneTextBoxBrush}" />
    <Setter Property="BorderThickness" Value="0"/>
    <Setter Property="Foreground" Value="{StaticResource PhoneTextBoxForegroundBrush}" />
    <Setter Property="HorizontalContentAlignment" Value="Left" />
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="custom:StatePicker">
                <Button Background="{TemplateBinding Background}"
                        BorderThickness="{TemplateBinding BorderThickness}"
                        FontFamily="{TemplateBinding FontFamily}"
                        Foreground="{TemplateBinding Foreground}"
                        Height="72"
                        HorizontalContentAlignment="{TemplateBinding  HorizontalContentAlignment}"
                        Name="PickerButton" />
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

By defining this template we are effectively creating a control that encapsulates a Button, we have styled the control to make it look like a TextBox.  This template must now be APPLIED to the control.  You guessed it, the OnApplyTemplate method is a hook into this process.  This is the implementation of OnApplyTemplate that I am using:

        public override void OnApplyTemplate()
        {
            if (_chooserButton != null)
                _chooserButton.Click -= OpenStatePickerPage;

            // apply the template
            base.OnApplyTemplate();

            // wireup the button from the template
            _chooserButton = GetTemplateChild("PickerButton") as ButtonBase;

            // wireup the event
            if (_chooserButton != null)
            {
                _chooserButton.Click += OpenStatePickerPage;
            }
        }

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

Important here is the call to base.OnApplyTemplate.  If you do not call this, the call to GetTemplateChild will return null because the control you are looking for is in the template you have no applied.  If you notice above, we gave a name to the button declaration in the template.

OpenStatePicker is responsible for showing the actual picking UI.  Since space is very constrained on mobile devices, don’t be afraid of using a second page to actually carry out an operation on a large set of data.  Your users will be grateful for it, provided it is kept seamless and they don’t even realize they are changing pages.  Ideally, your users should see this as a since control. Many Microsoft controls employ exactly this, and they do it so well that very few users even realize they are being taken to a second page.

To show the actual UI, we simply navigate to the new page using the RootFrame (the frame which contains the application).

        private void OpenStatePickerPage(object sender, RoutedEventArgs e)
        {
            var frame = Application.Current.RootVisual as PhoneApplicationFrame;
            frame.Navigated += frame_Navigated;

            if (_selectedState == null)
                rootFrame.Navigate(new Uri("/StatePickerUI.xaml",
                             UriKind.RelativeOrAbsolute));
            else
                rootFrame.Navigate(
                       new Uri(string.Format("/StatePickerUI.xaml?ab={0}", 
                         _selectedState.Abbreviation), UriKind.RelativeOrAbsolute));
        }

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

One of the most important aspects here is going to be the wireup of the Navigated event from the frame.  This speaks to that temporary navigation that will be enacted.  For the rest of this we are navigating to the StatePickerUI page, passing a parameter if a pre-existing selection already exists.

Our StatePickerUI page will be pretty simple:

    <Grid x:Name="LayoutRoot" Background="Transparent">
        <tk:LoopingSelector ItemSize="143,130"
                            Width="150" Name="StateLoopingSelector">
            <tk:LoopingSelector.ItemTemplate>
                <DataTemplate>
                    <Grid Height="125" Width="140"
                          Background="{StaticResource PhoneChromeBrush}">
                        <Grid.RowDefinitions>
                            <RowDefinition Height="0.736*"/>
                            <RowDefinition Height="0.264*"/>
                        </Grid.RowDefinitions>

                        <TextBlock Style="{StaticResource PhoneTextTitle1Style}"
                            HorizontalAlignment="Center" VerticalAlignment="Center"
                                   Text="{Binding Abbreviation}" Margin="0" />
                        <TextBlock Margin="0" Text="{Binding Name}"
                                   VerticalAlignment="Bottom" Grid.Row="1" Height="25"
                                   Style="{StaticResource PhoneTextSmallStyle}" />
                    </Grid>
                </DataTemplate>
            </tk:LoopingSelector.ItemTemplate>
        </tk:LoopingSelector>
    </Grid>

    <phone:PhoneApplicationPage.ApplicationBar>
        <shell:ApplicationBar IsVisible="True" IsMenuEnabled="False">
            <shell:ApplicationBarIconButton
                x:Name="CancelButton"
                IconUri="/Toolkit.Content/ApplicationBar.Cancel.png" Text="cancel"
                Click="CancelButton_Click" />
            <shell:ApplicationBarIconButton
                x:Name="AcceptButton"
                IconUri="/Toolkit.Content/ApplicationBar.Check.png" Text="accept"
                Click="AcceptButton_Click" />
        </shell:ApplicationBar>
    </phone:PhoneApplicationPage.ApplicationBar>

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

Basically, this turns out to look like this:

2012-05-05_0958

We need the application bar so we allow the user to make a selection.  The key things with the LoopingDataSelector primitive is to define a data source.  The class which represents the data source must implement the ILoopingSelectorDataSource interface.  This interface describes three methods, a property, and an event.

  • object GetNext(object)
    • Loads the next object in the data source relative to another.  This is done because the user can swipe the list up and down for an infinite amount.  Your selection logic should be circular
  • object GetPrevious(object)
    • Same as above, just does previous
  • object SelectedItem
    • This is what was actually selected by the user (generally its rendered in the center)
  • event SelectionChanged – When the user makes a selection different from what is previous selected, this event is fired

I wont bore you with the implementations of these methods, rather check out the zipped source that can be downloaded at the bottom.

Once this is in place you need to establish a way to get the selected state from the PickerUI and to the StatePicker control that is on the page.  This is where we come back to the Navigated event.  Here is the code:

private void rootFrame_Navigated(object sender, NavigationEventArgs e)
{
    if (_isOpen)
    {
        // we need to close
        CloseStatePickerPage(_statePicker);

        var frame = Application.Current.RootVisual as PhoneApplicationFrame;
        rootFrame.Navigated -= rootFrame_Navigated;
        _isOpen = false;
    }
    else
    {
        _statePicker = e.Content as IPicker;
        if (_statePicker == null)
             throw new Exception("Some craziness is happening");

        _isOpen = true;     // mark the picker as open
    }
}

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

For this example, if the PickerUI is not open, we want to store a reference to the PickerUI (that is e.Content).  To simplify the code, we create a user interface (IPicker) which allows us to extract the selected item from the PickerUI, an instance of the State class in this case.

The reason for this is because we do NOT have access to the PickerUI content when we are coming back from the PickerUI, only when we are going to it.  This is why we must so closely control the “state” of the control.

Also important here is the removal of the Navigated event handler from the rootFrame.  Remember that we are employing “temporary navigation rules” within the “control”.  A control can be made up of many different XAML pages depending the intent.  Thus we need to ensure that we can properly control “state” within the context of the control.  However, when we leave that context, we cannot leave the Navigated event handler in place, less it possibly interfere with functionality in the rest of the application.

Once we have the selected State instance, we can process it however, we like:

        private void CloseStatePickerPage(IPicker statePicker)
        {
            if (statePicker.SelectedItem != null)
            {
                _selectedState = statePicker.SelectedItem;
                _chooserButton.Content = string.Format("{0} ({1})",
                           _selectedState.Name, _selectedState.Abbreviation);
            }
        }

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

Feel free to download the full source code, available from Skydrive:

 

Final Thoughts

Lets be honest, mobile applications, even mobile web applications, are not web applications, nor should they be treated and designed as such.  A mobile experience must be crafted to be more personal and intimate then the generic web application user experience which must have a wider appeal.  Mobile environments constrain what can be fit on a screen thus making it even more critical that developers understand how to determine exactly what they need.

Custom controls represent a way to combine existing controls or create some altogether new. In our example, we created more of a composite control as opposed to a full on new control, but the principles are the same.  Thanks the flexibility provided to use with XAML Control Templates, new controls can be very easily designed and implemented.

Working with the Facebook SDK from Windows Phone 7

Facebook has become a vital part of modern application development, both as a means to link users with their pre-existing social data, add to their social data, and as a form of validation.  In our new app we are developing, we are supporting both Facebook based authentication as well as normal authentication.
Within .NET there exists the Facebook C# SDK which is hosted on GitHub.  It is installed via nuget, but lacks documentation for what is available and how to use it.  Example code is available, but its very hard to find, and I have to succeeded in returning to where I found it.
Before we talk about Facebook, we need to talk about the authentication protocol being used by Facebook that allows it to be used in such a way: OAuth.  OAuth is widely used by many of the popular social networking sites such as Twitter, Foursquare, and Facebook.  Using OAuth we can obtain an “access token” which allows us to use the Facebook API.  For the app I am writing, I don’t plan to access Facebook directly, just use the token as a means to authenticate.  One quick side note, while I have not seen it in practice, I am told these “access tokens” do expire, most likely with lack of usage.
So, at this point, you’ve gone out to the website and seen the nuget statement, ran that to add Facebook Client SDK to your project.  Now lets use it.  I am just going to show you how to authenticate and then make a simple call using that authentication.  In addition, we will store the access token so it can be used again.

Authenticating

The important thing to understand is, when authenticating with OAuth, more often then not you will have to display the Facebook login page to collect the credentials.  But you should only have to do this once.  This is the code I used to generate the URL and then feed my Web Browser control:

var client = new FacebookClient();
var parameters = new Dictionary<string, object>();
parameters["client_id"] = AppId;
parameters["redirect_uri"] = "https://www.facebook.com/connect/login_success.html";
parameters["response_type"] = "token";
 
var uri = client.GetLoginUrl(parameters);
webBrowser.Visibility = Visibility.Visible;
webBrowser.Navigate(uri);

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

This code simply generate the URI we will pass to our web browser. Generally if a user has already granted access to the app, the call will simply redirect.  This is where our Navigated event handler comes into play.

FacebookOAuthResult oauthResult;
var client = new FacebookClient();
if (client.TryParseOAuthCallbackUrl(e.Uri, out oauthResult))
{
    if (oauthResult.IsSuccess)
    {
        string accessToken = oauthResult.AccessToken;
        ((WebBrowser) sender).Visibility = Visibility.Collapsed;
 
        SaveAccessToken(accessToken);
    }
    else
    {
        // user cancelled
        MessageBox.Show(oauthResult.ErrorDescription);
    }
}

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

This is a common way of handling this case.  The FacebookClient class, in this case, hides what is really happening.  If we get back the redirect URL we were looking for, then the operation completed.  The Access Token can then be acquired from that query string.
Notice the call to SaveAccessToken, ideally you would put this in the database, but in this case we are just storing it to IsolatedStorage.  This will also allow us to read it again later when we reaccess the application so that we can by pass having to ask Facebook for it again.

using (var store = IsolatedStorageFile.GetUserStoreForApplication())
{
    using (var stream = new IsolatedStorageFileStream("fb_access_token", FileMode.Create, FileAccess.Write, store))
    {
        using (var writer = new StreamWriter(stream))
        {
            writer.Write(accessToken);
        }
    }
}

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

Very simple and straightforward.

Usage

Using the Facebook Client class to make a request to Facebook is very simple.  Simply provide the AccessToken to the client via the constructor or by updating the appropriate property.  Keep in mind that UI blocking methods are not allowed on Windows Phone 7, thus we need to use the Async version (this predates the async and await keywords, so we cant use them).

string accessToken = ReadAccessToken();
var fb = new FacebookClient(accessToken);
fb.GetCompleted += fb_GetCompleted;
fb.GetAsync("/me");

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

Don’t forget to handle the completed event, the return is a JSON object.  With the client, if the call works you will get the JSON object as mentioned, null if it does not work.

Conclusion

Granted this example is ultra simplistic, it nevertheless demonstrates what is likely the most common usage of the Facebook API, authentication.  The truth is that over 900 million people/groups have Facebook accounts, thus it is a very handy authentication mechanism that can save the time involved in creating, and securing, your own authentication mechanism.