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.

WP7 Async Data Access Pattern

One of the great things that I enjoy about Windows Phone 7 is the lengths Microsoft went to to make development easy and fun.  And of course, me being a .NET programmer by trade, getting to use .NET was pretty awesome too.  In my mind, Microsoft has done an excellent job communicating the ideas of the platform and the need to “control” the experience, in much the same way Apple does.  This “control” is necessary; mobile platforms do not, and cannot, offer the same freedom of expression we developers are used to in client apps and, in many ways, on the web.

One of the tight lines Microsoft has tried to walk over the years is the line that allows experienced programmers to use their knowledge and be creative while still providing the “protection” that keeps inexperienced devs from shooting themselves in the foot.  It is a difficult act to pull off, and Microsoft has been pretty good about getting it right, though rarely on their first try.

I came across something in Windows Phone 7 that really cramped my style recently.  The notion of forced asynchronous behavior in two areas.  Now, I have done a lot of programming in Android and I love their model.  Wrap your long running operation in AsyncTask.  This takes the operation off the UI thread thus mitigating the chance that OS will ask the user to kill the application (ANRing).

In Windows Phone 7 methods that are anticipated to be long running are async by default.  While this is good for novice programmers, it can make the OS seem inflexible in certain case.  For me this was mainly because the OS forces Web Requests to be Async.  My preferred approach would be to wrap a synchronous Web Request in a Background worker.  Since I can only this if I pass Action around, I decided to look for something different:

The Task

To start, I decided I was going to have to break apart the request from the processing since I knew I was not going to be able to make a web request synchronously, even if I wrapped it in a BackgroundWorker.  Thus I created the TaskBase serves as the base class for all tasks.  The centerpiece of this class is the Execute(Action) method, the source is shown below:

   1: /// 

   2: /// Perform the actual request

   3: /// 

   4: /// 

   5: public void ExecuteTask(Action<string> onRequestComplete)

   6: {

   7:     var request = new RestRequest(RequestUri, RequestMethod);

   8:     request.AddHeader("X-PayItSquare-AppKey", Config.AppKey);

   9:     if (RequiresAuthentication)

  10:         request.AddHeader("X-PayItSquare-Token",

  11:           CustomContext.Current.AuthToken);

  12:  

  13:     // add the parameters

  14:     foreach (var kv in _parameters)

  15:         request.AddParameter(kv.Key, kv.Value);

  16:  

  17:     // make the request

  18:     var client = new RestClient();

  19:     client.ExecuteAsync(request, response =>

  20:        onRequestComplete(response.Content));

  21: }

The idea here is that any task will result in a string being returned from the web request.  What the format of that string is, we do not care, it doesn’t matter.  (this code is using RestSharp library for the Rest request management)

The process of interpreting the string is the second part of the pattern.

Dependency Injection

I am not someone who believes Dependency Injection should be taboo on mobile devices.  Modern devices are extremely powerful and the applications we creating are becoming more complicated to the point where they can benefit from DI.  I use Ninject with my application to keep good separation and allow me to “design by contract”.

The Repository

I prefer to use the repository pattern to facilitate data persistence.  I can also use Ninject to inject various types of repositories each with the logic to parse the response string into whatever format.  For example, in Pay It Square I can load my repository using the following logic:

   1: /// 

   2: /// Loads the collect pages for the user into the repository

   3: /// 

   4: public void Load(string responseContent)

   5: {

   6:     XDocument document = XDocument.Parse(responseContent);

   7:     _collectPageList = (from xe in document.Root.Elements()

   8:                         select MakeCollectPage(xe)).ToList();

   9: }

With this pattern the purpose of the repository becomes clear. Interpret the response strings and return the appropriate information to the service layer to process the result.

This pattern’s purpose is to allow the Task execution to continue to be Async which is the one portion which is really the one portion that needs to be async.  Once the response string is generated the service and repository jump into action to parse and process the result.

Hope this helps some people when it comes to programming data centric applications in Windows Phone 7.

Remove your Screen from the Back Stack

One of the most important things in mobile application developer is management of the page stack.  You can give your user all the fancy glitzy effects you want but, at the end of the day, like and website your ease of navigation is tremendously important.  Users will want to go back and will not take kindly to going to pages that are unnecessary or redundant.

