Silverlight

Using LoopingSelector and ILoopingSelectorDataSource

Custom Time EntryThis week I finished and submitted my second Windows Phone app. On one of the pages I wanted to allow users to enter a custom TimeSpan in a manner similar to entering a date or time. Of course, the SDK doesn’t directly provide the controls to replicate that experience so I turned to the LoopingSelector in the Silverlight Toolkit for Windows Phone for help. Unfortunately, documentation is pretty sparse so I’m hoping this can help someone else out.

(more…)

Building Magic Manager

Now that the first version of Magic Manager has been certified and published I wanted to document some of my experiences building the application.  I built Magic Manager partially because I wanted a way to track Magic games without using dice but mostly so I could learn a few technologies I don’t typically get to work with.

This project was full of firsts for me.  Until now I had never built a native application for any mobile platform let alone Windows Phone.  Come to think of it, I’ve never really done much with Silverlight either outside of some minor XAML tweaks.  End-to-end this project was one learning experience after another.

Back-End

The back-end for Magic Manager is pretty simple and I wrote most of that in an evening.  By far the most interesting part in terms of functionality is the command pattern used to track each action in the game.  I’m planning on exposing this piece on a history panel in the next release.

Data Persistence

Stick around.
— Dutch, Predator

A big factor in this decision was that Mango is bringing native SQL CE.

An important part of Windows Phone development is restoring application state when the app resumes.  WP apps can either be suspended or tombstoned which means that we need a way to persist that state.

The most difficult part here wasn’t so much deciding what to store but rather how to store it.  Since v1.0 of Magic Manager is entirely self-contained that left isolated storage as my only option.  I considered using something like Sterling but ultimately decided that a very simple isolated storage based repository around my game class would be good enough for now.

An advantage of the repository is that every time I call its StoreGame method the data is serialized to isolated storage.  By using this approach I managed to avoid many of the concerns of restarting and resuming since the game state is preserved automatically by the repository.

For serialization I used the XmlSerializer.  I considered using the DataContractSerializer but ultimately decided that I preferred XmlSerializer’s opt-in model for this simple application.

User Interface

Thanks my wife and some of friends for putting up with me constantly demoing and asking for feedback on my various UI concepts!

I have to admit that I really struggled building the user interface for Magic Manager.  When I say I struggled building the UI I don’t mean to imply that the actual act of building the UI was difficult but rather that I just suck at UI design.  I’ve lost track of how many variations of the UI I built over the course of the project.

The reason I was able to build and test so many different variations in such a short time is a great example of how easy it is to work with XAML.  I found XAML a joy to work with at least for this app.  My favorite feature without a doubt had to be data binding.  I hate to abuse the phrase but it really “just works.”  My two wishes in the area of data binding on the phone are to have more built-in converters and StringFormat.

MVVM

It’s a crystal. Nothing more. But if you turn it this way and look into it, it will show you your dreams.
— Jareth, Labyrinth

Silverlight on the phone isn’t without its problems though.  Being a such newbie to the technology I needed a bit of help getting started, particularly with the preferred UI pattern – MVVM.  Unfortunately most of the resources I found were for Silverlight 4 or WPF and many examples simply didn’t translate well to the phone.

After reading several more general articles and attending an MVVM talk by Phil Japikse at IndyNDA it finally clicked.  MVVM purists won’t like my approach but ultimately I decided that the easiest thing to do was to make my model classes implement INotifyPropertyChanged and expose them through the ViewModels.  This approach greatly reduced the amount of code I needed to write and let me databind the Views to the ViewModels with minimal effort.

Commanding

Klaatu Barada N… Necktie… Neckturn… Nickel… It’s an “N” word, it’s definitely an “N” word! Klaatu… Barada… N… [coughs]  Okay… that’s it!
— Ash, Army of Darkness

One reason I settled on the event handlers is that Mango will include support for ICommand.  I’ll probably update that portion for greater flexibility.

On a related note, something that really stood out when using MVVM on the phone is the lack of native commanding. As I was learning about the MVVM pattern one constant theme was using commanding (via ICommand) to bind controls to actions but Silverlight on the phone doesn’t support it directly.

I briefly looked at MVVM Light but it seemed like overkill for this app so for now I’ve settled on hooking up the various control events in the codebehind to call a method on my ViewModel.  It’s not ideal but it works.

Navigation

Correction, I need the SUPERIOR information in your INFERIOR brain to fly this… thing.
— Max, Flight of the Navigator

Getting navigation working properly was a bit of a trick.  If I was just building pages with codebehinds I’d have been able to use the page’s NavigationService but I wasn’t – I was using MVVM.  The problem with NavigationService and MVVM is that NavigationService is a property of the page.  I could built my Navigation class with a dependency on the page but I wanted to avoid that as much as possible.

Luckily the PhoneApplicationFrame class also provides navigation methods so all that’s necessary is obtaining a reference to the frame through Application.Current.RootVisual.  Once we have that reference we can call Navigate or GoBack without requiring a reference to the current page.

