Discover Properties of Storage Items in Windows Store Apps

Preface

Sometimes it is helpful to discover some or all properties of storage items (StorageFile, StorageFolder).

These classes implement the interfaces IStorageItem and IStorageItemProperties.

IStorgeItem.GetBasicPropertiesAsync gets an object that provides access to the basic properties of an item. IStorageItemProperties.Properties gets an object that provides access to the content-related properties of an item.

To get the properties themselves, you need to call BasicProperties.RetrievePropertiesAsync respectively StorageItemContentProperties.RetrievePropertiesAsync. Both methods expect a list of property names to retrieve. But, at the time of writing this post, the docs do not give a hint on the question:

Which Properties are Available?

The complete list of possible property names can be found here.

But the list does not tell you which property is available on which storage item type. Images might have some other properties like text files or folders. Luckily, there is an undocumented way (undocumented at the time of writing) to get a list of all possible properties: Just pass an empty list. This returns a list of all properties of the current storage item both for basic and content-related properties.

Exceptions

Using the empty-list approach I noticed that there is at minimum one exception to the rule. Having a StorageFolder object of the root directory of a drive, e.g. c:\, the properties “System.ItemType” and “System.ItemTypeText” are not contained in the returned dictionary.

On the other hand, calling StorageItemContentProperties.RetrievePropertiesAsync(new string[] { "Type" }) on such a storage item, the result contains one entry with the key “System.ItemTypeText” with the value “Local Disk” (or “Network Drive”). Please notice that there is no property named “Type” contained in the list of available properties. The behavior is the same on Windows 8.1 Preview.

Discovering

Putting this together, one might think that the combination of basic and content-related properties gives the sum of all properties. Well, it does. But from what I saw during my tests, both lists contain the items. There is no difference between the basic and the content-related list. So you are free to use one of them (observed this on Windows 8.1 Preview too).

Tracing Basic Properties

To trace out all the properties using the basic interface, one might use this code:

private static async Task TraceBasicPropertiesAsync
  (
  IStorageItem storageItem
  )
{
  Debug.WriteLine(
    "{0}Tracing basic properties of storage item >{1}< / >{2}<", 
    Environment.NewLine, storageItem.Name, storageItem.Path);

  BasicProperties basicProperties 
    = await storageItem.GetBasicPropertiesAsync();

  Debug.WriteLine(String.Format(CultureInfo.InvariantCulture, 
    "DateModified {0:u} (UTC), ItemDate {1:u} (UTC), Size {2}", 
    basicProperties.DateModified, basicProperties.ItemDate, 
    basicProperties.Size));

  IDictionary<string, object> basicPropertyList 
    = await basicProperties.RetrievePropertiesAsync(new string[] { });

  foreach (KeyValuePair<string, object> property 
    in basicPropertyList.OrderBy(item => item.Key))
  {
    Debug.WriteLine("BasicProperty >{0}<: >{1}<", 
      property.Key, property.Value);
  }

  if (basicPropertyList.ContainsKey("System.Kind"))
  {
    foreach (string kind 
      in (string[]) basicPropertyList["System.Kind"])
    {
      Debug.WriteLine("BasicProperty kind >{0}<", kind);
    }
  }
}

Tracing Content-Related Properties

The code to trace all the content-related properites looks very similar:

private static async Task TraceContentRelatedPropertiesAsync
  (
  IStorageItem storageItem
  )
{
  Debug.WriteLine(
    "{0}Tracing content-related properties of storage item >{1}< / >{2}<",
    Environment.NewLine, storageItem.Name, storageItem.Path);

  // We need a different interface to access the 
  // content-related properties.
  IStorageItemProperties storageItemProperties 
    = storageItem as IStorageItemProperties;

  if (storageItemProperties == null)
  {
    Debug.WriteLine("IStorageItemProperties not implemented",
      Environment.NewLine);
    return;
  }

  IDictionary<string, object> propertyList 
    = await storageItemProperties.Properties
      .RetrievePropertiesAsync(new string[] { });

  foreach (KeyValuePair<string, object> property 
    in propertyList.OrderBy(item => item.Key))
  {
    Debug.WriteLine("Property >{0}<: >{1}<", 
      property.Key, property.Value);
  }

  if (propertyList.ContainsKey("System.Kind"))
  {
    foreach (string kind 
      in (string[]) propertyList["System.Kind"])
    {
      Debug.WriteLine("Property kind >{0}<", kind);
    }
  }

  // Handle missing properties for root directories.
  if (!propertyList.ContainsKey("System.ItemTypeText"))
  {
    IDictionary<string, object> missingList
      = await storageItemProperties.Properties
        .RetrievePropertiesAsync(
          new string[] { "System.ItemType", "System.ItemTypeText" });

    foreach (KeyValuePair<string, object> property 
      in missingList.OrderBy(item => item.Key))
    {
      Debug.WriteLine("Property >{0}<: >{1}<", 
        property.Key, property.Value);
    }
  }
}

There is an extra loop on the “System.Kind” property becaus it contains a string array.

Links

Windows Property System that can be set on Windows files

Update: MDI / Multiple Tabs Flat Navigation App Bar Sample

The MDI / Multiple Tabs Flat Navigation App Bar in Windows Store Apps sample was updated to version 1.2.0.0.

Now it also runs on Windows 8.1. Before the update, it crashes on Windows 8.1 when animation was disabled and the user right-clicks and added new content pages more than two times.

In case you cannot see any animation under Windows 8.1, please check the Performance Options setting “Animate controls and elements inside windows” (System / Advanced system settings / Performance / Settings). If this option is not set, transition is disabled for Windows Store apps too.

MessageBox for Windows Store Apps in C# / XAML

Preface

The replacement of MessageBox for Windows Store apps is the class MessageDialog.

This class is fine as long as you do not need more than three options the user can choose from. In technical words, MessageDialog allows only up to three commands. At the time of writing, this is not mentioned in the documentation of the Commands property, but in Quickstart: Adding a message dialog (Windows Store apps using JavaScript and HTML). In case you try to add more commands, an exception will be thrown: “The operation attempted to access data outside the valid range (Exception from HRESULT: 0x8000000B)

Of course, I do have the need for more than three commands. But the new control should not differ much from MessageDialog.

This results in the following requirements:

  • Show the message box by calling a ShowAsync method
  • Dynamically add IUICommand-based commands with a button label, an optional Action that will be executed when the user selects the command, and an optional id
  • Define a default cancel and default focus command
  • Show a message, an optional title, and an optional symbol
  • Reset the focus when the message box closes

ShowAsync & Dynamic Number of Buttons

This part was the most challenging one – and the funniest one too 🙂

The approach in the sample is this:

  • Have a popup torso, ready to be filled with title, message, symbol, and command buttons
  • Create one button per command, and attach a ManualResetEvent to each button
  • Start a new thread and let it wait for of one these wait handles to be signaled, i.e. wait for the user to push one of the buttons
  • Map the signaled wait handle to the corresponding action
  • Meanwhile, await the completion of the new thread
  • Execute the action by the main (UI) thread
  • Return the selected command
  • Reset the focus

Add Commands To Popup

Before it makes sense to bring up the message box, the buttons for the commands have to be added. And there needs to be some kind of connection between the buttons and the ManualResetEvents that are required for async usage. Here is the implementation.

// Implemented by MessageBox
private void AddCommandsToPopup()
{
  // In case no commmand is set, 
  // add a continue command without an action.
  if (CommandList.Count == 0)
  {
    CommandList.Add(new UICommand("Continue"));
  }

  // Remove exiting buttons 
  // in case ShowAsync was called more than once.
  ControlStackPanel.Children.Clear();

  // Create the delegate command used when a button is pressed
  DelegateCommand<ManualResetEvent> delegateCommand
    = new DelegateCommand(OnButtonPressed);

  // Iterate over the list of commands.
  foreach (IUICommand command in CommandList)
  {
    // Create a new wait handle for the command
    ManualResetEvent waitHandle = new ManualResetEvent(false);

    // Add it to the list.
    WaitHandleList.Add(waitHandle);

    // Create the button and attach the wait handle.
    Button button = new Button()
    {
      Command = delegateCommand,
      CommandParameter = waitHandle,
      Content = command.Label,
      Style = (Style)Application.Current.Resources["ButtonStyle"]
    };
    
    // Add the button to the popup
    ControlStackPanel.Children.Add(button);
  }
}