I do this in Android all the time with login pages.  When my app first starts, if I don’t detect any kind of pre-existing authentication, I ask the user to log in.  When the user initiates the login task, I place the request on a separate thread and use a progress dialog control to hold the user on the login screen until the operation.  Often you would see something like this in the result code:

   1: private void completeLoginOperation(String token) {

   2:     myPreferences().setAuthToken(token);

   3:     myPreferences().setStoredUsername(txtUsername.getText().toString());

   4:     startActivity(new Intent(this, MainActivity.class));

   5:     finish();

   6: }

On the last line we call the method finish().  What this does is kill the activity.  What does this mean?  This activity will be “finished” and removed from the stack. Hitting back immediately after arriving on MainActivity will cause the application to exit.

This is a very nice, clean effect and will allow the application to function as the user expects.  One of the important tips for getting the effect to work properly is to pick the start up screen correctly.  In the case of the application above I used a “splash screen” which made the determination which pages to go to on the start.  You could have also done the check, in Login, just remember to do it on a separate thread and inform the user what is happening, otherwise you will get ANRed.

This same principle is vital in Windows Phone 7 as well.  However, the application development model differs considerably from Android.  Where as Android feels like an application, WP7 tends to feels like developing a website.

Since all WP7 apps are required to have a splash screen, you can do most of the load in App.xaml.  I am still trying to work out how you could navigate to a certain page from App.xaml.  For now, make your startup page your login screen.  Use the Loaded event in your login page to check if the application is authenticated.  If it is, redirect to your main page.  In this way you are preventing the login screen from ever being displayed if the application is authenticated.

Windows Phone 7 states in its design requirements that Silverlight application are not permitted to exit programmatically.  To kill an application the user must either hit the ‘Start’ button or hit ‘Back’ when no other pages exist in the stack.  While this makes sense, it is somewhat of nuisance is you are coming from an environment like Android.  Nevertheless, with the release of Mango an additional API call was added to allow manipulation of the back stack.

For each page in my application, I inherit from a common base class.  Any page that requires authentication, I derive from this common base to support authentication checks.  This was a common pattern I used when developing web applications so as not to duplicate the security check on each page.  The code for the security check is below:

   1: protected override void OnNavigatedTo(NavigationEventArgs e)

   2: {

   3:     // if the user is not authenticated, send them back for authentication

   4:     if (!CurrentContext.IsAuthenticated)

   5:         NavigationService.Navigate("/Visual/Login.xaml");

   6:  

   7:     // if the user has just come from Login

   8:     // remove it from the stack so they dont hit when pressing back

   9:     var entry = NavigationService.BackStack.FirstOrDefault();

  10:     if (entry != null && entry.Source.OriginalString.Contains("Login"))

  11:         NavigationService.RemoveBackEntry();

  12: }

The logic here is, if the page being displayed is navigated to from the login page, we will call NavigationService.RemoveBackEntry().  This call will remove whatever the last entry in the BackStack is, in this case the login page.  This is a new call allowable by the Mango upgrade.  In effectively simulates the “finish” from Android, though quite as cleanly.

The end result is the login screen is effectively removed from the stack and is never shown to the user, even though it is the application start page.

I like Windows Phone 7, but you can clearly see the differences between it and a more mature OS like Android.  I have confidence, though, that as Microsoft continues to evolve their OS and open more API calls to developers.  Right now, it seems they are trying to prevent developers from writing apps that would create problems that damage the experience they are trying to provide.  For example, apps that do everything on the UI thread and cause lock ups and freezes.  As a more proficient developer my experience causes me to view these sorts of measures as headaches.  But I understand their reasons and hope that they lead to wider adoption of the OS.

Designing an Overlay Message in WP7

As I continue working, slowly, on the Pay It Square app for Windows Phone 7 one of my points of emphasis is the UI and the design experience.  One thing that I have learned is that, unlike Android, WP7 does not give you a whole lot, even with the Toolkit, for certain effects; for example modals and overlays.

This is not a huge problem though, as the XAML gives you an incredible amount of flexibility in designing the look and feel of an application.  So, while the controls may not come pre-built, we still have the opportunity to build our own.  The following is an example of the Pay It Square Overlay in action:

2011-10-17_1114

This produces a very nice effect which keeps the user informed and prevents them from making a double request.  The code to produce this effect is quite simple.

Microsoft provides the System.Windows.Controls.Primitives namespace which contains all sorts of goodness and pieces that you can use to make your own controls.  Among these controls is the Popup class.  This class allows you to create the popup effect for the screen, enabling custom dialogs.  The class itself is incredibly simple to use:

   1: Popup dialogPopup = new Popup() {Child = new ProgressDialog()};

   2: dialogPopup.IsOpen = true;