Backward navigation is pretty simple unless you want to go back more than one page at a time.  Windows Phone maintains a navigation stack that allows us to return to the previous page simply by calling the GoBack method but if we want to go back more than one page we have to do a little extra work.

An early incarnation of the UI had a page two levels deep but I wanted to return the user to the application’s home page.  I’ve since removed most of the code for that scenario since I no longer need it but the work around involved setting a flag variable on the App object and checking that value in the OnNavigatedTo event on each page before calling GoBack again.

Page Layout

PHENOMINAL COSMIC POWERS …itty-bitty-living space
— Genie, Aladdin

The hardest part of developing Magic Manager though was just from the nature of mobile apps.  I was trying to present a bunch of information about game state in a tiny viewing area.  What I learned fairly quickly was that the default controls weren’t going to cut it.  I could either spend a bunch of time building some custom controls or I could look around for some 3rd party controls.

First I looked at the Silverlight Toolkit for Windows Phone but the only thing that it included that would be useful for this app was the WrapPanel.  Hope was not lost though, Telerik’s RadControls for Windows Phone were also available.  I installed the trial and was hooked immediately.

As with so many things in life timing is everything.  When I was looking at the controls they were still available for their introductory price.  As an added bonus, two days after I purchased a license Telerik released an update that included charting!

From the RadControls package I ended up using the DataBoundListBox, ListPicker, NumericUpDown, WrapPanel, and Chart.  Each of these controls greatly expanded my options for page layout yet simplified user interaction in a very intuitive manner.

The control that probably had the largest impact on design was the NumericUpDown control.  Without the control I was more or less forced into using a TextBox and setting its InputScope to Numeric.  At first it sounds like a good solution for getting a numeric TextBox but when you look at the keyboard you see that the InputScope doesn’t actually restrict the keyboard to numbers.  By using NumericUpDown instead I removed all possibility of setting a bad value.

I’m still not completely happy with the status page layout but I think it’s a good start.

Appearance

Hey, Hicks. Man, you look just like I feel.
— Drake, Aliens

A major part of the Windows Phone experience is the unified look and feel of the Metro UI.  I wanted to make Magic Manager feel like it belonged on the platform and I quickly discovered that the easiest way to do that was to make extensive use of the built-in theme resources.

The phone provides a ton of default resources that tie in to the current OS theme.  The resource picker in Visual Studio does a decent job of listing the resources but overall isn’t all that helpful since it doesn’t adequately depict them.  I also found myself working almost exclusively in XAML so it was usually easier to type the resource names than hunt for them in the picker.  Fortunately MSDN has a comprehensive listing and description of the theme resources.

Some of the resources I found most useful were:

  • PhoneAccentBrush
  • PhoneBackgroundBrush
  • PhoneForegroundBrush
  • PhoneBorderBrush
  • PhoneBorderThickness.

¿Hablas Español?

Whoa, lady, I only speak two languages, English and bad English.
— Korben Dallas, The Fifth Element

One final thing that I wanted this first version to include was support for Spanish.  There is no better quote than the one above to summarize my ability with foreign languages so how could I provide a Spanish version?  That’s where having a bilingual spouse comes in handy for software development! [Thanks, Esther!]

Although Esther is fluent in Spanish she’s not a Magic player so she was a bit worried about some of the translations but with the help of the Spanish version of the rules we were able to work through the handful of phrases that she didn’t know.

Supporting multiple languages only requires a little setup work:

  • Add the resource files for each language we want to support.  The default resource file doesn’t need a language identifier in the name but any secondary languages do.
  • Update the project’s Assembly Information to identify the default (neutral) language
  • Manually modify the project file (in a text editor) and list any secondary languages in the SupportedCultures element
  • Expose the resources as a property on a new class so control properties can be bound

When the app runs the runtime will determine the appropriate resources to show based on the phone’s settings.  Testing the Spanish resources was merely a matter of switching the phone’s language over to Spanish and restarting it for the changes to take effect.

Final Thoughts

When Microsoft started promoting Windows Phone one of the key selling points for me was that it was going to be easy for .NET developers to transfer their existing skills to the mobile platform.  After developing an app I feel that for the most part they achieved what they set out to do.

Developing Magic Manager was a fun way to learn some Silverlight and experience developing for a mobile platform but even with such a limited experience to draw from in these areas I was able to be productive in a short amount of time.  I’m really looking forward to the API improvements that Mango will bring and already have some ideas for my next app.

If anyone has any tips or tricks they’d like to share I’d love to hear them.

Download Magic Manager

Download Magic Manager

My IndyTechFest Experience

This past Saturday I, along with 400+ developers, admins, and DBAs attended IndyTechFest.  It was a long, intense day of sessions covering topics such as WPF, Silverlight, SQL Server, C#, VB, Testing, and Windows Phone 7.  I’ve had a few days to digest what I heard and wanted highlight some things from each of the sessions I attended.

