How to prove you are a novice .NET programmer (String Concatenations)

I freely admit that I still have a lot to learn with respect to .NET programming.  I figure in any endeavor the day you think you have finally figured it all out is the day when you have well and truly, totally deluded yourself.  There are many ways to determine that somebody (yourself or another) is a novice .NET programmer, but there are some things that truly seem to stand out for me.

String Concatenation

How string concatenations are coded has implications on raw code performance but far more importantly it has a HUGE impact on memory performance.  When the string concatenations are occurring within a web application they could cause recycling of the application pool.  Basically, with reference to memory performance, the more temporary objects code creates that need to be garbage collected the more often garbage collections have to occur and the more likely that the code could receive OutOfMemoryExceptions and/or the application performance suffer during the garbage collections.

There are basically two methods for concatenating strings in C#.  Use of the overloaded string concatenation operator ‘+’ and use of the StringBuilder class.  There are a variety of BCL class methods that concatenate strings like string.Join, but underneath they are usually using the StringBuilder class so I’ll ignore that permutation of this issue.

There is a good article at http://support.microsoft.com/kb/306822 documenting the raw code performance statistics in some sample code between the two methods of string concatenation.  The code sample used uses a loop to concatenate a string 5,000 times.  You might think this is an extreme example used to illustrate the issue.  It would be nice to think so, however I recently saw some code that used 40+ concatenations per record to generate a string for a data structure that consisted of approximately 20,000 records.  That comes to over 800,000 string concatenations.  Ok, forget the extreme examples, let’s look at the following code:

    data = "\"" + data + "\",";

Each time this line of code executes it will create two new strings and leaves two old strings around to be garbage collected at some point in the future.  Now do this in a loop 10 times or 20 times or 100 times.

  • String 1 = "\"" + data
  • String 2 = (String 1) + "\","
  • Throw away String 1
  • Throw away the original value of data
  • Keep String 2 (at least until the next concatenation occurs)

On the other hand the code:

    data = string.Format("\"{0}\",", data);

creates one new string and leaves the old value of data to be garbage collected at some point in the future.  Using the StringBuilder class does even better with the code:

    StringBuilder stringBuilder = new StringBuilder();
    stringBuilder.AppendFormat("\"{0}\",", data);

which doesn’t create any new strings (until the point that all concatenations are complete and a call is made to stringBuilder.ToString()) and leaves the old value of data to be garbage collected at some point in the future. There are some considerations when using the StringBuilder class in needing to use the StringBuilder(int) constructor overload to give StringBuilder a larger than default estimate on how big the string will get to reduce the amount of internal array allocations that are used to hold the parts of the once and future string.

Let’s look a little bit more at some more code that appears fairly regularly:

    string result = String.Empty;
    foreach (var item in items)
    {
        if (!String.IsNullOrEmpty(result))
        {
            result += ",";
        }
        result += item.Name;
    }

    return result;

If this code executes on a collection with just four values it will have created eight new strings, returning one and leaving 7 to be garbage collected.  This code could be rewritten in a couple of different ways:

Better:

    StringBuilder result = new StringBuilder();
    foreach(var item in items)
    {
        if (result.Length > 0)
        {
            result.Append(",");
        }
        result.Append(item.Name);
    }

    return result.ToString();

But why even have all that code? I love LINQ! And string.Join uses the StringBuilder class for us.

Best:

    return string.Join(",", items.Select(item => item.Name));

Learn to be Lazy<T>

Updated: 3/24/2013

 

It sounds funny but it’s a matter of fact that many people work very hard to be lazy.  There are a number of common patterns to this pursuit of…

A common one looks like:

    public static SchemaProvider Instance
    {
        get
        {
            if (_instance == null)
            {
                _instance = new SchemaProvider();
            }

            return _instance;
        }
    }