By setting the Child property of Popup you are telling the Popup which content will “pop up”.  I am still trying to figure out a way to get away from referencing ProgressDialog, which is a custom User Control that I created.

Using the Popup instance will NOT give you the overlay that you see above.  The Popup only allows content to be displayed in a “popup” type fashion.  You still need to create that effect yourself, this is one of the problems I have with Windows Phone 7.  It is nice to have the ability to customize things to your hearts content, but at times, you want to just things out of the box easily.

The XAML to get this effect is below:

2011-10-17_1128

The idea here is to create a non-opaque rectangle with a custom filling.  This rectangle is locked into the first row and first column of the LayoutRoot Grid.  This rectangle is then extended to cover the entire screen.  Then a StackPanel is defined after which will place the content on top of the grid.

From this point, you use the IsOpen property to control whether the Popup content is visible or not.

As a side note, I don’t fully like this implementation completely because it relies on an externally defined user control. I would prefer to avoid this type of coupling.  Still working on that.

Jay Harris on Going for Performance

Recently, the West Michigan .NET User Group returned from its August recess with a new location and new meeting time.  We presented Jay Harris and his “Going for Speed” presentation.  This talk, as he put it, “is not about performance testing”, it was a presentation about things to look for when analyzing application performance.

I learned quite a bit, especially in regards to what is integrated into Visual Studio.  The project I am currently engaged in at Meijer Inc is one where performance will be critical.  The Profiler feature especially caught my eye.  The ability to run code in a testing scenario and get, line for line, performance analysis was astounding and I can see many uses for the tool.

Jay comes from a background involving Unit Testing and he has taken that approach with testing for performance as well.  He talks about using Stopwatch to actually time Unit Tests themselves and allow for Assertions if the test exceeds a set time.  This will allow you to measure and know, in an automated fashion, if you application may have performance issues.  I found this very interesting, and while a novel concept, incredibly useful.

The presentation was well received.  We were worried about attendance due to the situation with New Horizons forcing us out of our previous meeting location.  However, our community came through in fine style, with an increase in attendance from previous levels and many new faces.  This was very pleasing and encourages us for the future.

Thanks to Jay Harris for coming out.  Don’t forget GRDevDay is coming up on November 5th, 2011.  We have a good number of sponsors and speakers so now we need the most important thing: attendees.  Head over to GVDevDay.org and sign up today.

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.

Pay It Square Android Goes LIVE!!

Today I am finally able to publish the Pay It Square Android application to the Android Marketplace.  I learned a lot developing this application as it took place over the course of time where my Android knowledge really blossomed.

The project began in November of 2010 when Brian Anderson of OST approached me about helping his company, Develomatic, create an Android version for a site he was working on called Pay It Square.  The project seemed interesting and, at the time, I was seeking to leave RCM and OST was a place that I had a strong desire to work at as many of my close friends and mentors had started working there.

After a couple iterations and some heavy redesign both from a code standpoint and UI (I learned how to use Drawable XML and do 9-patch drawing) I began to make substantial progress.  I think the biggest thing I learned from this project is how DI can help make a project better.  Using Guice I was able to abstract away the business objects and separate out, cleanly.  It was an awesome learning experience.

So head out to the Android marketplace and as long as you are in a supported country (the EU, US, Canada, Mexico) and have at least Android 2.1, you are good to go.

Unit Converter and a Custom Control in WP7

I recently finished the development on my first Windows Phone 7 app, titled Unit Converter.  While the idea is hardly unique, I decided to write one for two reasons 1) it was a good chance to get some hands on experience developing WP7 apps and 2) it was something I needed while traveling through Japan.

Most of the code in the application is straightforward and easy to understand. There was one obstacle I ran into that I felt was worth blogging about: custom controls.  The app supports a number of different units.  I needed a way to select these units.  I choose to use LoopingSelector control, which is available via the WP7 Toolkit, in the Primitives namespace.

My first thought was to make these selections available on the screen itself.  However, given the way the LoopingSelector displays and the effect it tries to achieve, it just didn’t look right.  This is where I drew inspiration from the DatePicker control and how it uses a second page to support the selection.

My first attempt at this worked, but was pretty flakey.  I used a TextBox and whenever it got focus Navigated to the page supporting the selection.  After selection the user would “Go Back” to the main page and the unit selected would be shown.  The flakiness came in with the management of the Focus.  I found it very hard to get ride of the focus once the user returned to the page.  This meant the user would have to select somewhere else on the screen.  Like I said, flaky.