Handling Button Pressed

This command handler is really simple. The only intention is to let the waiting thread know that a button was pressed. This is done by signal the ManualResetEvent that is associated to button as the CommandParameter. That’s it.

// Implemented by MessageBox
private void OnButtonPressed
  (
  ManualResetEvent waitHandle
  )
{
  // Just signal the wait handle.
  waitHandle.Set();
}

Open the Message Box and Wait For User Input

Now that everything is prepared, we can go on and show the message box.

// Implemented by MessageBox
public async Task ShowAsync()
{
  // Add all commands to the command bar 
  // and create the matching wait handles.
  AddCommandsToPopup();

  // Keeps the index of the signaled wait handle.
  int signaledHandle = -1;

  // Find the control currently having the focus
  Control focusedControl 
    = FocusManager.GetFocusedElement() as Control;

  // Start the thread to wait for user input.
  Task waitForUserInputTask = Task.Run(() =>
  {
    // Wait for a handle to be signaled.
    signaledHandle 
      = ManualResetEvent.WaitAny(WaitHandleList.ToArray());
  });

  // Open the message box with a popup.
  Popup popup = PopupHelper.CreateFullScreenWithChild(this);

  // Set the focus on the defined button
  if (FocusCommandIndex >= 0
    && FocusCommandIndex < CommandList.Count)
  {
    ((Button)(ControlStackPanel.Children[FocusCommandIndex]))
      .Focus(FocusState.Programmatic);
  }

  // Wait for the wait thread to finish 
  // (one of the events to be signaled)
  await Task.WhenAny(new Task[] { waitForUserInputTask });

  // Free all wait handles.
  while (WaitHandleList.Count > 0)
  {
    WaitHandleList[0].Dispose();
    WaitHandleList.RemoveAt(0);
  }

  try
  {
    // Invoke the event handler of the selected command 
    // in case it is defined.
    if (CommandList[signaledHandle].Invoked != null)
    {
      CommandList[signaledHandle].Invoked
        .Invoke(CommandList[signaledHandle]);
    }
  }
  catch (Exception)
  {
    // re-throw any exception caused by the event handler.
    throw;
  }
  finally
  {
    // Make sure the popup will be closed.
    popup.IsOpen = false;

    // Release the message box from the popup
    popup.Child = null;

    // Reset the focus
    if (focusedControl != null)
    {
      focusedControl.Focus(FocusState.Programmatic);
    }
  }

  // Return the selected command
  return (CommandList[signaledHandle]);
}

That’s all the “magic” behind the async call. The very important implementation detail is that the sequence of the list of commands and wait handle have to be the same. Because ManualResetEvent.WaitAny returns the index of the signaled wait handle, it is very simple to call the corresponding event handler.

UI Controls Must Not Have Multiple Parents

To be able to call ShowAsync more than once on the same MessageBox instance, it is important to “release” the instance from its containing Popup. This is done by setting the Popup.Child to null.

In case the MessageBox is not released, an exception will be thrown when it is set as the child of a newly created Popup. The exception’s message is “Value does not fall within the expected range.” It is thrown by Popup.put_Child, means the setter of the Child property.

Well, the message does not seem very helpful to me. But after all, it makes sense that a UI control cannot have multiple parents. This is why the local Popup‘s Child is set to null after it is closed.

Using the MessageBox

In case the implementation details are a little bit confusing to you: relax. You don’t have to implement it yourself 😉 Focus on the usage. This should look very familiar to all users of MessageDialog.