Ok, I admit it. I wrote that one in the .NET 3.5 days. Another one I’ve been seeing a lot of lately looks like:

    private DelegateCommand<EditCommandArgs> _editCommand;
    public DelegateCommand<EditCommandArgs> EditCommand
    {
        get { return _editCommand ?? (_editCommand = new DelegateCommand<EditCommandArgs>(EditCommandExecuted)); }
    }

Both of these have issues. 

One being that they are not thread-safe (although depending on how they are used they may never have a problem). 

I think an even more rudimentary issue is why these particular pieces of code are even using lazy instantiation.  As far as I understand it the main reason for lazy instantiation is that code needs to instantiate an object that is expensive either in the time it takes to construct and return the object or in the amount of memory it takes.  The hope being that maybe the code will never have to actually instantiate the object but it it does you don’t want application startup (for instance) to be delayed while the code attempts to construct these objects.

The code at the top could have just:

    private   static  SchemaProvider _instance =  new  SchemaProvider();

The second code block could have just set the variable _editCommand in the constructor and been done with it.

Just for the sake of argument, however, let’s say that there was a valid need to lazily construct some object, hopefully in a thread-safe way.

Good news!  As of .NET 4 the Lazy<T> class is available for all your lazy resource conservation needs.

An example is:

    private static readonly Lazy<IDataProvider> _dataProvider = new Lazy<IDataProvider>(() => new DataProvider(), LazyThreadSafetyMode.ExecutionAndPublication);
    public IDataProvider DataProvider { get { return _dataProvider.Value; } }

If you need even more control over the object creation just use a Func<TResult> delegate instead of a lambda:

    private static readonly Lazy<ILogger> _logger = new Lazy<ILogger>(GetLogger, LazyThreadSafetyMode.ExecutionAndPublication); 
    private static ILogger GetLogger()
    {
      ...
    }
    public ILogger Logger { get { return _logger.Value; } }

Jeffrey Richter covers this very thoroughly in his book ‘CLR via C#’, Chapter 30, ‘The Famous Double-Check Locking Technique’  http://www.amazon.com/CLR-via-Microsoft-Developer-Reference/dp/0735667454/ref=pd_rhf_gw_s_cp_8 showing that the simple patterns you see most don’t really work well if at all any way.  In addition he gives an excellent explanation of the LazyThreadSafetyMode enumeration values with examples.

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.

Prism 4, MEF and the CompositionInitializer

So I have been using MEF (Managed Extensibility Framework) for a while now on most of my WPF projects. Lately, I have been really getting a lot of use out of Prism 4.0 as well and utilizing the built in MEF with the MefBootstrapper.

One of the things that I always found a bit troublesome however was what to do when you need a non-exported class to satisfy its imports from MEF. This came up on a recent project, as I was using the IEventAggregator from Prism, thought it would be useful to have it in classes that may not come from MEF- i.e. classes that are new’ed up depending on the business logic dictated. Now, the true MEF heads may say, ‘Nooooo! That’s not what MEF is for!’. But I thought I would see how it worked anyway.

To solve this, one approach was to pass in my IEventAggregator to my class through the constructor, but this didn’t seem too elegant. What if I need other imports besides the IEventAggregator? Then potentially I need to pass in more and more stuff to the constructor.

What I really needed, was some way to tell the class that it has imports it needs to satisfy, and notify that class that it needs to check the already existing container for this. This is where the CompositionInitializer comes in. One problem with that is that the CompositionInitializer was designed for Silverlight, and my application is MEF. But, no worries, Glenn Block had anticipated my need and kindly written a WPF CompositionInitializer, to be found here. Thanks Glenn. And in addition, I found lots of other great info from Reed Copsey’s site. Thanks Reed.

So I placed my CompositionInitializer in my non-exported class in the constructor:

// No export here
public class MyClass
{
	public MyClass()
	{
		CompositionInitializer.SatisfyImports( this );
	}

	[Import]
	private IEventAggregator EventAggregator { get; set; }
}

But when I ran the code, even though I had a valid import for my IEventAggregator, none of my messages were being received. A bit of googling brought me here. Aha! Simply placing my CompositionInitializer.SatisfyImports( this ) in the constructor is insufficient. How, after all, does the CompositionInitializer know what container you are using? I was so used to MEF magic that it hadn’t occurred to me that CompositionInitializer needs to have its container set.