It was at this point, drawing upon more inspiration from the DatePicker that I finally achieved a good solution, a custom control.  And thankfully, I could use the DatePicker source code from the Toolkit.

What I ended up doing was creating a custom button, similar to the DatePicker, and internalizing everything.  It ended up working quite well.

First thing to do is to inherit your class from Control.  This will give you access to several methods and allow you to use the class in XAML.

   1: [TemplatePart(Name = ButtonPartName, Type = typeof(ButtonBase))]

   2: public abstract class ConversionUnitPickerBase : Control

   3: {

   4:    // code goes here

   5: }

The TemplatePart attribute denotes what sort of base type this control “is”.  In this case, we are viewing the control as basic button. The actually look of this control is applied through a style, shown here:

  1:         <Style TargetType="pickers:ConversionUnitPickerBase" x:Key="ConversionUnitPicker">
  2:             <Setter Property="Background" Value="{StaticResource PhoneTextBoxBrush}" />
  3:             <Setter Property="BorderThickness" Value="0"/>
  4:             <Setter Property="Foreground" Value="{StaticResource PhoneTextBoxForegroundBrush}" />
  5:             <Setter Property="HorizontalContentAlignment" Value="Left" />
  6:             <Setter Property="PickerPageUri" Value="/Pickers/ConversionPicker.xaml" />
  7:             <Setter Property="Template">
  8:                 <Setter.Value>
  9:                     <ControlTemplate TargetType="pickers:ConversionUnitPickerBase">
 10:                         <StackPanel>
 11:                             <Button x:Name="PickerButton" Content="This is a Test"
 12:                                 Background="{TemplateBinding Background}"
 13:                                 BorderThickness="{TemplateBinding BorderThickness}"
 14:                                 FontFamily="{TemplateBinding FontFamily}"
 15:                                 Foreground="{TemplateBinding Foreground}"
 16:                                 Height="72" HorizontalContentAlignment="{TemplateBinding HorizontalContentAlignment}" />
 17:                         </StackPanel>
 18:                     </ControlTemplate>
 19:                 </Setter.Value>
 20:             </Setter>
 21:         </Style>

The key thing to look at with this code sample is the Setter.Value which effectively creates the template.  Unfortunately, to this point I have not figured how to apply this style to all controls automatically, as is done in the Toolkit source.  For the sake of time and sanity, I simply specified it manually in my XAML:

   1: <pickers:TemperatureUnitConversionPickerBase x:Name="sourceUnit"

   2:                               Style="{StaticResource ConversionUnitPicker}"

   3:                               TemperatureType="Celcius" />

It would appear, based on the samples, that the way to do this is through themes, but I simply have not figured it out yet.

Returning to our class which inherits from Control and is decorated with TemplatePart attribute, the only method that I have found the need to override is OnApplyTemplate which effectively gets the ball rolling, see below:

   1: public override void OnApplyTemplate()

   2: {

   3:     // this is a cleanup step

   4:     if (_mainButton != null)

   5:         _mainButton.Click -= new RoutedEventHandler(HandleUnitPickerLaunch);

   6:  

   7:     base.OnApplyTemplate();

   8:  

   9:     // get a reference to the button we are representing

  10:     _mainButton = GetTemplateChild(ButtonPartName) as ButtonBase;

  11:     if (_mainButton != null)

  12:     {

  13:         _mainButton.Click += new RoutedEventHandler(HandleUnitPickerLaunch);

  14:         _mainButton.Content = Value;

  15:     }

  16: }

This approach reminds me a lot of Android, where we are looking up controls based on names and then populating them through a find method.  Since this control is really a “super” button, we are only wiring up the click event.

From this point the implementation is your own.  In my case, I choose to make this class abstract so I could inherit it for my specific conversion types (Distance, Weight, Volume, and Temperature).  As part of the click handler for the button itself, I had it open my conversion picker, as shown below:

   1: private void OpenUnitPicker()

   2: {

   3:     _applicationContent = PhoneApplicationFrame.Content;

   4:  

   5:     PhoneApplicationFrame.Navigated += new NavigatedEventHandler(

   6:        PhoneApplicationFrame_Navigated);

   7:  

   8:     PhoneApplicationFrame.NavigationStopped += new NavigationStoppedEventHandler(

   9:        PhoneApplicationFrame_NavigationStoppedOrFailed);

  10:  

  11:     PhoneApplicationFrame.NavigationFailed += new NavigationFailedEventHandler(

  12:        PhoneApplicationFrame_NavigationStoppedOrFailed);

  13:  

  14:     _applicationFrame.Navigate(PickerPageUri);

  15: }

