Hijacking Mobile Service Authentication

Recently, while developing Score Predict I ran into a snafu where my iOS version was rejected by the Apple AppStore.  There were two reasons for this rejection; one of the reasons was not surprising, the other one, however, was.  According to Apple, if I chose to rely exclusively on Facebook authentication, I had to use my granted FB access for something else in addition to authentication; a lesson I had to learn.  This effectively met I could either speed up the timeline and implement the FB capable features.  This would mean pulling the Android version (which had already been approved) and likely cost me the entire football season.  So I opted to create a supplemental manual login for Facebook only.

The principle issue was, I was relying on the generated Facebook username, given to me by mobile services, as a means to link data together.  In addition, I had already implemented user level authentication on the sensitive services and I did not want to provide non-social endpoints for the manual users.  So what to do?

Well as I looked at what makes the client authenticated, I realized it was the combination of a generated user Id and what I came to learn was a JWT (JSON Web Token) token, I previously referred to this as a Zumo token.  In addition, it is widely known that you can give the client a pre created token from a social provider to be used.  So I summarized that the same could likely be said for the Auth token.  If I could create it myself, I could likely get Azure Mobile Services to use it and the two logins types could use the same endpoints.

To begin with this, I knew I would need to determine how I might create a JWT token.  Lucky for me, I stumbled across this article: http://www.thejoyofcode.com/Generating_your_own_ZUMO_auth_token_Day_8_.aspx

In reality, all this is a simple hashing algorithm where the salt is unknown to the under user, this is what allows the security to exist, being signed by the Master Key.  For my project I created the following NodeJS module to house this logic:

// require external node modules
var crypto = require("crypto");

// actual node module
module.exports = {
    createZumoToken: function(expiryDate, aud, userId, masterKey) {
        function base64(input) {
            return new Buffer(input, 'utf8').toString('base64');
        }

        function urlFriendly(input) {
            return input.replace(/\+/g, '-').replace(/\//g, '_').replace(/\=/g, '');
        }

        function sign(input) {
            var key = crypto.createHash('sha256').update(masterKey + "JWTSig").digest('binary');
            var str = crypto.createHmac('sha256', key).update(input).digest('base64');
            return urlFriendly(str);
        }

        var s1 = '{"alg":"HS256","typ":"JWT","kid":0}';
        var j2 = {
            "exp":expiryDate.valueOf() / 1000,
            "iss":"urn:microsoft:windows-azure:zumo",
            "ver":2,
            "aud":aud,
            "uid":userId
        };

        var s2 = JSON.stringify(j2);
        var b1 = urlFriendly(base64(s1));
        var b2 = urlFriendly(base64(s2));
        var b3 = sign(b1 + "." + b2);

        return [b1,b2,b3].join(".");
    }
};

.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; }

Then it gets down to it, it is very straightforward.  It relies on the crypto library which is included as part of the overall Node setup you are given for every Mobile Service JS backend project.

In terms of usage, following the creation of the user, that is after the record has been inserted, I simply create the token and add it to the response (below):

var expiry = new Date().setUTCDate(new Date().getUTCDate() + 30);
var aud = "";
var master = "";
var token = jwt.createZumoToken(expiry, aud, user.id, master);

complete({ id: user.id, token: token });

.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 have yet to understand how the validation of these tokens works, what it is looking at because, aside from the Master Key, the aud is not stored anywhere.  However, this appears to work, so for right now, that is enough.

To utilize this is no different than if you were working with Facebook.  Below is some Objective-C code which handles the response to the create_user endpoint.

-(void)handleSuccessfulUserCreateWithData:(NSDictionary *)data {
    // get the values from the data
    NSString *userId = [data objectForKey:@"id"];
    NSString *token = [data objectForKey:@"token"];
    
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    [defaults setValue:userId forKey:@"UserId"];
    [defaults setValue:token forKey:@"Token"];
    [defaults synchronize];
    
    [self goToMainView];
}

.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 can see that we are simply storing the values as normal in the User Defaults.  They are then accessed through our getClient method from the ClientFactory class (below):

+ (MSClient *)getClient {
    NSURL *url = [NSURL URLWithString:@"https://scorepredict.azure-mobile.net"];
    MSClient *client = [MSClient clientWithApplicationURL:url
                                           applicationKey:@""];

    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    if ([defaults objectForKey:@"UserId"] != nil && [defaults objectForKey:@"Token"] != nil) {
        NSString *userId = [defaults stringForKey:@"UserId"];
        NSString *token = [defaults stringForKey:@"Token"];

        MSUser *user = [[MSUser alloc] initWithUserId:userId];
        user.mobileServiceAuthenticationToken = token;
        client.currentUser = user;
    }

    return client;
}