This year’s conference was split into seven tracks each with five sessions and an all-day open space.  All of the tracks had at least one topic I was interested in and many time slots had conflicts but ultimately I stayed within the general .NET and Silverlight tracks.  My schedule for the day was:

  • Keynote: Are My Three Screens Cloudy?
  • WPF for Developers
  • Implementing MVVM for WPF
  • The State of Data Services: Open Data for the Open Web
  • C# Tips and Tricks
  • Silverlight Code Survey

For the most part I found value in each of the sessions I attended.  Thanks go out to the sponsors, organizers, and volunteers that made this event possible.

Keynote: Are My Three Screens Cloudy?

Presented By: Jesse Liberty

In many ways Jesse Liberty’s keynote was the highlight of the day.  I think my #1 takeaway for the day is that Jesse Liberty is awesome!  In the keynote Jesse briefly described his position within Microsoft, how he got there, and gave a quick history on the evolution of Silverlight.  He went on to describe what Microsoft sees as the “three screens” (computer, TV, and phone) and how Silverlight is the technology that will bring the three screens together through Windows, XBox360, and Windows Phone 7.

WPF For Developers

Presented By: Phil Japikse

This was the first of two Windows Presentation Foundation (WPF) sessions from Phil Japikse.  In this session Phil gave a good introduction to WPF for the non-initiated (like me).  He started by defining WPF, describing the advantages and disadvantages of WPF to WinForms, and discussing new features in .NET 4.0.  The majority of the session was demonstrating some of the more common features.

Some highlights:

  • Creating custom spell-check dictionaries with .lex files
  • Panels dock in XAML order
  • Controls tab in XAML order by default
  • INotifyPropertyChanged interface
  • INotifyCollectionChanged interface

The presentation and example code are both available on Phil’s Samples and Presentations page.

Implementing MVVM for WPF

Presented By: Phil Japikse

Expanding upon his first WPF session, Phil discussed how to implement the Model-View-ViewModel (MVVM) pattern in WPF.  This session was almost entirely demo showing the classes that represent each part of the pattern and how they interact.

The presentation and example code are both available on Phil’s Samples and Presentations page.

Additional Resources:

The State of Data Services: Open Data for the Open Web

Presented By: Dan Rigsby

Dan Rigsby gave a great introduction to OData, a protocol developed by Microsoft to facilitate data interchange between systems using existing Web technologies.  He started by describing REST and Atom/Pub, two technologies that make OData possible then went on to show OData in action.

REST (http://en.wikipedia.org/wiki/Representational_State_Transfer)

  • Embrace the URI
  • HTTP Verbs (GET, POST, etc…) translate to methods
  • Content-Type defines the object model
  • Status code is the result

Atom/Pub (http://atompub.org/)

  • Standards based XML syndication format for publishing and editing web resources
  • Preserves metadata
  • Provides constructs

OData (http://www.odata.org/)

  • “Open” Data
  • Formerly known “Astoria” and ADO.NET Data Services
  • Open protocol
  • WCF Data Services is Microsoft’s provider for creating and consuming OData
  • Netflix provides an OData interface to its video library

C# Tips and Tricks

Presented By: Mark Strawmyer

With all due respect to Mr. Strawmyer I was incredibly disappointed by this session.  The IndyTechFest program had this to say about the session:

This C# presentation focuses on tips and tricks for the C# developer.  It contains a mixture of C# specific features along with other handy how-to items such as shortcuts for working with the C# IDE that will make you more productive.

This session did not fit the description.  I understand the the previous session was a C# 4.0 overview and there was a strong desire to avoid duplication of information but only two of the tips/tricks mentioned were actually specific to C# and one of those was a C# 4.0 feature!

For the curious, the tips and tricks discussed were:

  • Optional & named parameters
  • Extension methods
  • ObsoleteAttribute
  • GC.Collect()
  • using keyword
  • Parallel extensions
  • Utilities

I really question offering up GC.Collect() as a tip, especially when it was provided with the caveat “you can do this but don’t.”  Is letting people know something is possible really a tip if it shouldn’t be done or is not doing it the tip?

To me, a C# tips and tricks presentation should include things such as lesser known/used operators, XML documentation & IntelliSense, compiler options, automatic properties, etc…

Silverlight Code Survey

Presented By: Jesse Liberty

This session was originally going to be “Application Development with Silverlight 4″ but after some feedback from the morning’s keynote and the overlap with the MVVM session it was changed.  In this session Jesse did a quick run-through of creating a new Silverlight application, showing some basic data binding, and some basic animation.  Most of the demonstration is available on the Learn page of Silverlight.net.  Nevertheless, I wasn’t about to miss the opportunity to listen to Jesse present again.

In the Hallway

As with just about any conference lots of interesting things happen in the hallway between sessions.  I’ll sheepishly admit that I didn’t use this time as well as I could (should?) have but I really did enjoy playing with the Windows Phone 7 demo application at the Microsoft booth.  I was even clever enough to crash the app by clicking the emulator’s home button while a dialog box was open :)