This code is effectively helping to do the switch, by saving the content of the control before the Navigate.  PickerPageUri is simply the Uri path within the Silverlight application to the XAML page which will allow the user to pick the unit they are using in the conversion.

We can pass values to this Uri using an interface and the Navigated event, an example is below:

   1: void PhoneApplicationFrame_Navigated(object se, NavigationEventArgs e)

   2: {

   3:     if (e.Content == _applicationContent)

   4:     {

   5:         // close the picker

   6:         CloseUnitPicker();

   7:     }

   8:  

   9:     if (_pickerPage == null)

  10:     {

  11:         _pickerPage = e.Content as IUnitPickerPage;

  12:         if (_pickerPage != null)

  13:         {

  14:             // assign default values to picker page

  15:             _pickerPage.ConversionType = ConversionType;

  16:             _pickerPage.SelectedUnit = GetConversionUnit();

  17:         }

  18:     }

  19: }

What is happening here is as we leave the “page”, we track a reference to the next page.  Through the casting to an interface we can access properties.  We use the same approach for reading the data coming back from the Picker page:

   1: private void CloseUnitPicker()

   2: {

   3:     if (_applicationFrame != null)

   4:     {

   5:         _applicationFrame.Navigated -= new NavigatedEventHandler(

   6:           PhoneApplicationFrame_Navigated);

   7:         _applicationFrame.NavigationFailed -= new NavigationFailedEventHandler(

   8:           PhoneApplicationFrame_NavigationStoppedOrFailed);

   9:         _applicationFrame.NavigationStopped -= new NavigationStoppedEventHandler(

  10:           PhoneApplicationFrame_NavigationStoppedOrFailed);

  11:  

  12:         _applicationFrame = null;

  13:         _applicationContent = null;

  14:     }

  15:  

  16:     // selected unit will be null if they hit cancel

  17:     if (_pickerPage != null && _pickerPage.SelectedUnit != null)

  18:     {

  19:         // get the value through the interface

  20:         _mainButton.Content = _pickerPage.SelectedUnit.LongDisplay;

  21:         SetUnit(_mainButton.Content.ToString());

  22:     }

  23:  

  24:     _pickerPage = null;

  25: }

The key lines here are 17 – 22, which take care of reading the data coming back, so long as the user didn’t cancel, which is handled by the null check.

Writing custom controls is a very powerful tool for your toolbox, I learned this writing Android as well.  The ability to customize is essential in mobile development.  Always consider the user, the usage, and the native paradigms of the platform when designing an interface.  This is a case where being unique may not be a good thing, mobile interfaces are highly specialized.

I plan to deploy this app after additional testing next week, the source code will be made available here at that time.

Unit Testing Windows Phone 7

During my time in Japan one of the most common confusions I had was with units of measurement.  Japan being a normal country, uses the metric system, unlike the US with its wacky system of units.  Many times, I wish I had Google by my side to do the conversions.  To correct this, I started working on app for my Windows Phone 7 that would allow me, without Internet access, to convert to and from all manner of units.

As I started developing it, it became clear that I unit tests would be a huge help because of all of the math being done.  But how?

Thanks to this link (http://dotnet.dzone.com/news/test-driven-development) I came across the Silverlight Unit Testing framework from the Silverlight Toolkit.  The link contains all of the direction needed to get going on this.  Using it you can effectively use the Windows Phone emulator as a Test GUI.

2011-08-22_0703

Its no NUnit Test Runner, but it gets the point across.  Curiously, if you use Assert.AreEqual and the test fails, you get the exception in the IDE as opposed to it being reported here, which is kind of weird.  It still needs some work but it works.  This is one of my test methods

2011-08-22_0706

As you can see, the framework does nothing more then allow the test results to be shown in the Windows Phone 7 Emulator, the rest is all straight MSTest.

The thing I love about writing code with unit tests, especially code involving math, is you have a degree of confidence it is right.  I tend to have a hard time with the whole Red, Green, Refactor model since I tend to write code that does what I want. One of my goals is to work on a team where unit testing is huge and I can learn from smarter people the best way to integrate TDD into my coding style.