.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 all the same for both the manual and Facebook calls, thus the service works regardless of which login method is used.  The difference in the two is the UserId transmitted, which will be the generated Facebook username for the Facebook calls, but a randomly generated Guid for the manual calls.  This being the case, I ensured that a string is used to store the user associated with the data, thus joining is agnostic to this difference.

In reality, we are not really hijacking the login system, we are simply performing some impersonation.  I am still looking at the overall security of the Mobile Service with this approach, however, I feel that as long as the Master Key is kept secret, there should be little chance of a compromise.

DevLink 2013

Last week I attended the DevLink 2013 conference Chattanooga, Tennessee.  I really must tip my hat to all the people that work together to put together such a great event.  The sessions were amazing and I absolutely love the people and networking events.  This year, the team brought in, among others, Scott Hanselman to keynote at lunch on the second day.  A fan of his Hanselminutes podcast I was not disappointed.  The keynote focused on JavaScript and showed off some of what is being written, and how Microsoft is constantly working to make JavaScript debugging and HTML debugging easier and easier leveraging Visual Studio.  I must admit though, the best part of the talk was the humor and pure entertainment value.  Scott has an amazing ability to make you chuckle and laugh but communicate necessary information.

My focus with regard to the sessions was SPA.  While I have not had as much of a chance to work on SPAs as I would like at Centare I still enjoy knowing how to use frameworks like Angular, Ember, and now Durandal which builds on top of the excellent MVVM provided by Knockout JS.  To that end, I also sat in on the Object Oriented JavaScript session.  The speaker, from AppendTo and clearly very knowledgeable on JavaScript, showed that by leveraging the proper native constructs that JavaScript can emulate the features of an object oriented language.  It was really neat and provided a glimpse into how framework designers do certain things to keep things more organized.

This was my second time attending DevLink, but it was my first time I had been accepted at a speaker.  After a good show at That Conference I was eager to prove I could handle speaking at larger conferences.  My talk started very well, some great information.  But then we got into the demos and I realized that I had not prepared as well as I should have.  I forgot to the grab the source for one of my demos, but I was able to use the Azure Management Portal to show off what would have been the result.  However, the central piece of the talk: the YouTube Voting Demo, fell apart.  I learned many things about keeping a demo on a USB stick, such as Windows 8 apps dont like their source code being on USB sticks, especially not those formatted with NTFS.

Needless to say, I was grateful most of my audience stuck with me, but I was horribly embarrassed and disappointed as I was not able to even get through my talk all the way.  Whether it was hardware or not, I obviously rested on my laurels after That Conference and assumed the code would work without me having touched it.  The only saving grace for me is, I am giving the same talk on Wednesday at Chicago Downtown .NET Developer Meetup, so its a quick chance for redemption.

But I refuse to let me poor performance take away from what was a productive and valuable conference going experience.  I look forward to attending next year as well.

Speaking at That Conference