By adding the following line to my BootStrapper file in a location that gets called after CreateShell():

CompositionHost.Initialize( Container );

My CompositionInitializer was now armed with the appropriate container, and everything worked great in the constructor. Now I was able to new up an instance of any class and satisfy its imports against my Container.

Using Kinect in a Windows 8 / Metro App

We have been working with the Kinect for a while now, writing various apps that let you manipulate the UI of a Windows app while standing a few feet away from the computer – the “10 foot interface” as they call it.  Very cool stuff.  These apps make use of the Microsoft Kinect for Windows SDK to capture the data coming from the Kinect and translate it into types we can use in our apps:  depth data, RGB image data, and skeleton points.  Almost all of these apps are written in C# / WPF and run on Windows 7.

Last month a few of us went to the Microsoft //BUILD/ conference, and came back to start writing apps for the new Windows 8 Metro world.  Then naturally, we wanted to combine the two and have an app that uses Kinect in Windows 8 Metro.  At InterKnowlogy we have a “Kiosk Framework” that fetches content (images, audio, video) from a backend (SQL Server, SharePoint) and has a client for various form factors (Win7, Surface, Win Phone 7) that displays the content in an easy-to-navigate UI.  Let’s use the Kinect to hover a hand around the UI and push navigation buttons!  Here’s where the story begins.

One of the First Metro Apps to Use Kinect

Applications that are written to run in Windows 8 Metro are built against the new Windows Runtime (WinRT) API, which is the replacement for the old Win32 API that we’ve used since Windows 3.0.  The problem when it comes to existing code is that assemblies written in .NET are not runtime compatible with WinRT (which is native code).  There is a lot of equivalent functionality in WinRT, but you have to port existing source code over, make changes where necessary, and compile specifically against WinRT.  Since the Kinect SDK is a set of .NET assemblies, you can’t just reference it in your WinRT / Metro app and start partying with the Kinect API.  So we had to come up with some other way…

You CAN write a .NET 4.5 application in Windows 8, using Visual Studio 11 and it will run on the “desktop” side of the fence (alternate environment from the Metro UI, used for running legacy apps).  So we decided to take advantage of this and write a “Service” UI that will run in the classic desktop environment, connect to the Kinect and receive all the data from it, and then furnish that data out to a client running in the Metro side.  The next issue was – how to get the data over to our Kiosk app running in Metro?  Enter web sockets.  There is a native implementation of web sockets in the WinRT framework and we can use that to communicate on a socket channel over to the .NET 4.5 desktop which can reply to the client (Metro) socket with the Kinect data.

Some Bumps in the Road

Writing the socket implementation was not conceptually difficult.  We just want the client to poll at a given frame rate, asking for data, and the service will return simple Kinect skeleton right-hand position data.  We want to open the socket, push a “request” message across to the service, and the service will write binary data (a few doubles) back to the caller.  When pushing bytes across a raw socket, obviously the way you write and read the data on each side must match.  The first problem we ran into was that the BinaryWriter in the .NET 4.5 framework was writing data differently than the DataReader in WinRT was receiving the data.

As with any pre-release software from MIS, there is hardly any documentation on any of these APIs.  Through a ton of trial and error, I found that I had to set the Unicode and Byte Order settings on each side to something that would match. Note the highlighted lines in the following code snippets.

    // Send data from the service side

    using ( MemoryStream ms = new MemoryStream() )
    {
        using ( BinaryWriter sw = new BinaryWriter( ms, new UnicodeEncoding() ) )
        {
            lock ( _avatarPositionLock )
            {
                sw.Write( _lastRightHandPosition.TrackingState );
                sw.Write( _lastRightHandPosition.X );
                sw.Write( _lastRightHandPosition.Y );
            }

        }

        Send( ms.GetBuffer() );
    }
    // Receive data in the client 

    DataReader rdr = e.GetDataReader();

    // bytes based response.  3 ints in a row
    rdr.UnicodeEncoding = UnicodeEncoding.Utf16LE;
    rdr.ByteOrder = ByteOrder.LittleEndian;
    byte[] bytes = new byte[rdr.UnconsumedBufferLength];

    var data = new JointPositionData();
    var state = rdr.ReadInt16();
    Enum.TryParse&lt;JointTrackingState&gt;( state.ToString(), out data.TrackingState );
    data.X = rdr.ReadDouble();
    data.Y = rdr.ReadDouble();

    UpdatePositionData( data );

