Sunday, November 06, 2011

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<T,U,V>.  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<T> 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<string>) method, the source is shown below:

   1: /// <summary>
   2: /// Perform the actual request
   3: /// </summary>
   4: /// <param name="onRequestComplete"></param>
   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: /// <summary>
   2: /// Loads the collect pages for the user into the repository
   3: /// </summary>
   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.

Sunday, October 23, 2011

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.

Sunday, October 16, 2011

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.

Saturday, October 01, 2011

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.

Tuesday, September 27, 2011

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.

Wednesday, August 31, 2011

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.

Sunday, August 28, 2011

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.