// Implemented by MainPage
private async Task ShowInformationAsync()
{
  // Create the message box.
  MessageBox messageBox 
    = new MessageBox("This is an information.", 
        "Showing information", MessageBoxSymbol.Information);

  // Add the commands
  messageBox.CommandList.Add(new UICommand("OK", 
    action: null, commandId: "Confirmed"));
  messageBox.CommandList.Add(new UICommand("Abort", 
    action: null, commandId: "Aborted"));

  // Set the index of the focus and cancel command
  messageBox.FocusCommandIndex =
  messageBox.CancelCommandIndex = 1;

  // Show the message box
  string selectedCommandId 
    = (string)(await messageBox.ShowAsync()).Id;

  // Show the value selected
  ResultTextBlock.Text = selectedCommandId;
}

This sample uses the id of the selected command. The code contains samples using the event handler (action) and just the command too.

Please notice that the MessageBox implementation allows you to add a symbol. There is a definition for information, warning, and error included in the sample. In case you need some more, feel free to extent the code.

Disable AppBars

The MessageBox suppresses the opening of app bars, caused by a right click, as long as it is open. This is implemented by MessageBox by handling the RightTapped event. The Handled property of the event arguments is set to true.

It does not prevent the app bar from being opened when the user swipes in from the lower edge. There is no simple event to be handled for this gesture. One idea might be to handle the Opened event of the AppBar. When a MessageBox is open, the event handler should close the AppBar immediately.

Popup Dialog Basics

Please refer to BusyIndicator for Windows Store Apps in C# / XAML for details on popup dialog basics, like disabling the user to interact with the app.

For details on command delegates, please refer to Simple and Generic ICommand Implementation for Usage in XAML.

The Sample

… can be found here.

Information MessageBox

Warning MessageBox

Error MessageBox

Links

Quickstart: Adding a message dialog (Windows Store apps using JavaScript and HTML)

BusyIndicator for Windows Store Apps in C# / XAML

Simple and Generic ICommand Implementation for Usage in XAML

Threading Objects and Features

BusyIndicator for Windows Store Apps in C# / XAML

Preface

The BusyIndicator for Windows Store apps is a variation of the Busy-Indicating Dialog for Windows Store apps.

The motivation for creating such a control is almost the same. No such a control is available. And I want to make sure the user cannot start a new task while a running one has not finished, without blocking the UI thread or fiddling around with flags and disabled controls.

In contrast to the busy-indicating dialog, the busy indicator should not offer the ability to cancel the operation. This is because the underlying operation can’t be canceled too. And it cannot show progress, because the underlying operation is an indeterminate task.

This leads to the following requirements:

  • Disable user interaction (‘lock’ the app)
  • Give visual feedback to let the user know interaction is disabled
  • Do not block the UI thread
  • Show some progress indication

Also, it should comply with these Windows 8 user experience guidelines for indeterminate tasks:

  • If the task is modal — it blocks interaction until its completion — use the indeterminate progress ring style
  • Provide status text to the right of the progress ring
  • Make the progress ring the same color as its status text
  • Disable controls that user shouldn’t interact with while the task is running (matches with the first item of the requirements list above)

Disable User Interaction

Disabling the user to interact with the app is quite simple. Rob Caplan gave me the initial idea in his answer on how one might implement a modal popup. He suggested to use a full screen popup with a similar look to the MessageDialog.

Creating a full screen popup, or better say a popup having the current size of the app, disables the interaction with the app. No matter if the user clicks, taps, or uses the pen.

The first requirement is (almost) fulfilled.

Disable Keyboard Interaction

The reason for the ‘almost’ above is this. When you enable keyboard shortcuts in your app like this sample does, you still need some flag fiddling.

The BusyIndicator only disables interaction via the screen (mouse, touch, pen), but not via the keyboard. This is because there is no control embedded into the BusyIndicator that will handle keyboard input. I tried to handle the KeyDown events, but hadn’t received any.

So the bad news is, one has to set a flag when an indeterminate task starts, and evaluate that flag when another task should be started.

The busy-indicating dialog does not have that issue, because it contains a button to cancel the operation. This button captures the keyboard input.

Give Visual Feedback

Depending on how the full screen popup is implemented, the user might not recognize that the interaction is disabled.

Looking at MessageDialog, one might notice that the area that is not covered by the dialog itself is dimmed out.

To achieve this, a UserControl is implemented. In the sample code, this user control is named BusyIndicator and can be found in UI/Xaml/Popups.