Once I got the socket channel communicating simple data successfully, we were off and running.  We built a control called HoverButton that just checks whether the Kinect position data is within its bounds, and if so, starts an animation to show the user they’re over the button.  If they hover long enough, we fire the Command on the button.

The next problem was connectivity from the client to “localhost” which is where the service is running (just over in the desktop environment).  Localhost is a valid address, but I would keep getting refused connections.  Finally re-read the setup instructions for the “Dot Hunter” Win8 SDK sample which tells about a special permission that’s required for a Win8 app to connect to localhost.

PackageFamilyName

Open a command prompt as administrator and enter the following command (substitute your package name for the last param):

    CheckNetIsolation LoopbackExempt -a -n=interknowlogy.kiosk.win8_r825ekt7h4z5c

There is no indication that it worked – I assume silence is golden here.  (I still can’t find a way to list all the packages that have been given this right, in case you ever wanted to revoke it.)

CheckNetIsolation

Finally, a couple other minor gotchas:  the service UI has to be running as administrator (to open a socket on the machine), and the Windows Firewall must be turned OFF.  Now we have connectivity!

What’s Next?

Beyond those two problems, the rest was pretty straight forward.  We’re now fiddling with various performance settings to achieve the best experience possible.  The skeleton data is available from the Kinect on the desktop side at only about 10 frames per second. We think this lower rate is mostly due to the slower hardware in the Samsung Developer Preview device we got from BUILD.  Given that speed, the Metro client is currently asking for Kinect data from the service at 15 frames per second.  We are also working on better smoothing algorithms to prevent a choppy experience when moving the hand cursor around the Metro UI.

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…

Windows 8 Development–First Impressions

Along with 5000 other developers, I attended //BUILD/ in September and came home with the Samsung pre-release hardware loaded with Visual Studio 11 and the Win8 bits.  Since then, I’ve been writing a few apps, getting my feet wet writing code for Metro / WinRT apps in C#.  Here are some early impressions on the Windows 8 operating system in general, and then some thoughts on what it takes to develop Metro apps.

Don’t Make Me Hop That Fence Again

The grand new look of Windows 8 is the “Metro” style interface that you see right away on the Start Screen.  The traditional start menu is gone, you don’t have a hierarchy of StartScreenstart menu icons that you wade through, and you don’t have a bunch of icons scattered on your desktop.  Instead you have the clean looking, larger sized “tiles”, some of which are “live”, showing you changes to application data in real-time.    You can find lots of info on the Win8 Metro interface here, so I won’t talk about that.  Apps written for Metro, built against the Windows Runtime (WinRT) run over here on this “Metro” side of the fence.

What is so interesting to me though is that there exists an alternate world in Windows 8 – the classic desktop.  This is where legacy apps run, where the familiar desktop can be littered with icons, the taskbar shows you what’s running,etc. Everything from old C and C++ code to .NET 4 apps run over here on this “Desktop” side of the fence.

DesktopSideSo here then is the problem. Throughout the day, I run a few apps to check Facebook and Twitter (Metro), then I startup Visual Studio 11 (desktop), then I start Task Manager (Metro), then maybe a command prompt (desktop).  Each time I’m in one environment and run an app that runs in the other, the OS switches context to the other side of the fence.  This becomes SUPER ANNOYING over the course of a day.  I’m in the desktop, all I want to do is fire up a command prompt.  Click the start menu (which takes me to the Metro start screen), then choose command prompt, which switches me back to where I just came from and fires up the command prompt.  I’ve become accustomed to pinning all my necessary apps to the desktop side taskbar so I don’t have to go to the Metro screen to run time.

