Crossing The Finish Line With IMSA

This slideshow requires JavaScript.


As Tim called out the other day, we recently went live with a brand new mobile experience for IMSA, and I had the privilege of leading the engineering team on the project here at IK. The scope and timeframe of the project were both ambitious: we delivered a brand-new, content-driven mobile app with live streaming audio and video, realtime in-race scoring results, custom push notifications and more, across all major platforms (iOS, Android, and Windows), with custom interfaces for both phone and tablet form factors – all in a development cycle of about twelve weeks. It goes without saying that the fantastic team of engineers here at IK are all rockstars, but without some cutting-edge development tools and great partnerships, this would have been impossible to get across the finish line on time:

  • Xamarin allowed our team to utilize a shared codebase in a single language (C#, which we happen to love) across all of our target platforms, enabling massive code reuse and rapid development of (effectively) six different apps all at once.
  • Working closely with the team at Xamarin enabled us to leverage Xamarin.Forms to unlock even further code-sharing than would have been otherwise possible, building whole sections of the presentation layer in a single, cross-platform XAML-based UI framework.
  • On the server side, our partners at Microsoft’s continued world-class work on Azure made utilizing Mobile App Service (née Azure Mobile Services) a no-brainer. The ability to scale smoothly with live race-day traffic, the persistent uptime in the face of tens of thousands of concurrent users making millions of calls per day, and the ease of implementation across all three platforms, all combined to save us countless hours of development time versus a conventional DIY approach to the server layer.
  • Last but not least, being able to leverage Visual Studio’s best-of-breed suite of developer tools was essential to the truly heroic amounts of productivity and output of our engineering team at crunch time. And Visual Studio Online enabled the Project Management team and myself to organize features and tasks, track bugs, and keep tabs on our progress throughout the hectic pace of a fast development cycle.

The final result of this marriage between cutting-edge cross-platform technology and an awesome team of developers is a brand new app experience that’s available on every major platform, phone or tablet, and this is just the beginning – we have lots of great new features in store for IMSA fans worldwide. I’ll be following up with a couple more technical posts about particular challenges we faced and how we overcame them, and be sure to check out the next IMSA event in Detroit the weekend of May 29-30; I know I’ll be streaming the live coverage from my phone!

Session 1 & 2 of the WinRT Development Class – Introduction, XAML, and WinRT’s Control Framework

WinRTWebBannerSmall_JPEG

 

The first two sessions of the WinRT Development class were a great introduction to what Windows 8 WinRT development really is and to XAML development. We’re very excited about the future sessions and hope every developer will come learn with us about developing WinRT apps!

Session 1 Resources

Session 2 Resources

 

Overview of Sessions

The links below lead you to Meetup Events where you can RSVP. We look forward to seeing you at our next session!

1. Introductory Lecture (Nov 27th by Danny & Kevin)
2. Introduction to XAML and WinRT’s powerful Control Framework; (Dec 4th by Danny & Kevin Click here for the video recording)
3. Page-Navigation Model and Application Lifecycle (Jan 8th by Danny)
4. Fundamentals (Async/Await, WinRT API, Security) (Jan 15th by Kevin)
5. Settings and Search Contract (Jan 28th by Danny)
6. Share Contract (Feb 4th by Kevin)
7. Live Tiles and Background Tasks (March 18th by Kevin)
8. Orientation Handling and Proximity using Near Field Communication (NFC) (March 25th by Danny)
9. Introduction to ModelViewViewModel (MVVM) (April 8th by Danny)
10. InterKnowlogy’s WinRT MVVM Framework Session Part I/II(April 22nd by Kevin)
11. InterKnowlogy’s WinRT MVVM Framework Session Part II/II(May 6th by Danny)
12. Presentation of Hackathon Results + Certificate/Prize Giveaway(May 22nd by Danny and Kevin)

Accessing Dependency Property (DP) Changed in WinRT

With the release of Windows 8 and WinRT, I began the process, during RECESS, of porting an existing app we’d created for the Microsoft Surface (the team that is now called “Pixel Sense”) to be a Windows Store application. The application followed more of an MVC (Model View Controller) approach, rather than MVVM (Model View ViewModel), so there we a number of controls that subscribed to the DataContext and Visibility changed events in their code behind, which don’t exist in WinRT.

WinRT (Windows Store) applications seem to have many of the same limitations that Silverlight had, compared to WPF, and rather than rewrite the parts of the application to try and avoid needing to know when these DPs changed, I came up with a simple framework to register for a callback when a specified DP changed.

First Solution

The way to get around this issue was actually really straight forward. In each control, I created and registered a DP for each DP I wanted a change notification from (ie. DataContextEx, VisibilityEx, etc…).

public static readonly DependencyProperty DataContextExProperty =
		  DependencyProperty.Register( "DataContextEx", typeof( object ), typeof(DemoControl ),
			new PropertyMetadata( null, OnDataContextExChanged ) );

public object DataContextEx
{
	get { return (object)GetValue( DataContextExProperty ); }
	set { SetValue( DataContextExProperty, value ); }
}

private static void OnDataContextExChanged( DependencyObject d, DependencyPropertyChangedEventArgs e )
{
	( (DemoControl)d ).OnDataContextExChanged( e );
}

private void OnDataContextExChanged( DependencyPropertyChangedEventArgs e )
{
	//Handle the change
}

Then, in the control’s constructor, I bound the created DP(s) to the related DP I wanted to know had changed. With this binding, whenever the source DP (ie. DataContext, Visibility, etc…) changed it would cause the “extension” DP to change and that would call the changed handler I registered when creating the DP.

var binding = new Binding
			{
				Path = new PropertyPath("DataContext"),
				RelativeSource = new RelativeSource
								{
									 Mode = RelativeSourceMode.Self
								}
			};
SetBinding(DataContextExProperty, binding);

With this I had all that I needed. However, I hated the idea of having to rewrite this code on every control that I needed the notification on. So I decided to create a framework to allow me to register for a changed callback on any FrameworkElement.

Framework

I decided to go the route of creating a FrameworkElement extension method called RegisterDependencyPropertyChanged that takes a lambda expression for the property to bind to and a callback for when that property changes.

this.RegisterDependencyPropertyChanged( () => DataContext, DataContextChangedHandler );

The extension then calls RegisterDependencyPropertyBinding on FrameworkElementAttachedProperties. FrameworkElementAttachedProperties is an internal class that holds the functionality to create and register an Attached DP for each type of DP (ie. DataContext, IsHitTestVisible, Visibility, etc..) the user desires a callback for and bind that Attached DP to the DP (using the same process defined under First Solution. Then whenever that value changes it attempts to find a callback registered for it, and if one is found, calls the registered callback with the DependencyPropertyChangedEventArgs provided.

Attached DPs are only able to be bound to one property of an object at a time (but can be bound to the same property of multiple objects). This is why an Attached DP is created and registered for each DP of a control as there may be a case where a change callback is registered for more than one property of that control. Therefore whenever FrameworkElementAttachedProperties.RegisterDependencyPropertyBinding is called it calls GetNextUnusedAttachedPropertyForFrameworkElement. This either grabs an existing Attached DP registered for that property, or it will create and register a new one and return it.

private static DependencyProperty GetNextUnusedAttachedPropertyForFrameworkElement( string propertyName )
{
	if ( !_staticExtensionDPs.ContainsKey( propertyName ) )
	{
		var unusedDependencyProperty = DependencyProperty.RegisterAttached( _extensionDPsNamePrefix + "_" + propertyName,
													   typeof( object ),
													   typeof( FrameworkElementAttachedProperties ),
													   new PropertyMetadata( null, DependencyPropertyExPropertyChanged ) );
		_staticExtensionDPs.Add( propertyName, unusedDependencyProperty );
	}
	
	return _staticExtensionDPs[propertyName];
}

The registered callbacks are stored in the DependencyPropertyCallbacks Attached DP on FrameworkElementAttachedProperties. By storing the callbacks in the Attached DP, when the control that has registered is unloaded, it can be collected by the Garbage Collector and there aren’t memory leaks.

Conclusion

I tend to prefer the MVVM approach, but there are cases when constraints dictate that a different approach is used. This is a nice little addition for when that occurs. Here is a demo solution containing the framework (FrameworkElementExtension.cs) and an example of how to use it.

Make Portable Libraries Your Go-To Project Template

With the upcoming release of Visual Studio 2012, Portable Libraries will finally be built into the product. The 2012 iteration of Portable Libraries is much improved from the prior versions, adding not only new platforms (Windows 8 Metro) but greatly increasing the list of available framework library classes that can be used across the various platforms.

Continue reading

Presentation Materials for San Diego Code Camp

Thanks to everyone for another great Code Camp!

Future-proofing your XAML Applications with Portable Libraries: Slides | Code

A Survey of Multi-threading in .NET 4.5: Slides | Code

Visual Studio 11: http://www.microsoft.com/visualstudio/11/en-us/downloads

Portable Libraries Hands-On-Lab: http://tinyurl.com/plibhol

Reactive Extensions: http://msdn.microsoft.com/en-us/data/gg577610

Crazy WinRT XAML Bug in Windows 8 Developer Preview

I’ve been playing with the developer preview release of Windows 8 that we got from //BUILD/.  Everyday, we find more and more “issues” that are either just straight up bugs, things that are not implemented yet, or maybe even issues that won’t be resolved because WinRT is “just different”.  This one was especially “fun” to track down – and when we did, we couldn’t believe the issue.

Start with a simple WinRT application in Visual Studio 11.  Add a class library project that will hold a couple UserControls that we’ll use in the main application.  Pretty standard stuff.

Create 2 UserControls in the library, the first one will use the other.  UserControl1 can just have some container (Grid) then use UserControl2 (which just has an ellipse).  In the main application, add a reference to the ClassLibrary and use UserControl1 in the MainPage.  Your solution should look something like this:

Solution

  <!-- MainPage.xaml -->
  ...
  xmlns:controls="using:ClassLibrary1.Controls"
  ...

<Grid x:Name="LayoutRoot"
    Background="#FF0C0C0C">
  
  <controls:UserControl1 />
  
</Grid>
  <!-- UserControl1.xaml -->
  ...
  xmlns:controls="using:ClassLibrary1.Controls"
  ...

  <Grid x:Name="LayoutRoot"
      Background="#FF0C0C0C">
    
    <controls:UserControl2 />

  </Grid>
  <!-- UserControl2.xaml -->

  <Ellipse Height="40" Width="40" Fill="Red" />

Now here’s the key step.  Add a new class to the ClassLibrary, say Class1, and have that class IMPLEMENT INotifyPropertyChanged (be sure to choose the right using statement – the one from UI.Xaml.Data).

    public class Class1 : INotifyPropertyChanged
    {
        #region INotifyPropertyChanged Members

        public event PropertyChangedEventHandler PropertyChanged;

        #endregion
    }

That’s it.  Run it.

You will get a runtime exception:

Exception

Crazy, huh?  The Microsoft guys have confirmed this to be a known bug.  I just can’t believe what that bug would be?  How is a simple UNREFERENCED class that implements INPC getting in the way of a couple UserControls?

Ahh … the joys of coding against pre-release software…

Icons for Windows 8 Metro Application Buttons

To make it easier to use standard button icons, a new Segoe UI Symbol font has been added to Windows 8 that currently includes 25 icons. The available icons are listed below with their hex and base 10 values. The icons can be used from XAML like: <TextBlock Text=”&#57615;” FontFamily=”Segoe UI Symbol”/>

IconFontChart

XamlReader, Loose ResourceDictionary Files, and the ParserContext

In a few WPF projects that I have been on I have needed to load in loose ResourceDictionary files to provide different runtime styling. When there isn’t any external content being referenced (ie. images, videos, etc…) it is as simple as calling XamlReader.Load and then merging the dictionary into the application’s resources:

var resourceDictionary = XamlReader.Load(fileStream) as ResourceDictionary;
if(resourceDictionary != null)
{
    Resources.MergedDictionaries.Add(resourceDictionary)
}

When external content is being referenced there is the possibility that the XamlReader won’t be able to find those files, even if they are in the exact same folder as the ResourceDictionary files. To solve this issue, you will need to create a ParserContext and set its BaseUri to the root folder containing the files. For example, if the ResourceDictionary and content files are located in a folder called RuntimeResources, which is in the same folder as the application’s exe, then the BaseUri needs to point to that RuntimeResources folder. Then when the XamlReader loads the ResourceDictionary, it uses the provided ParserContext to know where to look for the actual files. NOTE: In the ResourceDictionary you will still need to include the root folder (RuntimeResources) at the beginning of the uri otherwise it will look in the parent directory for the desired file.

Below is the related code:

C#

var applicationDirectory = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
if(!String.IsNullOrEmpty(applicationDirectory ))
{

    var runtimeResourcesDirectory = Path.Combine(applicationDirectory , "RuntimeResources");
    var pc = new ParserContext
    {
        BaseUri = new Uri(runtimeResourcesDirectory , UriKind.Absolute)
    };
    if(Directory.Exists(runtimeResourcesDirectory ))
    {
        foreach (string resourceDictionaryFile in Directory.GetFiles(runtimeResourcesDirectory , "*.xaml"))
        {
            using (Stream s = File.Open(resourceDictionaryFile, FileMode.Open, FileAccess.Read))
            {
                try
                {
                    var resourceDictionary = XamlReader.Load(s, pc) as ResourceDictionary;
                    if (resourceDictionary != null)
                    {
                        Resources.MergedDictionaries.Add(resourceDictionary);
                    }
                }
                catch
                {
                    MessageBox.Show("Invalid xaml: " + resourceDictionaryFile);
                }
            }
        }
    }
}

Resource Dictionary

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
			    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">

	<ImageBrush x:Key="LogoImage"
			  ImageSource="RuntimeResources/logo.png" />

</ResourceDictionary>

Now you’ve got the ability to change your WPF application’s styling at runtime.

Binding to alternate DataContexts

The DataContext is one of the most important parts of the WPF data binding system, especially in MVVM applications. Being built into the Binding type as the common source for bindings in a specific scope reduces plumbing code needed and makes XAML more concise. Unfortunately, for any given element there is only one DataContext available to bind against. Most of the time this isn’t a problem, but complex data hierarchies often lead to situations where an element needs to bind to the DataContext of some parent element in addition to its own local DataContext.

I most often run into this with ItemsControls where something inside the ItemTemplate needs to bind to the ViewModel containing the entire collection:

<ItemsControl ItemsSource="{Binding Items}">
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <DockPanel>
                <TextBlock Text="{Binding Name}"/>
                <Button Content="Remove" Command="<Remove item command on parent VM>" CommandParameter="{Binding}"/>
            </DockPanel>
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>

Continue reading