BusyIndicator contains one Grid without any content. This Grid has a black background and an opacity of 0.4.

Setting an instance of BusyIndicator as the child of the Popup, the app’s window gets dimmed out when the Popup is opened. The second requirement is fulfilled.

Do Not Block the UI Thread

Because common UI controls are used, this requirement can be fulfilled without any additional effort.

Of course, one has to take care that the operation to be performed is non-blocking. Means it should be implemented in an asynchronous way. But this is independent from the implementation of the BusyIndicator.

Show Some Progress Indication

Now, the user sees that the interaction is disabled. But there is no information about what is going on. This might lead to the impression that the app has stopped working.

To show that there is something going on in the background, BusyIndicator contains a second Grid. It is something like a modal dialog, showing processing information. This Grid contains a ProgressRing and aTextBlock.

The ProgressRing is what the guidelines demands for indeterminate tasks. The TextBlock makes the control comply with the guideline to provide some status text.

The text will be set when the BusyIndicator is created. There is no binding required, since the text will not change while the BusyIndicator is active.

Make the Progress Ring the Same Color as Its Status Text

To comply with this UX guideline, the file Assets/ApplicationStyles.xaml contains the following SolidColorBrush definition:

<SolidColorBrush x:Key="IndicatorTextBrush" Color="#383838"/>

This brush is used by the TextBlock and the ProgressRing of the indicator to set the Foreground property.

Creating the Busy Indicator

The following code snippet shows all the steps that needs to be done to show the busy indicator.

// Implemented by BusyIndicator
public static BusyIndicator Start
  (
  string title
  )
{
  // Create a popup with the size of the app's window.
  Popup popup = new Popup()
  {
    Height = Window.Current.Bounds.Height,
    IsLightDismissEnabled = false,
    Width = Window.Current.Bounds.Width
  };

  // Create the BusyIndicator as a child, 
  // having the same size as the app.
  BusyIndicator busyIndicator = new BusyIndicator(title)
  {
    Height = popup.Height,
    Width = popup.Width
  };

  // Set the child of the popop
  popup.Child = busyIndicator;

  // Postion the popup to the upper left corner
  popup.SetValue(Canvas.LeftProperty, 0);
  popup.SetValue(Canvas.TopProperty, 0);

  // Open it.
  popup.IsOpen = true;

  // Return the BusyIndicator
  return (busyIndicator);
}

Prepare the Indeterminate Task

Because there are several steps to be done before an indeterminate task can start, this is encapsulated in a separate method.

// Implemented by MainPage
private BusyIndicator PrepareIndeterminateTask
  (
  string title
  )
{
  // Disable the app bar
  BottomAppBar.IsEnabled = false;

  // Lock the screen by starting the BusyIndicator
  BusyIndicator busyIndicator = BusyIndicator.Start(title);

  // Set the flag
  IsTaskInProgress = true;

  // return the indicator
  return (busyIndicator);
}

Please notice the fact that the app bar is disabled explicitly. The popup does not ‘block’ the app bar.

Cleanup

When the indeterminate task has finished, some cleanup is required.

// Implemented by MainPage
private void CleanUpIndeterminateTask
  (
  BusyIndicator busyIndicator
  )
{
  // close the BusyIndicator
  busyIndicator.Close();

  // Reset the flag
  IsTaskInProgress = false;

  // Enable the app bar
  BottomAppBar.IsEnabled = true;
}

Consider Windows Store App Lifecycle

In the article ‘The Windows Store App Lifecycle‘, Rachel Appel points out that “Windows 8 is changing how and when applications run”. In fact, it does!

Unlike desktop applications, Windows 8 suspends Windows Store apps (after a few seconds) when the user switches to another app. No matter what the app is currently doing. You cannot keep the app ‘alive’.

One should be aware of this. It means the user has to wait for long running operation to complete, and should not switch to another app meanwhile. This is kind of ‘blocking’ the device. Keeping this in mind, one should think twice before using Windows Store apps to execute long running operations, e.g. copy gigabytes of data.

Yes, there are background tasks available. But you cannot trigger them from within your app. So the usage is limited.