Enough of the Rant – What About Development?

The Windows 8 Runtime (WinRT) is a completely re-written layer akin to the old Win32 API that provides lots of new services to the application developer.  When sitting down to write a new app, you have to decide right away, are you writing a .NET 4.5 app, or are you writing a Metro app.  (This dictates which side of the fence you’ll be hanging out in.)  Some of the coolest features of the Win8 runtime are:

Contracts

Contracts are a set of capabilities that you declare your application to have, and the OS will communicate with your app at runtime based on the contracts.  Technically they’re like interfaces, where you SearchResultspromise to implement a set of functionality so the OS can call you when it needs to.  The most popular contracts are those that are supported by the “Charms” – Search, Share, and Settings.  These are super cool.  Implement a couple methods and your app participates as a search target, so the when the user enters some text in the search charm, your app is listed and you furnish the results.

 

 

protected override void OnLaunched( LaunchActivatedEventArgs args )
{
    var pane = Windows.ApplicationModel.Search.SearchPane.GetForCurrentView();
    pane.QuerySubmitted += QuerySubmittedHandler;

    pane.SuggestionsRequested += SuggestionsRequestedHandler;
    pane.ResultSuggestionChosen += ResultSuggestionChosenHandler;

    pane.PlaceholderText = "Search for something";

	// ...
}

private void QuerySubmittedHandler( SearchPane sender, SearchPaneQuerySubmittedEventArgs args )
{
    var searchResultsPage = new SearchTest.SearchResultsPage1();
    searchResultsPage.Activate( args.QueryText );
}

private void SuggestionsRequestedHandler( SearchPane sender, SearchPaneSuggestionsRequestedEventArgs args )
{
    var searchTerm = args.QueryText;

    var sugg = args.Request.SearchSuggestionCollection;
    for ( int i = 0; i < 5; i++ )
    {
        // just faking some results
        // here you would query your DB or service
        sugg.AppendResultSuggestion( 
            searchTerm + i, 
            "optional description " + i, 
            i.ToString(), 
            Windows.Storage.Streams.StreamReference
              .CreateFromUri( new Uri( "someurl.jpg" ) ),
            "alternate text " + i );
    }

    //defer.Complete();
}

protected override void OnSearchActivated( SearchActivatedEventArgs args )
{
    var searchResultsPage = new SearchTest.SearchResultsPage1();
    searchResultsPage.Activate( args.QueryText );
}

ShareSharing is just about as easy. Declare the contract in your manifest and your app is a share target.  When the user chooses to share to your app, the OS sends you the data the user is sharing and you party on it.

protected override void OnSharingTargetActivated( ShareTargetActivatedEventArgs args )
{
	var shareTargetPage = new ShareTestTarget.SharingPage1();
	shareTargetPage.Activate( args );
}

Settings leave a little bit to be desired in my opinion. You declare the contract, and add a “command” to tell the OS to put in the settings charm panel.  But when the user chooses that command (button), your app has to show its own settings content (usually in a slide out panel from the right).  This is a 4 step process to make any settings changes in your app (swipe from right, touch the button, change settings, dismiss the panel). I really hope in future versions they figure out a way to embed our application settings content right there in the settings panel, not in our own app.

    Windows.UI.ViewManagement.ApplicationLayout.GetForCurrentView().LayoutChanged += LayoutChangedHandler;
    DisplayProperties.OrientationChanged += OrientationChangedHandler;
    Application.Current.Exiting += ExitingHandler;

    SettingsPane pane = SettingsPane.GetForCurrentView();
    SettingsCommand cmd = new SettingsCommand("1", "Pit Boss Settings", (a) =>
        {
            ShowSettingsPanel();
        });
    pane.ApplicationCommands.Add(cmd);

