Proceed with Caution – Windows Phone 8 App Lifecycle Events vs Async Methods

April 13, 2013

“We are on the path to Windows and Windows Phone Convergence” (//Build 2012 – How to Leverage your Code Across WP8 and Win8, Slide 6)

I often hear people saying the phrase “Windows 8 Phone” when they are talking/asking about “Windows Phone 8”.  Throughout presentations that I’ve given and other discussions I’ve had over the past several months that covered the topic of Windows Phone 8, I’ve made it a point to emphasize that Windows Phone 8 is NOT a Windows 8 Phone.  By doing so I’m not trying to be a nit-picky jerk, but rather I’m trying to underscore that there are important differences – both obvious and subtle – between the Windows Store App and Windows Phone platforms, and there are some major pitfalls that developers can stumble into if they are not aware of the way that some of the key platform technologies work.  One situation where these nuanced platform differences comes to light is in differences in the proper use of asynchronous operations within the various lifecycle events exposed by these two platforms; specifically the events pertaining to suspension/deactivation and application closing.

Huh?  To put it simply, the APIs available to Windows Store App development include tools that developers can use to safely(*) include asynchronous method calls when their application is being suspended.  The Windows Phone 8 APIs that support Deactivation and Closing do not include these tools, and it can be tricky to notice the problems that can arise.

Background

OK… time for some background which should serve to highlight the problem.  There are 2 general areas to cover.  First, there are the application lifecycles that are exposed by Windows Store and Windows Phone 8 apps.  Second, some background as to the nature of the new async/await-based asynchronous programming model needs to be provided.

The Windows Phone and Windows Store Application Lifecycles

Both Windows Phone and Windows Store apps (hereafter WP and WS)  feature a lifecycle that is a bit different from that of a traditional desktop application.  While desktop apps are allowed to constantly run (and make unfettered use of precious device resources), the execution lifetime of WP/WS apps is primarily(**) limited to only when the app is currently in the foreground.  In WP, there’s only one app running in the foreground at a given time, where in WS there are currently at most two, depending on whether one is running in Snapped View.  When the apps are either being closed or losing their foreground status, events are provided which allow program code to execute as a result.  Note that while this code can delay the related app lifecycle event from completing, they cannot cancel/prevent it – there is no way to prompt the user to ask “are you sure you’d like this to happen? Yes/No?”  In fact, there’s also the notion of a “death clock” – the apps have a limited amount of time to execute their cleanup code, or the OS will simply kill the app.  With this in mind, it is worth giving strong consideration in WP/WS apps to a “save as you go” approach over the more traditional “save at the very end” approach that was quite common in Desktop apps.

As a simple overview, in WP apps, when a user brings up a different app through the use of one of the device hardware buttons or by responding to a Toast notification or a Reminder, or by switching to another application via a file or protocol association (or one of several other ways), the app enters a dormant state. On its way to this state, the OS gives the app an opportunity to handle a Deactivated event.  The app then has 10 seconds to complete any operations, and once execution of this handler has completed, the OS then moves the app along to this end-state.  Likewise, when an app is closed by using the Back button from the first page in the app’s backstack, the app can elect to handle a Closing event.  Note that the OS may decide to exit a running application that has been deactivated, either due to device memory pressure or if the app is relaunched from the Start or Tile screens, in which case the Deactivated event has been called, but since the app is already dormant, the Closing event will not be called. (App Activation & Deactivation for Windows Phone)

Similarly, in WS apps, when a user brings up a different app through a contract activation (including the Launch contract which occurs when a Tile is clicked form the Start screen), the OS invokes the app-losing-focus’s Suspending event.  This event is also raised if the app is being explicitly closed by dragging/swiping from the top of the screen to the bottom, or the OS is rebooting, etc.  There is no “dedicated” close method that will be called. (Windows Store App Lifecycle Overview)

In either case, these event handler methods offer the last opportunity for an app to persist user state information to disk, potentially to be re-accessed the next time the app is activated/launched/awakened/etc.  Once either the app completes processing these methods or the aforementioned “death clocks” expire, control is returned to the OS to complete its suspension/shutdown operations.  (This last sentence is very important.)

The Task Based Asynchronous Pattern and the Async/Await Keywords

One of the core concepts that applies to development with the new Windows Runtime APIs (WinRT) is that any API call that *could* potentially take more than 50ms to complete has been made asynchronous, with no synchronous equivalent.  Among other consequences, this continues a trend first seen in other Microsoft APIs of ensuring that developers do not create UI’s that lock up while some long-running operation is underway, and if managed correctly, can make applications seem more responsive than ever before.  However, developers who had previously not delved into the nuances of asynchronous programming are now required to do so.  To that end, the async and await keywords added to the C# language offer substantial help, but it is still important to understand what’s going on “under the hood.”

A detailed description of how the compiler reacts to async/await in code it encounters is beyond the scope of this article, and a great explanation is available in Chapter 28 of Jeff Richter’s book “CLR Via C#, 4th Edition”.  To put it simply, when the compiler encounters an async function, behind-the-scenes it generates a state machine and rearranges the code into various states the state machine manages.  The state machine waits for code marked with “await”, and when that code signals as “complete”, the subsequent code is executed, etc.  This is the “magic” that allows the code to be written linearly, while still respecting the asynchronous execution.

The following class shows one of the simplest implementations I could think of:

   1: public class SimpleAsync

   2: {

   3:     public async Task DoSomething()

   4:     {

   5:         await Task.Delay(1000);

   6:         DoSomethingElse();

   7:     }

   8:  

   9:     public void DoSomethingElse()

  10:     {

  11:     }

  12: }

In this case, the compiler loosely interprets the code as the following:

  • Start Task.Delay for 1000ms (on another thread), and when it completes, execute DoSomethingElse().
  • Then signal the Task (implied if return type is void) that execution has completed.
  • If the return type is Task<T>, the function’s return type will be used as the T value.
  • While that is going on, go ahead and return control to the calling function
   1: public class SimpleAsyncThatReturnsSomething

   2: {

   3:     public async Task<Int32> ReturnSomething()

   4:     {

   5:         await Task.Delay(1000);

   6:         return ReturnAValue();

   7:     }

   8:  

   9:     public Int32 ReturnAValue()

  10:     {

  11:         return 42;

  12:     }

  13: }

The Problem

OK…so what’s the big deal?  Some readers may have figured it out from the background – don’t worry if you haven’t – some very competent developers have fumbled this pretty badly.  The crux of the problem lies when you merge the concept of the applications’ lifecycle closing events with the execution of asynchronous code.  Remembering the sentence I called attention to earlier regarding the processing of the Deactivated/Closing events (WP) or the Suspending event (WS):

Once either the app completes processing these methods or the aforementioned “death clocks” expire, control is returned to the OS to complete its suspension/shutdown operations.

But if these methods are made asynchronous using async, the compiler will generate a state machine, moving the execution from the first await forward into alternate threads and returning to the calling method at that point….at which time, the OS will proceed with its suspend/shutdown operations, blithely ignoring whatever may be going on in those other threads.  If the asynchronous method in question happens to be a file-save, congratulations!  You may have just saved half a file!  Or more…or less.  (Have you heard the one that goes “Why did the multithreaded chicken cross the road?  To other side get to the.  Ask me again…”)

This can be seen with the following WP code:

   1: // Code to execute when the application is deactivated (sent to background)

   2: // This code will not execute when the application is closing

   3: private async void Application_Deactivated(object sender, DeactivatedEventArgs e)

   4: {

   5:     await DumpText();

   6: }

   7:  

   8: // Code to execute when the application is closing (eg, user hit Back)

   9: // This code will not execute when the application is deactivated

  10: private async void Application_Closing(object sender, ClosingEventArgs e)

  11: {

  12:     await DumpText();

  13: }

  14:  

  15: private async Task DumpText()

  16: {

  17:     foreach (var currentTime in Enumerable.Range(0, 10).Select(i => DateTime.Now.ToString("T")))

  18:     {

  19:         // Substitute your own asynchronous process

  20:         await Task.Delay(1000);

  21:         Debug.WriteLine(currentTime);

  22:     }

  23: }

And the following WS code:

   1: private async void OnSuspending(object sender, SuspendingEventArgs e)

   2: {

   3:     await DumpText();

   4: }

   5:  

   6: private async Task DumpText()

   7: {

   8:     foreach (var currentTime in Enumerable.Range(0, 10).Select(i => DateTime.Now.ToString("T")))

   9:     {

  10:         // Substitute your own asynchronous process

  11:         await Task.Delay(1000);

  12:         Debug.WriteLine(currentTime);

  13:     }

  14: }

In the examples above, the DumpText function may start outputting content to the Debug Window, though it is likely it won’t even get to the first write, and highly unlikely that it will get all the way to 10.

But it Works in Windows Store Apps…

This is partially true.  WS apps introduce the concept of “deferrals” at critical places where the OS and asynchronous operations may possibly collide – and it just so happens that suspension is one such critical place.  A deferral can be requested from the SuspendingEventArgs that are part of the event handler signature by using the GetDeferral method.  When a deferral is requested, the OS will wait for the deferral instance’s Complete method to be called before it proceeds with its normal suspension/shutdown operations***.  (Shameless self promotion alert: I discuss this in the “Application Suspension” of Chapter 3 – Application Life Cycle and Storage in my book “Windows Store Apps Succinctly.”)  This process is illustrated in the following code, which will successfully get all the way through the desired 10-count:

   1: // The Suspending event handler with an asynchronous operation. 

   2: private async void OnSuspending(Object sender, SuspendingEventArgs e)

   3: {

   4:     var deferral = e.SuspendingOperation.GetDeferral();

   5:     //TODO: Save application state and stop any background activity.

   6:     await DumpText();

   7:     deferral.Complete(); 

   8: } 

Great!  Now all we have to do is be sure to use deferrals in our Windows Phone Deactivated and Closing event handlers and we’re all set!  There’s just one small problem…the DeactivatedEventArgs and ClosingEventArgs provided by those methods have no notion of deferrals…for that matter, WP8 doesn’t have any such notion as a whole.  Remember – we are on a path to convergence…we have yet to achieve said convergence.

image

Great…Now What?

So what are our options in this situation?

  • Use the synchronous WP8 APIs.  In the case of storage, the IsolatedStorage APIs that are part of the WP7 SDK are still available in WP8.  Since these calls are synchronous, it avoids the whole “I’ve returned from the method but am not done with my work” issue that is at play.  However, for code-reuse/compatibility, it isn’t exactly an ideal option (though the lifecycle events are different enough between the platforms that this may not be a big deal) and in general, it feels like a bit of “looking backwards.”
  • Though it has been mentioned before, it should be repeated for completeness – it may not be ideal to “wait until done” to persist content to disk, if that is what the desired async operation involved here happens to be.  It may be better to pursue an approach that involves “save as you go.”

Wrapping Up

In the end, I hope that I have illustrated that it is quite important that developers be aware of the nuances of asynchronous code and the problems than can occur if asynchronous code is used in the exit-oriented event handlers in Windows Phone apps.  Ultimately, the simplest guidance is to not make these handlers asynchronous until such a point that the Windows Phone API is given its own mechanism – similar to that afforded to the Windows Store API or otherwise- for handling asynchronous calls in its exit handlers.

While async & await are powerful additions to our developer toolboxes, but “with great power comes great responsibility.”  It is important to understand their true functionality.  A few resources that can aid in such an understanding include:

* I say “safely” with some trepidation – there are a lot of factors that can impede any perceived “safety” when it comes to executing code in these quasi-shutdown methods, and the nature of asynchronous code inherently adds complexity to the number and nature of possible things that can go wrong.

** Another “weasel word” – there are circumstances where these platforms do allow apps (or some limited portion of the app) to run, such as Background Tasks/Agents.

*** Note that deferrals do not stop the “death clock”…the method can still time-out even if a deferral has been requested.  The only thing the deferral does is prevent the normal course of completion signaling that otherwise takes place when the method returns to its caller.


LIDNUG Webinar Presentation Materials

July 24, 2012

Many thanks to the participants, organizers, and sponsors of today’s LIDNUG webinar – “Putting the Cloud in Your Pocket Pt1 – Using Windows Azure to Build Cloud-Enabled WP7 Apps.”  I especially appreciate the patience of those who attended as we struggled to do the best we could to resolve the LiveMeeting technical issues that dogged us during the presentation.  For what it is worth, prior to the presentation, the LIDNUG folks made sure we did a technical walkthrough to do everything possible to mitigate the possibility of running into these kinds of glitches…alas, despite our best efforts, the “demo gods” decided to frown upon us today.

As I mentioned during the talk, I have gone ahead and posted the code (along with the slide that were available for download during the talk) here.  As is often the case with talks about this topic, the demo contains keys and other “private” information that is specific to my own Azure account.  With that in mind, I have sanitized/removed the private content from the posted demo code, and included a document “ACS Update Instructions” alongside the code zip file that describes the steps necessary to get yourself up and running with your own Azure subscription.

As we mentioned during the talk, I will be working with the LIDNUG folks to make sure we are able to post a complete recording of the presentation.  Stay tuned for updates.  In the meantime, please be sure to check out additional upcoming Wintellect events as well as upcoming LIDNUG events, and please be sure to visit our webinar’s sponsor – Syncfusion.


Boston Azure Bootcamp Presentation Materials

June 24, 2012

I had a tremendous time this weekend presenting alongside Bill Wilder, Michael Collier, John Zablocki, and Jim O’Neil at the Boston Azure Bootcamp event in Cambridge, MA.  The topic once again covered the concepts of using Windows Azure to enhance mobile Windows Phone application and general mobile development considerations, and went beyond my demos to include a hands on lab that most everyone seems to have enjoyed.

As promised, the slide and code content I referred to in my talk can be found here.  I mentioned to a few who asked – there are some values in the lab that are specific to the ACS namespaces I have set up.  I am including in the code file a word doc that indicates how to set up the ACS values for the demo code in question.

Again, many thanks!  I’m looking forward to hearing about how folks are using Azure to add cloud “goodness” to their mobile applications.


CodeStock 2012 Presentation Content

June 17, 2012

I would like to thank the attendees of my “Putting the Cloud in Your Pocket – A Guide to Using Windows Azure to Build Cloud-Enabled Windows Phone Apps” talk at the recent Codestock event – especially considering the early hour following the previous night’s fun.  The slide and code content I referred to in my talk can be found here.   Also, many thanks go out to the event organizers – I had a great time traveling down to Tennessee for this event, and hope to maybe do so again in the future.

As can be expected, I removed my custom/personal ACS information from the sample code.  This includes the acsnamespace and realm resources in the AccessControlResources.xaml file within the Phone project, and the SwtSigningKey, realm, and namespace values from the MVC project’s web.config file.  These values can be obtained from a new or existing ACS namespace as follows:

ACS Configuration Values

These values are available in the following locations (Note – this is based on the current Silverlight-based management portal.  Precise locations may shift slightly when this content moves to the newer HTML5-based portal.)

The namespace value is the namespace you indicated when creating the ACS instance.

image

The Realm is specific to the relying party application that has been configured, and can be found on the Relying Party Application page:

image

The symmetric key can be obtained from the Access Control Service management portal, selecting Certificates and Keys, selecting (and/or creating) a Symmetric Key specific to the namespace:

image

image

image

Async CTP

Also, please remember that the code made use of the Async CTP assembly.  This was not strictly required, but was instead put in place to help improve the code flow instead of using Lambdas or complete methods for the various callback functions used when interacting with Azure Storage.  Information about the Async CTP is available here.


Metro XAML Nugget: App Bar AutoMagic

May 29, 2012

You may have noticed that in many places of the Windows 8 Metro UI, as well as many Metro applications where list content can be selected, that making a selection automatically/magically (“automagically”) brings up one or more app bars.  This is consistent with the “Guidelines and checklist for app bars” published in the Metro Style Apps Dev Center:

Do place contextual commands on an app bar and show that bar programmatically.

If you have commands that are specific to the mode of the app, such as the Crop command appearing only when a photo is selected, place those commands on an app bar and show it programmatically while in that context.

If you have commands that can be performed whether content is selected or not, keep those commands on the bar if you have enough room.

Do set the app bar’s dismissal mode to sticky when displaying contextual commands.

If you have contextual commands on an app bar, set the mode to sticky while that context exists and turn off the sticky mode when the context is no longer present (such as when a photo is deselected). In sticky mode, the bar doesn’t automatically hide when the user interacts with the app. This is useful for multi-select scenarios or when the context involves interaction such as manipulating crop handles. The bar stays visible while the user performs their actions. The user can still hide the bar by swiping the top or bottom edge of the screen and they can show it again with an edge swipe.

One place where this behavior can be seen occurs when selecting and deselecting tiles in the Metro Start Screen.

image

Of course, this is nice and all, but sitting down to implement this (it isn’t out-of-the-box behavior) for the Metro XAML list controls (ListBox, ListView, GridView), I figured I had several options.  First, I could just handle the SelectionChanged event and in the codebehind I could programmatically bring up and/or collapse the page’s app bar(s).  That would do for one-off code, but its hardly the approach I would want to take for a more robust application.  A second option is to bind the list’s SelectedItem(s) property to property on the page’s ViewModel, and either use a related property or a ValueConverter to bind to the AppBar’s properties.  This felt a little bit much for wanting to simply alter the behavior of one control to react to the behavior another control.  There are other solutions that fell into this category as well (ViewState etc.)  What I ended up coming up with is a quasi-Behavior using Attached Properties that makes this (ahem) behavior reusable and quite easy to wire up.

Note: Another similar approach would be to actually use Behavior<T>.  Although this component of the Blend SDK is not included with the WinRT tools, some folks have published the equivalent WinRtBehaviors project on CodePlex at http://winrtbehaviors.codeplex.com/.

As I mentioned, at the heart of this implementation are an attached property and a set of Flags indicating which app bar(s) should react to the selection change.

   1: [Flags]

   2: public enum AppBarDisplayFlags

   3: {

   4:     None = 0,

   5:     Bottom = 1,

   6:     Top = 2,

   7:     BottomAndTop = 3,

   8: }

   9:  

  10: public static readonly DependencyProperty AppBarDisplayOnListSelectionProperty = 

  11:     DependencyProperty.RegisterAttached(

  12:         "AppBarDisplayOnListSelection", 

  13:         typeof(AppBarDisplayFlags), 

  14:         typeof(Selector), 

  15:         new PropertyMetadata(AppBarDisplayFlags.None, OnAppBarDisplayOnListSelectionChanged));

  16:  

  17: public static void SetAppBarDisplayOnListSelection(Selector element, AppBarDisplayFlags value)

  18: {

  19:     element.SetValue(AppBarDisplayOnListSelectionProperty, value);

  20: }

  21:  

  22: public static AppBarDisplayFlags GetAppBarDisplayOnListSelection(Selector element)

  23: {

  24:     return (AppBarDisplayFlags)element.GetValue(AppBarDisplayOnListSelectionProperty);

  25: }

Nothing really fancy there…just a simple attached property – I opted to indicate the owner as the Selector class instead of the containing class simply for convenience.  The important part is that the attached property is defined with a callback to be used when the value of the attached property is changed – OnAppBarDisplayOnListSelectionChanged.

In the property changed handler, a check is performed to see if the code is running in the designer – if so, everything bails out.  Otherwise, the selector to whom the property is being applied is obtained (if not found, bail out).  The selector and the value of the flags are then passed to a helper method to handle hooking up to the pertinent events.

   1: private static void OnAppBarDisplayOnListSelectionChanged(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs dependencyPropertyChangedEventArgs)

   2: {

   3:     // Don't hook up the event listeners when running in the designer

   4:     if (Windows.ApplicationModel.DesignMode.DesignModeEnabled) return;

   5:  

   6:     // Identify the selector to which this property has been applied (if none, then do nothing)

   7:     var selector = dependencyObject as Selector;

   8:     if (selector == null) return;

   9:  

  10:     var selectedFlags = (AppBarDisplayFlags)dependencyPropertyChangedEventArgs.NewValue;

  11:     HookEvents(selector, selectedFlags);

  12: }

In HookEvents, as long as one of the app bars is of interest, listeners are registered for the selector’s Unloaded and SelectionChanged events.  Some preemptive housekeeping is also performed to first unhook the same events in order to prevent leaks.  The Unloaded event merely unhooks these same events to once again prevent leaks.

The big workhorse is the HandleSelectionChanged event handler.  First, the Visual Tree is traversed until an ancestor of the Selector is found that happens to be a Page – which is presumed to be the site of the app bar(s) being affected.  Then the current state of the setting to show the top and/or bottom app bars is determined, and finally, if an item is selected, the appropriate app bars are shown.  If no item is selected, the appropriate app bars are collapsed.

   1: private static void HandleSelectionChanged(Object sender, SelectionChangedEventArgs e)

   2: {

   3:     var selector = sender as Selector;

   4:     if (selector == null) return;

   5:  

   6:     // Traverse the selector's parents to find the firet "page" element

   7:     var containingPage = selector.GetVisualAncestors().OfType<Page>().FirstOrDefault();

   8:     if (containingPage == null) return;

   9:  

  10:     var currentFlags = GetAppBarDisplayOnListSelection(selector);

  11:     var showBottomAppBar = (currentFlags & AppBarDisplayFlags.Bottom) == AppBarDisplayFlags.Bottom;

  12:     var showTopAppBar = (currentFlags & AppBarDisplayFlags.Top) == AppBarDisplayFlags.Top;

  13:  

  14:     if (selector.SelectedItem != null)

  15:     {

  16:         // An item has been selected - show the relevant app bars

  17:         if (showBottomAppBar) ShowAppBar(containingPage.BottomAppBar);

  18:         if (showTopAppBar) ShowAppBar(containingPage.TopAppBar);

  19:     }

  20:     else

  21:     {

  22:         // Nothing has been selected - hide the relevant app bars

  23:         if (showBottomAppBar) HideAppBar(containingPage.BottomAppBar);

  24:         if (showTopAppBar) HideAppBar(containingPage.TopAppBar);

  25:     }

  26: }

Once the project containing this code has been compiled, the attached property is available to be set to Selector-derived UI elements.

   1: <GridView

   2:     x:Name="itemGridView"

   3:     AutomationProperties.AutomationId="ItemGridView"

   4:     AutomationProperties.Name="Grouped Items"

   5:     Margin="116,0,40,46"

   6:     ItemsSource="{Binding Source={StaticResource groupedItemsViewSource}}"

   7:     ItemTemplate="{StaticResource Standard250x250ItemTemplate}"

   8:     SelectionMode="Multiple"

   9:     local:AppBarExtensions.AppBarDisplayOnListSelection="Bottom">

Obviously, this seems like a long way to travel – the value is realized when there are multiple Selector’s scattered throughout an application where this behavior is to be applied, and/or when this code is shared across multiple applications.  The entire code for the class containing the attached property follows:

   1: public static class AppBarExtensions

   2: {

   3:     [Flags]

   4:     public enum AppBarDisplayFlags

   5:     {

   6:         None = 0,

   7:         Bottom = 1,

   8:         Top = 2,

   9:         BottomAndTop = 3,

  10:     }

  11:  

  12:     public static readonly DependencyProperty AppBarDisplayOnListSelectionProperty = 

  13:         DependencyProperty.RegisterAttached(

  14:             "AppBarDisplayOnListSelection", 

  15:             typeof(AppBarDisplayFlags), 

  16:             typeof(Selector), 

  17:             new PropertyMetadata(AppBarDisplayFlags.None, OnAppBarDisplayOnListSelectionChanged));

  18:  

  19:     public static void SetAppBarDisplayOnListSelection(Selector element, AppBarDisplayFlags value)

  20:     {

  21:         element.SetValue(AppBarDisplayOnListSelectionProperty, value);

  22:     }

  23:  

  24:     public static AppBarDisplayFlags GetAppBarDisplayOnListSelection(Selector element)

  25:     {

  26:         return (AppBarDisplayFlags)element.GetValue(AppBarDisplayOnListSelectionProperty);

  27:     }

  28:  

  29:     private static void OnAppBarDisplayOnListSelectionChanged(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs dependencyPropertyChangedEventArgs)

  30:     {

  31:         // Don't hook up the event listeners when running in the designer

  32:         if (Windows.ApplicationModel.DesignMode.DesignModeEnabled) return;

  33:  

  34:         // Identify the selector to which this property has been applied (if none, then do nothing)

  35:         var selector = dependencyObject as Selector;

  36:         if (selector == null) return;

  37:  

  38:         var selectedFlags = (AppBarDisplayFlags)dependencyPropertyChangedEventArgs.NewValue;

  39:         HookEvents(selector, selectedFlags);

  40:     }

  41:  

  42:     private static void HookEvents(Selector selector, AppBarDisplayFlags flags)

  43:     {

  44:         if (selector == null) throw new ArgumentNullException("selector");

  45:  

  46:         // Clear any "active" event handlers

  47:         UnhookEvents(selector);

  48:  

  49:         if (flags != AppBarDisplayFlags.None)

  50:         {

  51:             selector.Unloaded += HandleUnloaded;

  52:             selector.SelectionChanged += HandleSelectionChanged;

  53:         }

  54:     }

  55:  

  56:     private static void UnhookEvents(Selector selector)

  57:     {

  58:         if (selector == null) throw new ArgumentNullException("selector");

  59:  

  60:         selector.Unloaded -= HandleUnloaded;

  61:         selector.SelectionChanged -= HandleSelectionChanged;

  62:     }

  63:  

  64:     private static void HandleUnloaded(Object sender, RoutedEventArgs e)

  65:     {

  66:         UnhookEvents((Selector)sender);

  67:     }

  68:  

  69:     private static void HandleSelectionChanged(Object sender, SelectionChangedEventArgs e)

  70:     {

  71:         var selector = sender as Selector;

  72:         if (selector == null) return;

  73:  

  74:         // Traverse the selector's parents to find the firet "page" element

  75:         var containingPage = selector.GetVisualAncestors().OfType<Page>().FirstOrDefault();

  76:         if (containingPage == null) return;

  77:  

  78:         var currentFlags = GetAppBarDisplayOnListSelection(selector);

  79:         var showBottomAppBar = (currentFlags & AppBarDisplayFlags.Bottom) == AppBarDisplayFlags.Bottom;

  80:         var showTopAppBar = (currentFlags & AppBarDisplayFlags.Top) == AppBarDisplayFlags.Top;

  81:  

  82:         if (selector.SelectedItem != null)

  83:         {

  84:             // An item has been selected - show the relevant app bars

  85:             if (showBottomAppBar) ShowAppBar(containingPage.BottomAppBar);

  86:             if (showTopAppBar) ShowAppBar(containingPage.TopAppBar);

  87:         }

  88:         else

  89:         {

  90:             // Nothing has been selected - hide the relevant app bars

  91:             if (showBottomAppBar) HideAppBar(containingPage.BottomAppBar);

  92:             if (showTopAppBar) HideAppBar(containingPage.TopAppBar);

  93:         }

  94:     }

  95:  

  96:     private static void ShowAppBar(AppBar appBar)

  97:     {

  98:         if (appBar == null) return;

  99:  

 100:         appBar.IsSticky = true;

 101:         appBar.IsOpen = true;

 102:     }

 103:  

 104:     private static void HideAppBar(AppBar appBar)

 105:     {

 106:         if (appBar == null) return;

 107:  

 108:         appBar.IsOpen = false;

 109:         appBar.IsSticky = false;

 110:     }

 111:  

 112:     /// <summary>

 113:     /// Gets the ancestors of the element, up to the root.

 114:     /// </summary>

 115:     /// <param name="node">The element to start from.</param>

 116:     /// <returns>An enumerator of the ancestors.</returns>

 117:     public static IEnumerable<FrameworkElement> GetVisualAncestors(this FrameworkElement node)

 118:     {

 119:         var parent = node.GetVisualParent();

 120:         while (parent != null)

 121:         {

 122:             yield return parent;

 123:             parent = parent.GetVisualParent();

 124:         }

 125:     }

 126:  

 127:     /// <summary>

 128:     /// Gets the visual parent of the element.

 129:     /// </summary>

 130:     /// <param name="node">The element to check.</param>

 131:     /// <returns>The visual parent.</returns>

 132:     public static FrameworkElement GetVisualParent(this FrameworkElement node)

 133:     {

 134:         return VisualTreeHelper.GetParent(node) as FrameworkElement;

 135:     }

 136: }


Using the New Caller Information Attributes for Reliable Property Change Notifications

March 4, 2012

As anyone who has implemented the INotifyPropertyChanged interface knows, the fact that the PropertyChangedEventArgs takes a property name as a string means that you are one fat-fingered mistake away from a bug that can sometimes be difficult to track down.  If the property name supplied in the string doesn’t match the actual property name, the data binding (or other operations) that relies on this interface doesn’t work properly.

   1: public Int32 MyProperty

   2: {

   3:     get { return _myProperty; }

   4:     set

   5:     {

   6:         if (_myProperty != value)

   7:         {

   8:             _myProperty = value;

   9:             OnPropertyChanged("MyProperty");

  10:         }

  11:     }

  12: }

Lambda expressions and Expression Trees in .Net 3 brought a solution to the problem, where the compile-time checking could help ensure that a correct value was provided.  I blogged about this back in 2010 (http://blog.dotnetgator.com/2010/06/21/finding-binding-trouble/), and even cited my (then-future) coworker Jeremy Likness’s treatment of the same topic (http://csharperimage.jeremylikness.com/2010/06/tips-and-tricks-for-inotifypropertychan.html).

   1: public Int32 MyProperty

   2: {

   3:     get { return _myProperty; }

   4:     set

   5:     {

   6:         if (_myProperty != value)

   7:         {

   8:             _myProperty = value;

   9:             OnPropertyChanged(() => MyProperty);

  10:         }

  11:     }

  12: }

Now there’s a new feature in .Net 4.5 that provides yet another opportunity to ensure that INotifyPropertyChanged is implemented correctly – possibly in a simpler fashion than ever before, and with better performance than the Expression Tree/Lambda expression approach.

.Net 4.5 includes 3 new “Caller Information” attributes  – CallerFilePathAttribute, CallerLineNumberAttribute, and CallerMemberNameAttribute.  These three attributes are scoped to individual method parameters, and when used, they apply the indicated value from the CALLING METHOD to the called method’s attributed parameter at run time.  In our case, we’re interested in the CallerMemberName attribute, which we can use to automatically retrieve the property that is trying to raise the property change notification:

   1: private void OnPropertyChanged([CallerMemberName] String caller = null)

   2: {

   3:     var handler = PropertyChanged;

   4:     if (handler != null)

   5:     {

   6:         handler(this, new PropertyChangedEventArgs(caller));

   7:     }

   8: }

Note that the Caller Information attributes require a default value be supplied.

This reduces the overhead of a property in the class that provides this method to the following:

   1: public Int32 MyProperty

   2: {

   3:     get { return _myProperty; }

   4:     set

   5:     {

   6:         if (_myProperty != value)

   7:         {

   8:             _myProperty = value;

   9:             OnPropertyChanged();

  10:         }

  11:     }

  12: }

Of course, one important question is how does this method perform in comparison to either just providing a string, or using the Lambda/Expression Tree approach?  In my tests with iterations of between 1,000-500,000 property changes I saw between ~10-30% performance improvement over the Lambda/Expression Tree approach, and performance between ~20-30% lower than using a directly supplied string.

Note that the latest version of the MSDN documentation illustrating the implementation of the INotifyPropertyChanged interface (as of this writing) show the use of the CallerMemberName attribute – http://msdn.microsoft.com/en-us/library/ms229614(v=vs.110).aspx


NuGet Nugget: File-System Based Package Stores

December 16, 2011

A recent network “hiccup” posed a bit of a challenge to a demo that was built around showing how the Windows Azure Toolkit for Windows Phone (WATWP) NuGet packages make it easy to add Windows Azure cloud features to a Windows Phone 7 application.  So how do you access NuGet content when a network connection isn’t available?  What if you want to exert some management over the updates that are exposed to the developers in your enterprise, including exposing often-used or internal-use assets?

It turns out that NuGet offers some functionality that addresses these scenarios.  In addition to supporting the ability to set up your own package server (also known as Creating Remote Feeds in the NuGet documentation), there is the ability to consume packages collected in a directory – either a network share or a local file-system folder.  This is illustrated in the NuGet documentation under the subtopic “Creating Local Feeds” within the “Hosting Your Own NuGet Feeds” topic.

Populating a File-System Based Package Store

Any folder that contains NuGet .nupkg files can be set to be as a file-system based package server.  From my own use, folders that contain subfolders with .nupkg files will also work, allowing for organization and hierarchy.  If you already have a Visual Studio solution that has references to NuGet packages, moving these packages into such a local package store can be quite simple (especially for demos!)  Just locate the “packages” folder that is created when the NuGet packages are added

image

The entire package folder is not required, since the nupkg files are really Zip files that contain all of the necessary contents.  Search for files that end with the .nupkg extension. 

SNAGHTML9fbf7a

Simply copy all of these files into the folder you are using for your file-system based package store.  Note that a wider set of packages is available in your local package cache, which is normally maintained in <UserFolder>\AppData\Local\NuGet\Cache, and can be accessed from Visual Studio via Tools-Library Package Manager-Package Manager Settings, and click the “Browse” button in the General section of the Package Manager settings node.

Using File-Based Package Stores

To tell Visual Studio to consume file-based package stores, bring up the settings dialog (via Tools-Library Package Manager-Package Manager Settings or through the other accessors in Visual Studio) and select the Package Sources section of the Package Manager settings node.  Provide a name and type in the path or browse to the package location and click the Add button.  Note that the elements in the Available Package Sources list are shown in a check-list-box – they can be enabled or disabled.  Elements in the list can also be reordered in order to determine the precedence in which the sources are searched for matching packages.

SNAGHTMLab5b5b

When adding NuGet package references to your project in Visual Studio via the Manage NuGet Packages dialog, note that the newly named source now appears within the “Online” package listing section. 

SNAGHTMLb09c32

The new source is also available as a pulldown option in the Package Manager Console window.

SNAGHTMLb430e2

As I’ve been digging into NuGet more lately, I’ve been quite impressed by the functionality it exposes.  There’s much more to it than just a right-click menu item and a dialog box  that adds and updates project assembly references.  Some of my current favorites include managing package references at the solution level and visualizing NuGet package chains.  Be sure to check out the NuGet docs in case you have yet to discover your favorite.


Follow

Get every new post delivered to your Inbox.