The Sample

… can be found here.

Screenshot

Screenshot

Links

Busy-Indicating Dialog for Windows Store apps

Forum question Modal popup

Download Windows 8 User Experience Guidelines for Windows Store apps

The Windows Store App Lifecycle

Background Tasks

Forum question ‘Trigger background task manually

Busy-Indicating Dialog for Windows Store Apps in C# / XAML

Preface

Some of you might know the BusyIndicator from the WPF Toolkit or from Silverlight.

I was using this control in Silverlight to disable user interaction while the application was performing some long running operations. This makes it really easy to make sure the user will not start a new task while another has not yet finished. And – very important – it does not block the UI thread, so the application does not seem to be unresponsive to the operation system.

Microsoft does not offer such a control for Windows Store apps. But even in a Windows Store app I needed to make sure the user ‘waits’ for the completion of a task, before a new is started. And I do not wanted to implement this by adding a flag telling no new task can be started (and/or disable controls based on that flag, …).

So what I wanted was a control that meets the following requirements:

  • Disable user interaction (‘lock’ the app)
  • Give visual feedback to let the user know interaction is disabled
  • Do not block the UI thread
  • Show some progress indication
  • Enable the user to cancel the operation

Disable User Interaction

Disabling the user to interact with the app is quite simple. Rob Caplan gave me the initial idea in his answer on how one might implement a modal popup. He suggested to use a full screen popup with a similar look to the MessageDialog.

Creating a full screen popup, or better say a popup having the current size of the app, and setting the focus to that popup, no interaction with the app is possible any more. No matter if the user clicks, taps, or uses the keyboard or pen.

The first requirement is fulfilled.

Give Visual Feedback

Depending on how the full screen popup is implemented, the user might not recognize that the interaction is disabled.

Looking at MessageDialog, one might notice that the area that is not covered by the dialog itself is dimmed out.

To achieve this, a UserControl is implemented. In the sample code, this user control is named BusyIndicatingDialog and can be found in UI/Xaml/Popups.

BusyIndicatingDialog contains one Grid without any content. This Grid has a black background and an opacity of 0.4.

Setting an instance of BusyIndicatingDialog as the child of the Popup, the app’s window gets dimmed out when the Popup is opened. The second requirement is fulfilled.

Do Not Block the UI Thread

Because common UI controls are used, this requirement can be fulfilled without any additional effort.

Of course, one has to take care that the operation to be performed is non-blocking. Means it should be implemented in an asynchronous way. But this is independent from the implementation of the BusyIndicatingDialog.

Show Some Progress Indication

Now, the user sees that the interaction is disabled. But there is no information about what is going on. This might lead to the impression that the app has stopped working.

To show that there is something going on in the background, BusyIndicatingDialog contains a second Grid. It is something like a modal dialog, showing the current processing state. It contains some TextBlocks and a ProgressBar.

These controls are bound to a view model, implemented by BusyIndicatingViewModel. This class can be found in ViewModels.

BusyIndicatingViewModel implements an event handler, OnItemProcessed. The class that implements the long-running operation, MainPage in this sample, needs to fire an appropriate event every time an item is processed (or when an update of the progress should be displayed). This event is implemented by MainPage.ItemProcessed.

And because BusyIndicatingViewModel implements the INotifyPropertyChanged interface (via its base class BindableBase), setting the properties in OnItemProcessed updates all the controls of the dialog.

Cancel the Operation

So far, we are able to stop user interaction with the app, give visual feedback on this, do not block the UI thread, and show how the operation proceeds. But maybe the user wants to cancel that operation, for whatever reason.

To enable the user to do this, a cancel button is added to the BusyIndicatingDialog. Pressing this button, the Cancel event is fired by the BusyIndicatingViewModel. This is implemented by binding the Command property of the Button control to the CancelOperationCommand of the view model.

Of course, just firing an event does not stop anything at all. The class that implements the long-running operation, MainPage in this sample, has to register an event handler on this event. The event handler (OnCancelOperation) sets a flag. This flag is evaluated on each iteration of the long-running operation. When it is set, the operation stops.

This feature makes the BusyIndicatingDialog ready to use.