Async Everywhere

The WinRT team has built the APIs with asynchrony in mind from day one. At //BUILD/, we heard over and over that your UI should NEVER freeze because it’s busy doing something in the background.  To that end, any API that could potentially take longer than 50 milliseconds is implemented as an asynchronous method.  Using the async and await keywords (we’ve seen these in a CTP for .NET 4) that are built into the WinRT-based languages, we can write our code in a flowing, linear fashion that makes sense semantically.  No longer do we have to use BackgroundWorkers and worry about marshalling results back to the calling thread.

    HttpClient http = new HttpClient();
    var task = await http.GetAsync( url );

    string responseText = task.Content.ReadAsString();

“Free” Animations

XAML support is implemented in WinRT as native code, and is available to use from C#, VB, and C++.  One of the coolest features they added to what we’re already used to in WPF & Silverlight is the “built-in” animation library.  Simply add any number of transitions on a container element, and any of the associated operations in ANY OF ITS CHILDREN will use that transition.  The list of built-in transitions include: Entrance (content appearing for the first time), Content (change content from old to new), Reposition (fluidly move elements when they get repositioned), Add/Delete (fade out/in and move existing items), and Reorder.

  <Grid>
    <Grid.ChildTransitions>
      <TransitionCollection>
        <EntranceThemeTransition
            HorizontalOffset="500" />
      </TransitionCollection>
    </Grid.ChildTransitions>
  </Grid>

Well, I’ve jumped all around in this post, and it’s long enough already.  Look for future posts with more specifics about features and code that we’re working into our apps.

Some Development Gotchas (aka Bugs)

Here’s a quick list of some issues we’ve run into these first few weeks.

  • You can only set DataContext in code-behind – future releases will allow setting in XAML
  • There are a handful of bugs in FlipView.SelectedItem.  If you’re binding to the SelectedItem property, you have to manually set the SelectedItem to null and then back to the correct property (get it from your ViewModel) in code-behind.  This will obviously be fixed in a future release.
  • You must use ObservableVector<object> based properties in your VMs if you are binding to ItemsControls.ItemsSource and want the UI to update when there are changes to the collection.  ObservableVector<T> does not exist in the class library – you can find source code for it in many of the SDK samples.
  • Use the correct INotifyPropertyChanged implementation (from Windows.UI.Xaml.Data, not System.ComponentModel)
  • There is no VS item template for custom controls in C#, so VS won’t make you the Themes\Generic.xaml structure.  We’re still tracking this one down. We’ve used a Style resource to describe the template for a Button-derived custom control and it works, but you don’t get access to the Template property in OnApplyTemplate, so we’ve resorted to using VisualStateManager instead of referring to template parts and changing UI that way.
  • I’m sure there are more to come … in fact, check out my co-worker Danny’s post (should be up in the next couple days) with more details on what we’ve been encountering while writing our first few Win8 apps.

Check out the Win8 Metro developer forums for ongoing discussions of many other issues.

Entity Framework Self Tracking Entities Cascade Delete Fails

This is just a quick FYI if you come across a situation while using self tracking entities where you’re getting weird errors when trying to delete a entity that had cascade delete turned on for related entities.

Instead of doing:

MyEntity.MarkAsDeleted();

myContext.MyObjectSet.ApplyChanges(MyEntity);
myContext.SaveChanges();

You need to first make sure the entity is attached and then call DeleteObject for the cascade to run correctly.

So now the code now becomes:

myContext.MyObjectSet.Attach(MyEntity);
myContext.MyObjectSet.DeleteObject(MyEntity);
myContext.SaveChanges();

Happy cascade delete.

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.

Event Leapfrogging

(Thanks to Sam Bent from the WPF team for identifying and giving a name to the problem)

Event Leapfrogging is an issue that arises from a combination of two inherent aspects of .NET events: multicasting and synchronous handler execution. A common place that it shows up is in property change handlers in WPF controls and INotifyPropertyChanged objects.

Here’s some code demonstrating the problem: Continue reading