For those not aware, the technology community of the Midwest has come together to create yet another amazing conference.  This was the second time That Conference (http://www.thatconference.com) was held at the Kalahari in Wisconsin Dells, and it was my first time attending. I really must give my thanks to Clark Sell and the rest of the planning committee for putting things together, I was very much reminded of Codemash (http://www.codemash.org).

Initially, I was not going to speak at That Conference but sometimes things happen and the outcome works in your favor. Josh Twist, the PM on the Windows Azure Mobile Services team at Microsoft, was initially slated to speak on Mobile Services, however, due to a scheduling conflict, ended up withdrawing.  I was very honored when he asked me to take his place. However, I decided my Push Notifications presentation was simply not appropriate for That Conference, I would need to discuss WAMS with a greater feature scope. This meant, creating an entirely new talk.  Thankfully, due to my commitments and other plans for August, Centare had been allowing me to remain relatively idle, I used this time to construct a new presentation, based largely on Josh’s BUILD 2013 talk.  I managed to complete the slide deck and demo’s within the week and thanks to the cooperation of my fellow Centarians, I was able to get in enough practice to make the presentation a rousing success at That Conference.

For me, it was a huge dream come true.  While I have been gratefully chosen to speak at many conferences in the past, That Conference was by far the biggest and most visible one to date; I have been trying to speak at Codemash for three years, but its not easy, there are MANY good speakers out there.  I was very thrilled and happy to share my views on Azure Mobile Services with the attendees at That Conferece.  I look forward to a success engagement next week at DevLink in Chattanooga, Tennessee and, with some luck, I will get to speak at Codemash in January of 2014.

Thanks again to That Conference for allowing me to speak and thanks to everyone who came and enjoyed my session.

Push Notifications with Azure

Recently I have been working on a new talk for speaking engagements.  The topic is Push Notifications which is something which come to the forefront more and more for app development.  As this happens the various OS players have continued to enhance the Push experience within their platform.  The talk was aimed at explaining Push Notifications, their importance, and how to support them in a cross platform way.

Having used Parse in the past I immediately defaulted to using it for the Android and iOS side of my talk, it seemed logical. I was midway through my presentation when I attended a talk at Chicago .NET Developer Group which focused on using Azure as a backend storage for Windows 8 apps.  Now, I had heard about Mobile Services and knew that Microsoft had been working to develop this service.  But I had heard it was limited to only Apple outside of the Microsoft stack and that it was still a work in progress; the talk, done by Adam Hoffman, showed me how wrong I was.

I know from experience that doing push notifications, even on Windows Phone, is not easy and requires a lot of knowledge about XML and the networking stack; so imagine my shock when I realized that Mobile Services could not only handle this for me for my Windows apps but also my iPhone and Android apps.  That with a single line of JavaScript run through node.js on Azure Mobile Services I could easily send notifications to any platform I desired.  And finally, imagine my glee when I saw the setup and just how remarkably easy it was.  Needless to say, my jaw about hit the floor and I promised Adam to check out Mobile Services over the weekend to see if I could fit it into my talk.

Forget fitting it in, I dont think I will ever use Parse again.  Over the course of one weekend I went from being behind in the development of my demo to being ahead of schedule.  I was able to completely overhaul my demo apps architecture and replace it with something that is very clean and consistent.  And, most importantly, I got consistent functionality from Android, iPhone, and Windows Phone apps.

Using the node.js + data table integration point, I was able to write a simple JavaScript script file which handles all of my push notifications for all of my clients, the details for those clients is stored elsewhere as the one shortcoming of the Mobile Services REST API vs Parse is the lack of an endpoint for sending a Push Notification via REST; I am sure the team will address this, in the meantime we have the Storage Table REST API which I was able to use in its stead.

The other nice thing is since Mobile Services uses SQL Azure as the storage mechanism you can access it with SQL Server Management Studio.  In this way you can view your data and interact with it in a much more robust way than with Parse (I cant speak to other services like Urban Airship or Pusher).

I do not want to give away the details of my talk on this post, that will  happen after its debut at Chicago Code Camp on April 27th, but I have to be honest.  What Microsoft is doing with Mobile Services is truly amazing; to think they even took the step of using GCM (Google Cloud Messaging) for Android Push Notifications when most Android devs either arent aware of it or dont use it shows an impressive amount of foresight.

If you havent checked out Mobile Services, do yourself a favor and do it.

The Conference Delta API

So I haven’t been blogging a lot, mainly because I have been busy, both at work and on the side.  During DevLink I had an idea come to me for a new project, which would test me in many of the new technologies that Microsoft is developing, specifically: Azure, WebAPI, and Windows 8.

In recent years, many conferences have begun exposing a REST API listing their session and speaker information.  Conference-goers have been encouraged, and have done so with remarkable results, to create smart phone apps to negate the need for attendees to use paper to find sessions.  While these apps have been largely impressive, they tended to suffer from one major flaw: load.  Whenever someone opens their app they generally have to download all of the latest data to ensure that any changes (as happen frequently at conferences) are taken into account.  With so many developers accessing the API load times can be extended, so much so that people tend to fall back on using the physical medium.

The project is designed to address this shortcoming as well as provide me a chance to dabble with Microsoft new Windows 8 platform.

The Poller

To address the load issue it is necessary to provide an API which can, along with providing the latest conference information, provide changesets which detail, simply, what data has changed.  These would be smaller packets.  To facilitate building these changesets, I created a Azure Worker Role which is designed to poll an API every so often and determine what has changed, if anything.  This data is then stored in a SQL Azure table.  The next step was to provide a way for users to access these changesets, along with the latest information for the conference.

The Delta API

So, in what I call a Proxy Pattern (I am sure it has a more formal name), I am creating a web instance to sit in front of another instance.  For the current implementation 4 things will be provided by this proxy API: Speaker information, Speaker Change information, Session information, and Session Change information.  This is a simple WebAPI which can return the data in JSON or XML format, depending on what the consumers asks for.

The Push Service

So one of the central features in Windows 8 and Windows Phone 7 is the MPNS (Microsoft Push Notification Service).  By utilizing this proxy approach I can allow for Push notifications about conferences changes to be pushed to subscribers.  I am also thinking, I can notify when a session is about to start, as a reminder.  I am hopeful that should my pilot of this system prove successful I can extend the push notifications to Apple and Google (via UrbanAirship, most likely).

The Clients

Because the DeltaAPI provides the data in JSON and XML formats, I could write a client for ANY platform, but as I carry a Windows Phone and I will be buying a Surface, I am targeting the Windows platform.  I am looking for other developers who would be interested in developing for Apple or Android platforms.  At the moment, I am working on the Windows 8 client application having finished the Delta API, Poller and Azure deployments.  I expect the Windows 8 client to be completed by end of week.  I am trying to do this ahead of a critical date for this project with respect to the pilot.

The Pilot

At the moment, I am awaiting the release of the CodeMash session selections (I may be one of them).  Once the API is released I intend to target it and begin building the data.  It will require some code changes as DevLink (which I used as a model) provides different information than CodeMash.  I am looking for anyone interested in developing apps for Apple and Android as I will simply not have time to address these platforms.

So there it is, its ambitious and part of a much larger goal I have for distributing conference data.  I am hoping for a solid pilot at Codemash this year.

Moving to Centare and Chicago

I am pleased to announce that, as of March 5, 2012, I have accepted the offer from Centare Group to work for them as a consultant out of their Downtown Chicago office. My start date will be April 9, 2012. Due to my responsibilities and knowledge with the current project at Meijer I am remaining on staff with Meijer until March 30, 2012.

I am extremely excited about this opportunity and look forward to the new and exciting challenges as a consultant in Chicago.

The Next Step: Command Binding

One of my biggest goals with this application is achieving a complete understanding of how the MVVM pattern can be applied and how to achieve strong code coverage through unit tests.  Thus far the first portion of the goal is proceeding nicely, regrettably I am having difficultly with the second piece.

One of the nice thing I am finding is by using an Dependency Injection model for class type resolution I can greatly cut down on the amount of code on my code behinds.  I was already familiar with this aspect with respect to properties and using INotifyPropertyChanged but now I am finally getting a chance to apply it to commands.  For example, I defined the following interface to define the contract which a view model must follow for the Venue management screen:

   1: public interface IVenuePageViewModel

   2: {

   3:      /// 

   4:      /// The list of stored venues from the repository

   5:      /// 

   6:      ObservableCollection Venues { get; }

   7:  

   8:      /// 

   9:      /// The ICommand instance which will handle the Saving operation

  10:      /// 

  11:      ICommand SaveCommand { get; }

  12:  

  13:      /// 

  14:      /// The ICommand instance which will handle the Add operation. Prepares the Venue instance appropriately

  15:      /// 

  16:      ICommand AddNewCommand { get; }

  17:  

  18:      /// 

  19:      /// The ICommand instance which will handle the Cancel Operation for active Save state

  20:      /// 

  21:      ICommand CancelCommand { get; }

  22:  

  23:      /// 

  24:      /// Select a Venue to be the active Venue

  25:      /// 

  26:      /// 

  27:      void SelectVenue(Venue venue);

  28:  

  29:      /// 

  30:      /// Indicates the current active venue

  31:      /// 

  32:      Venue Venue { get; }

  33:  

  34:      /// 

  35:      /// Return a list of States that can be displayed to the user

  36:      /// 

  37:      IList States { get; }

  38:  }

What this gives me is a way to implement multiple view models and allow them to operate on the same or different views.  This achieves a very nice, clean separation between the view model code and the view itself.

ICommand

One of the neat things that WPF can allow you to do is to bind to commands.  This removes the need for the view to specify an event handler and allows the event to be directly routed to the view model where it can be handled.  I created two classes which implement this interface: EventCommand and ActivatedEventCommand.  This is how I perform the binding in code and XAML:

   1: /// 

   2: /// The ICommand instance which will handle the Saving operation

   3: /// 

   4: public ICommand SaveCommand

   5: {

   6:     get

   7:     {

   8:         return new ActivatedEventCommand(() => _canSave, SaveVenue);

   9:     }

  10: }

  11:  

  12: /// 

  13: /// The ICommand instance which will handle the Add operation. Prepares the Venue instance appropriately

  14: /// 

  15: public ICommand AddNewCommand

  16: {

  17:     get

  18:     {

  19:         return new EventCommand(CreateNewVenue);

  20:     }

  21: }

   1: <Button Style="{StaticResource CommandButton}" x:Name="btnAdd" HorizontalAlignment="Left" Margin="10,5,0,0"

   2:         Command="{Binding Path=AddNewCommand}" Grid.Column="0" Grid.Row="2" />

   3:  

   4: <Button Style="{StaticResource CommandButton}" x:Name="btnSave" HorizontalAlignment="Left" Margin="0,0,7,0"

   5:         Command="{Binding Path=SaveCommand}" />

The only real difference between EventCommand and ActivatedCommand is that the activated variant will update its Enabled status based on the return value of the provided lambda.  This is curcial because once the binding here it functions like any other property, with one slight twist.  Whenever the property changes ICommand.CanExecute is polled.  If the method returns false, then the command will be disabled.

What this means is whenever I notify that SaveCommand has changed WPF will set IsEnabled to the boolean return value of ICommand.CanExecute.  This allows the interface to update the enabled state of components automatically based on the internal state of the view model.  A very powerful concept, especially when you then combine it with ElementBinding.

   1: <TextBox x:Name="txtVenueName" Width="200" MaxLength="70" HorizontalAlignment="Left" Text="{Binding Venue.Name, Mode=TwoWay}"

   2:          IsEnabled="{Binding ElementName=btnSave, Path=IsEnabled}" />

Now, not only does the Save button automatically disable itself when saving is not allowed, it is being watched by other elements within the form who will set their IsEnabled state based on whether the Save button is enabled.  Through adding almost no code, I am quickly able to provide a clean intuitive interface which switches state intelligently.  This is the code is my code behind:

 

   1: public partial class ManageVenue : UserControlBase

   2: {

   3:     public ManageVenue()

   4:     {

   5:         InitializeComponent();

   6:     }

   7:  

   8:     private void Venue_Loaded(object sender, System.Windows.RoutedEventArgs e)

   9:     {

  10:         LayoutRoot.DataContext = InjectionContainer.Get();

  11:     }

  12:  

  13:     private void dgVenue_SelectionChanged(object sender, SelectionChangedEventArgs e)

  14:     {

  15:         if (e.AddedItems.Count > 0)

  16:             InjectionContainer.Get().SelectVenue((Venue)e.AddedItems[0]);

  17:     }

  18: }

Since we define each ViewModel as a Singleton, thereby allowing only one instance to event exist we don’t even need to worry about casting or accessing the LayoutRoot property here.  However, I wonder what will happen if I hit my “Back” button and do not reset the internal state of the view model. Could be kind of weird when I come back to this page later on.  But Ill check that out later.

Conclusion

The MVVM pattern is a very powerful pattern and requires much discipline and understanding to fully implement.  This is why it is common for programmers to rely on a framework like Caliburn.Micro to do this for them.  That said, I have often found that understanding what you are doing makes using a framework much easier.  I can already see some of the concepts I didn’t quite grasp in Caliburn making more and more sense to me.  With any luck when I do finally decide to transition this application to use Caliburn the switch will be very easy.

Command Binding is quickly becoming one of my new favorite aspects in WPF, though it does seem you can command bind everything, case in point the SelectionChanged event on the DataGrid.  But, it does make things significantly cleaner.  I am also certain that when I focus more on the testing aspect of this it will be easier to test with all the view logic in the View Model instead of the code behind.

Building a Data Layer with Sterling

For our Team Trivia Game Management application I needed a local database to store data to fulfill my requirement of being able to support the application regardless of connectivity.  I looked at a variety of database systems but with the additional requirement that the app run on a Mac my options were limited.

I had heard about Jeremy Likness’s Sterling project a year ago or so and always fascinating.  I have actually, myself, built a similar conceptual idea using Isolated Storage on Windows Phone 7.  However, Jeremy’s project takes into account and handles many more of the complicated scenarios that a basic wrapper would not.  And because it essentially functions as a file system wrapper to give the impression of a database it is platform independent and I felt fulfilled my needs nicely.

Building the Engine

Sterling operates with the notion of Engine.  The Engine is the driving force behind your database and is responsible for creating the database.  Ideally we would like the Engine to be created automatically once our application starts.  This will remove the need for specialized code.  In .NET we can use a Lifetime object to carry out this.  Lifetime objects are creating by having a class implement the following interfaces which allow it to interact at different points during runtime:

  • IApplicationLifetimeAware
  • IApplicationService

Implementing these two interfaces will allow you to carry out operations at different points during the operation.  For our purposes we only care about Starting and Exiting.  To get the application to actually care about this class you need to specify it as a Lifetime object.  The best way to do this is to add it to App.xaml.  The XAML code to do this is shown below:

2012-02-19_1225

Composing the Database

Within the Engine, you must register your database and build up the table definitions.  In Sterling there is no SQL, the tables are built from classes which represent the rows contained within the table.  This being said, before you can define your database, first compose your entities.  For my application, we are starting with two entities: Team and Venue.  The code is shown below:

   1: public class Team : EntityBase, ISimpleEntity

   2: {

   3:      public int TeamId { get; set; }

   4:      public string TeamName { get; set; }

   5:      public string LeagueId { get; set; }

   6:  

   7:      #region Implementation of ISimpleEntity

   8:  

   9:      public int Id

  10:      {

  11:          get { return TeamId; }

  12:          set { TeamId = value; }

  13:      }

  14:  

  15:      #endregion

  16:  }

   1: public class Venue : EntityBase, ISimpleEntity

   2: {

   3:      public int VenueId { get; set; }

   4:      public string VenueName { get; set; }

   5:      public string Address { get; set; }

   6:      public string City { get; set; }

   7:      public string State { get; set; }

   8:      public string ZipCode { get; set; }

   9:      public bool Active { get; set; }

  10:  

  11:      #region Implementation of ISimpleEntity

  12:  

  13:      public int Id { get; set; }

  14:  

  15:      #endregion

  16:  }

Once you have your entities, you define a custom class representing your database which inherits from BaseDatabaseInstance.  The class representing my database is shown below:

   1: public class TeamTriviaDatabase : BaseDatabaseInstance

   2: {

   3:      #region Overrides of BaseDatabaseInstance

   4:  

   5:      public override string Name

   6:      {

   7:          get { return "TeamTrivia"; }

   8:      }

   9:  

  10:      protected override List RegisterTables()

  11:      {

  12:          return new List()

  13:                     {

  14:                         CreateTableDefinition<Venue, int>(m => m.VenueId),

  15:                         CreateTableDefinition<Team, int>(m => m.TeamId)

  16:                     };

  17:      }

  18:  

  19:      #endregion

  20:  }

When you inherit from this class, you are required to implement the abstract method RegisterTables.  In this class, as you can see above, we specify our class names through the CreateTableDefinition call.  The second generic type specifies the type of the key.  Sterling doesn’t support super complex keys, nor do I think you would want them.

With this code in place we can safely know that our database will be saved and loaded from the disk when the application starts.  Our next step is deciding how we will access our data.

Creating the Repositories

I am a big fan of the repository pattern.  I think it lends itself very well to modern application design where objects are used heavily to represent rows in databases.  Using objects gives you a number of advantages, such as dirty tracking and abstraction.  This allows finite control over how Entities are constructed and operate.

When I implement the pattern I like to create a RepositoryBase abstract class to contain the common used methods for my repositories.  This might include a general save method which looks at the items in the repository, determines which are dirty, saves the items, and resets the dirty flag.

Next, because I am a huge fan of Dependency Injection as a means to stitch together the data layer of application while continuing to maintain proper decoupling between classes while enforcing “design by contract” principles and making testing easier.  To facilitate this I usually create the IRepository interface which defines the common methods for all repositories.  The code is below:

   1: public interface IRepository where T : EntityBase

   2: {

   3:      /// 

   4:      /// Add an item to the repository

   5:      /// 

   6:      /// The item to add to the repository

   7:      void Add(T item);

   8:  

   9:      /// 

  10:      /// Get an item based on a predicate condition

  11:      /// 

  12:      /// The condition to find the item with

  13:      /// An instance of T from the Repository or null

  14:      T Get(Func<T, bool> predicate);

  15:  

  16:      /// 

  17:      /// Return a list of all items within the Repository

  18:      /// 

  19:      /// 

  20:      IList GetAll();

  21:  

  22:      /// 

  23:      /// Save dirty items in the repository

  24:      /// 

  25:      void Save();

  26:  

  27:      /// 

  28:      /// Marks all instances within the Repository as Deleted

  29:      /// 

  30:      void Clear();

  31:  }

This gives us an adequate template to build all repositories, which allowing RepositoryBase gives all the support we need to interact with the database.  I decided to use Ninject for Dependency Injection.  To make the binding easier I created the IVenueRepository interface which inherits from IRepository and provides Venue specific methods.

Interacting with the Data Layer

In a simple case for interaction, I might call on the Repository directly:

   1: public partial class VenueSelect : ChildWindowBase

   2: {

   3:      public VenueSelect()

   4:      {

   5:          InitializeComponent();

   6:      }

   7:  

   8:      private void OKButton_Click(object sender, RoutedEventArgs e)

   9:      {

  10:          var repository = InjectionKernel.Get();

  11:          repository.Add(new Venue());

  12:      }

  13:  

  14:      private void CancelButton_Click(object sender, RoutedEventArgs e)

  15:      {

  16:          var repository = InjectionKernel.Get();

  17:          repository.Clear();

  18:      }

  19:  }

InjectionKernel is a property I defined in ChildWindowBase which refers to my Ninject Injection container.  Calling Get specifying the interface I want gives me the concrete class mapped to the interface via the Ninject Module.

For more complicated operations, I might define a service which can encapsulate the interactions between repositories.  For simpler pages, you might refer to the repository directly, as shown above.

Future Plans

This data layer is not totally complete and contains a number of things I would like to improve upon.  For example, we can utilize Sterling Triggers to support an AutoNumber feature for keys.  The problem with this is shown below:

   1: /// 

   2: /// Called by an application immediately before the  event occurs.

   3: /// 

   4: public void Starting()

   5: {

   6:     Activate();

   7:     Database = SterlingDatabase.RegisterDatabase();

   8:  

   9:     // Register the Triggers for the Database

  10:     Database.RegisterTrigger(new IdentityTrigger(Database));

  11:     Database.RegisterTrigger(new IdentityTrigger(Database));

  12: }

Within the Engine the RegisterDatabase call returns our ISterlingDatabaseInstance which is what we will use to save/load data.  The problem is, the IdentityTrigger requires this database instance so that it can determine the starting index for new instances.  I personally hate seeing code where an object method is called and the same object is passed in the same call.  I feel that DI can solve this, but I ran into problems with double initialization of the database.

I also still have to develop the services layer which allows the encapsulation of operations involving multiple repositories.

Getting Started with Silverlight Out of Browser

So, its been a long time.  My work at Meijer has certainly become all consuming, but recently I have made a pledge to myself to get back into programming on the side.  I really had forgotten just how much fun coding on the side was.  Even better, current opportunities in my life allowed me a chance to really create something.

My friend moonlights as a Trivia Game host.  Essentially, various restaurants in the area hold games where questions are asked and teams compete for prizes.  Its very fun and lively atmosphere that is beneficial to all.  However, I noticed that much of the score keeping during these games was done differently depending on the host.  Sometimes it was pen and paper other times Excel.  Bottom line, very manual and error prone.  Wanting to help I offered to write an application to make this process easier for the hosts.

Designing the Application

I initially planned for the application to be a WPF application.  Since Internet connectivity was not always guaranteed, I decided for the first version to rely totally on an SDF file. I also decided to model the application off of Microsoft Office, since this is what most people most closely identified with.  Thus I downloaded and started using the Microsoft Ribbon Control for WPF.  This design came a good deal of the way and I showed my prototype to my friend and several other hosts.  Only then did I realize I missed the fact that the majority of the hosts use Macs, so WPF was immediately out.

I contemplated other platforms I could use since I wanted to make the application highly available and didn’t want to write multiple versions.  Eventually, through the advice of my friend Ryan, I decided to go with Silverlight Out of Browser since it is capable of running on a Mac.  At the same time I decided I wanted to change the design thanks to feedback I realized that some of the more complex features I was planning were not necessary.

Version 2

This time I decided to design the application using much of what I know from mobile apps.  I wanted to interface to be clean and to the point.  The people using this application are not exactly tech savy and I didn’t want to confuse them with lots of clicks and buttons.  The results was the interface shown below:

2012-02-11_1653

Note: The Large Empty middle section will be used as kind of a dashboard to see games played, winning teams, things like that.

The main goal of the interface was to be very simple and straightforward.  The level of visual control you get in XAML is really remarkable and can really lend itself to developing very clean and responsive interfaces.  In this application, the main action is tracking a game, hence a shortcut was broken out.

Lesson Learned: Visual Design vs Technical Design

One of the things I feel developers are famous for is attempting to design and implement the architecture of an application way too early, I know I have done it many times.  One of the things I am trying with this application, and it does seem to be working very well, is to not write any code, other then for navigation.  I want to establish the visual aspect of the application and let that guide the rest of my design.

So far, this is working very well, as I have moved very quickly through design without getting distracted by technical elements yet.  I know that I want a DI layer so I can easily change the business layer in and out as needed, since I do plan for a web service to be involved down the road.

Navigation

Oddly enough, it seems within Out of Browser applications, no NavigationContext is available.  Coming from Windows Phone 7 I am very familiar with the notion of navigating from XAML Page to XAML Page.  My first attempt at this was thwarted because, by default, UserControls are used heavility within OOB.  I decided to change the inheritance structure of this so I was using Silverlight Pages.  Sure enough, doing this gave me access to the NavigationService property.  However, this property was null.

Perplexed, I Googled for a reasons and/or workaround but found nothing.  I decided to take matter into my own hands and simply relegate my content screens to UserControl objects, inheriting from my custom base class UserControlBase.  Doing this allowed me to set an event which I could use to change the visual display based on the page requested.

Now, when I want to change to page I simply raise this event with the appropriate enum which inidcates the PageType I want.  Its not very sophisticated, but it does work.  I would like to know what Microsoft recommends to fulfill this scenario.

Initial Thoughts

My initial thoughts is that Silverlight OOB does seem to present a very interesting avenue for cross platform application development.  Other friends of mine did recommend HTML5 and I did deeply consider it.  However, I had a desire to use Sterling and thus felt that using OOB seemed to be a better approach.

Starting my Windows Phone 7 App

As the Pay It Square Android app continues to gain in popularity I have decided to turn my attention to the other platform I am working to develop my knowledge for: Windows Phone 7.  As a .NET programmer I have longed for the ability to use C# and the other features of .NET to create mobile apps, WP7 gives me that chance.  I have had a chance to play with the platform in the past and even created a couple simple apps.  However, I decided it was time to do something serious and so I started my journey to making the Windows Phone 7 version.

This will be the first part in a series of posts detailing my experiences and thoughts on the platform at different stages.

Planning

I started off by planning the data architecture for my application.  I am a big believer in using Dependency Injection and Reflection to handle common tasks.  Very often with such systems you have to transmit data over the wire in a string based format (JSON, XML).  I understand where the rules of not using reflection in mobile systems comes from, I just think when platforms require a Duel Core chip, you can start to throw those sort of rules out the window.

I decided for my design, I wanted to try for a Repository pattern fronted by a Service based middle tier.  Basically, my pages would talk through services to repositories which would handle the communication to the web service in either XML or JSON format.

So right at the start, I hit a bump.  Whether its due to lack of maturity or just uncertainties about the platform, no one has really come up with a good way to fully integrate DI into the WP7 development experience, and least nothing compared to Guice on Android.  I looked at things like Funq and Caliburn.Micro, all of which seem incomplete to me or require more moving parts then I want to maintain.

In the end, I settled for straight Ninject and went about figuring out a way I could integrate this in myself using their WP7 bits. After not finding a pattern I was in love with I decided to work on the UI instead while I pondered good implementation patterns.

The UI

In my opinion, one of WP7 strengths is XAML and the level of customization that you can achieve by defining your own templates, this is made even easier with Blend.  However, to say this is easy is a bit of a misnomer in my book.  Perhaps it is because I am so used to DrawableXML in Android and the simplistic nature to quickly apply common design idioms to controls that I feel like WP7 gives you almost too much.  Lets face it, to really make XAML work well, you have to be a decent designer as well.

But I decided to dive in anyway.  The thing about WP7 is they do offer you default styles and therefore the ability to automatically get a good look and feel.  While this works well for simple apps, step into a more complicated app with a specialized color scheme, such is the case with Pay It Square.  Besides, good learning experience.

Conclusion

My final resolve was to skip out on data architecture planning and head straight to UI design with a basic concept of what I wanted.  The idea here is to establish application flow first, something that I consider very difficult in Windows Phone 7 due to the “difference” in the way the frames are handled.

I find that Microsoft has elected to, not surprisingly, stick with many of the idioms that they perfected from the web.  Thus thinking about each screen as a “page” rather then a “screen” makes more sense.  The only challenge with this is managing the back stack, since you can no longer mark a screen as finished (as in Android) and have it removed from the stack.  All you can rely on is catching an invalid flow movement and redirecting, much like with the back button in web applications.

One has to wonder if this resemblance to the web is intentional and thus represents Microsoft’s fence position between mobile web and native mobile.  Only time will tell.  For now I am moving through the process of creating the various templates that will comprise my interface.