Creating the Busy-Indicating Dialog

The following code snippet shows all the steps that needs to be done to show the busy-indicating dialog.

// Implemented by BusyIndicatingDialog
public static BusyIndicatingDialog LockScreen
  (
  int numberOfItemsToProcess
  )
{
  // Create a popup with the size of the app's window.
  Popup popup = new Popup()
  {
    Height = Window.Current.Bounds.Height,
    IsLightDismissEnabled = false,
    Width = Window.Current.Bounds.Width
  };

  // Create the busy-indicating dialog as a child, 
  // having the same size as the app.
  BusyIndicatingDialog dialog 
    = new BusyIndicatingDialog(numberOfItemsToProcess)
  {
    Height = popup.Height,
    Width = popup.Width
  };

  // Set the child of the popop
  popup.Child = dialog;

  // Postion the popup to the upper left corner
  popup.SetValue(Canvas.LeftProperty, 0);
  popup.SetValue(Canvas.TopProperty, 0);

  // Open it.
  popup.IsOpen = true;

  // Set the focus to the dialog
  dialog.Focus(FocusState.Programmatic);

  // Return the dialog
  return (dialog);
}

Prepare the Long Running Operation

Because there are several steps to be done before the long running operation can start, this is encapsulated in a separate method.

// Implemented by MainPage
private BusyIndicatingDialog PrepareLongRunningOperation
  (
  int numberOfItemsToProcess
  )
{
  // Disable the app bar
  BottomAppBar.IsEnabled = false;

  // Lock the screen
  BusyIndicatingDialog indicatorDialog 
    = BusyIndicatingDialog.LockScreen(numberOfItemsToProcess);

  // Set the view model as the event handler for processed items
  ItemProcessed += indicatorDialog.ViewModel.OnItemProcessed;

  // Set the handler for the cancel event.
  indicatorDialog.ViewModel.Cancel += OnCancelOperation;

  // Reset the flag for canceling the operation.
  CancelOperation = false;

  // return the dialog
  return (indicatorDialog);
}

Please notice the fact that the app bar is disabled explicitly. The popup does not ‘block’ the app bar.

Cleanup

When the long running operation has finished, some cleanup is required.

// Implemented by MainPage
private void CleanUpLongRunningOperation
  (
  BusyIndicatingDialog indicatorDialog
  )
{
  // Operation has finished => deregister the event handler 
  // so the garbage collector can release the dialog
  ItemProcessed 
    -= indicatorDialog.ViewModel.OnItemProcessed;

  // close the dialog
  indicatorDialog.Close();

  // Enable the app bar
  BottomAppBar.IsEnabled = true;
}

Additional Considerations

I consider this implementation to be useful in cases where many items (or tasks) should be processed sequentially, while the processing of each single item does not take too long. Having one task that takes very long, no progress can be displayed and no cancelation is possible. If you have to cover such a scenario, I think you need to find another solution.

One thing really important is to give the UI thread a chance to update the dialog control and react on user input. To do so, you should add an await Task.Delay(1); between the processing of each item. Otherwise, in case the processing of the single item is really fast, the dialog might not be updated and(!) pressing the cancel button does not have any effect.

Consider Windows Store App Lifecycle

In the article “The Windows Store App Lifecycle“, Rachel Appel points out that “Windows 8 is changing how and when applications run”. In fact, it does!

Unlike desktop applications, Windows 8 suspends Windows Store apps (after a few seconds) when the user switches to another app. No matter what the app is currently doing. You cannot keep the app ‘alive’.

One should be aware of this. It means the user has to wait for long running operation to complete, and should not switch to another app meanwhile. This is kind of ‘blocking’ the device. Keeping this in mind, one should think twice before using Windows Store apps to execute long running operations, e.g. copy gigabytes of data.

Yes, there are background tasks available. But you cannot trigger them from within your app. So the usage is limited.

The Sample

can be found here.

Main screen

Processing

Links

Forum question Modal popup

Simple and Generic ICommand Implementation for Usage in XAML

The Windows Store App Lifecycle

Background Tasks

Forum question ‘Trigger background task manually