DevCenter Promo Codes Not Working?

One of the great things about the new DevCenter is the ability to generate Promotional codes for your in-app-purchase products, so I generated 100 codes last night for the launch of Windows 10.

I gave out many codes today but I started getting “the promo code didn’t work” emails. After a quick investigation I found that the LicenseInformation for the user wasn’t refreshed automatically or even after the user restarted their phone. I suspect that this is just temporary, but I found a workaround…

The trick is to have the user go through the process to purchase the IAP product. The user’s phone will do a license verify check with the Store server and show this screen:

Already Owned

 

Normally, if they did not own the product there would be a payment method and a “buy” button. However, since they redeemed your code, the button will be labeled “install” as seen in this screenshot:

2015-07-29_1516

Just tell your user to click “Install” and go on experiencing your awesome app!

If you have any questions, feel free to leave a comment below or ping me on twitter

Lance

 

Error : DEP3321 – Can’t deploy to Windows 10 Mobile

With Windows 10 being rolled out as I write this article, there will be updated sample Windows Platform apps available soon (today). It’s also time to update your projects.

However, you may find yourself not able to deploy to Windows 10 Mobile after updating your projects or older samples to Windows 10 (build 10240). This post will show you how to resolve this problem.

The Problem

You’ll see an error something like this when deploying to a physical Windows 10 Mobile device:

Error : DEP3321 : To deploy this application, your deployment target should be running Windows Universal Runtime version 10.0.10240.0 or higher. You currently are running version 10.0.10166.0. Please update your OS, or change your deployment target to a device with the appropriate version.

The error is pretty clear but how do we fix it? The resolution is with the MinTargetVersion setting.

The Fix

We need to drop the lowest version your app targets to the version that your device has running, we can do this in one of two ways; through the project properties UI editor or manually edit the XML of the csproj file. I will show you how to do it manually because in some cases, the UI’s MinTarget dropdown list won’t show the lowest SDK if you do not have it installed. Below are the steps to fix it.

NOTE: Skip to step 3 if your project is already unloaded (it will show (unavailable) next to the name)

1) Right click on your project in Visual Studio

2) Select “Unload Project“, it will now appears as ProjectName (unavailable)

3) Right click on the unloaded project and select “Edit projectName.csproj

4) Locate the <TargetPlatformVersion> and <TargetPlatformMinVersion> items in the first <PropertyGroup>.

Here’s the “Before” screenshot:

2015-07-28_1734

5) Change the TargetPlatformMinVersion to the version that the error stated you are running. In this case, it’s 10166. Here’s the “After” screenshot:

After

6) Now Save and Close the file

7) Right click on the project again and select “Reload Project

8) Rebuild the project and deploy to device. Now you should be up and running!

Summary

I expect this to happen with increasing frequency as we move forward with Windows 10 SDK releases. The new paradigm is that we’ll have a set of installed windows 10 Tools, but multiple SDK versions. We need to be aware of the min version and targeted version of our apps.

If you have any questions, feel free to leave a comment below.

One XAML for UWP, Windows 8.1 and Windows Phone 8.1

I was recently involved in a conversation on how to have the easiest way to maintain a XAML view across a UWP (Universal Windows Project) a Windows 8.1 and Windows Phone 8.1 projects. There are a few options and the most straight forward way to do it with a UserControl residing in a Portable Class Library. However…

What if you wanted to have tailored code for each without littering your code with #ifdef but still share a XAML view?  The XAML View might be what you’re looking for. This is a tutorial on how to do just that. An example project is available for download at the end of the article. Let’s get started:

Step 1:

Create a new 8.1 Universal app

tpx1

Step 2:

Move the Shared, Windows and Windows Phone projects out of the virtual folder and delete the folder (you can cut/paste or just click and drag them). The solution should look like this now

tpx2

(Note: If you’re doing this to a solution that has many other projects, you might want to skip this step and add the UWP project to the virtual folder instead)

Step 3:

Add a new UWP project to the solution and name it the same as the 8.1 app, but with the Universal suffix.

tpx3

(Your solution should look like this now)

tpx4

Step 4:

Add a “Views” folder to each of the projects

tpx5

Step 5:

Within the Universal project, right click and Add > New Item > XAML View

tpx6

Step 6:

Move the new XAML View to the Shared project’s Views folder and change the namespaces in the view to match

tpx7

Step 7:

Delete App.xaml from the Universal project and add a reference to the solution’s Shared project (Note: this is in the new Shared projects references section)

tpx8

Step 8:

Here’s where the magic happens. We’ll be adding a code behind for this view in each of the projects! I’ll break this down into sub-steps:

  1. Add a new class to the Windows 8.1 project’s Views folder (Add > New Item), name it as if it were the code-behind for the view. In this case it would be SharedPage.xaml.cs
  2. Change the namespace of the class to Views
  3. Add the public, sealed and partial modifiers to the class
  4. You’ll next need to inherit from the Page class
  5. Add a page constructor
  6. Now you can copy and paste this new class into each of the platform projects (remember, we do not need it in the Shared project)

This is what it should look like

tpx9

Step 9:

You’ll need to quickly pop into the Build Configuration Manager and check off Build and Deploy for the Universal app (you can find Configuration Manager in the target dropdown or in the Build menu)

tpx10

Step 10:

Lastly, for the purposes of this demo, go to App.xaml.cs and change the initial launch target (MainPage) to be the new shared page (SharedPage). I could have put a button on MainPage for each app, but let’s keep this tutorial as short as possible.

tpx11

Final result!

This is the same XAML View compiled with different code-behind files 🙂

tpx12

(NOTE: I put a TextBlock on the SharedPage and update the text in each constructor to show which platform launched it. Here are the WP8.1 emulator, Windows 10 PC and Windows 10 Mobile Emulator running their apps all showing the same XAML view).

Source Code

Download the Sample App Source Code From Here

Bonus:

The Telerik Universal Control can be used in the shared page as long as each of the projects have a reference to the Telerik UYI for Windows Universal DLLs. Send me a tweet and show me what you’ve done, I’ll RT your awesomeness!

Custom Pivot Header with Animation

I recently wanted to make a header with tabs for my app’s pages that have a Pivot. Something like Office Mobile, but without the drop-down menus. Here’s the result I got in my upcoming app. I decided to post a tutorial and provide a sample app.

CustomPivotHeader

 

Notice the fast fade-in of the background color of the tab, this is important and is where you’ll be able to add your own flavor to the style after you’ve completed this tutorial. Ok, let’s get started!

Step One: Create the base elements

The two main components are a Pivot control and a ListView control. The Pivot has been stripped of it’s title template and pivot header templates. To get started, let’s do a File > New Pivot App (WinRT, not Silverlight) so that we’ll have some sample data and a pre-existing Pivot.

StepOne1

After the project template finishes, open PivotPage.XAML and add RequestedTheme=”Light” to the page’s properties. Next, find the root grid of the page. Add a couple RowDefinitions, with the first row’s height set to auto. Add a Grid containing a ListView to Row 0 and put the Pivot into Row 1.

StepOne2

Now, let’s clean up the pivot. Delete the Pivot’s Title and both the PivotItem’s Header properties. You should be left with only the pivot item’s contents, this is what your page should look like at this point.

StepOne3

Step Two: Create a Control for the Tabs

My demo uses text, however there are other approaches that can use an icon or other element in the tab. Since not all XAML elements have a “Foreground” property that can automatically inherit from the parent ListView’s foreground, we’ll use a  container control to hold the TextBlock. Make this by right clicking on your project and select Add > New Item. Then find Templated Control and give it the name HeaderTab.cs.

StepTwo1

A template control has a backing style where the UI is defined while the control’s logic is in the file named after it. Visual Studio will add a folder named Themes and a ResourceDictionary Generic.xaml.

StepTwo2

First, Open HeaderTab.cs and change the base class from Control to ContentControl. This will allow you to use the control as a ContentControl, which is what the ListViewItem’s template uses.

StepTwo4

Next, open Generic.xaml, ignore the errors for now, they will go away when you do a Build at the end of this step. First, replace the Border control in the style with a TextBlock. Now, use TemplateBindings for the Text and Margin properties (see screenshot). This is how we pass the properties values of the ListView ItemContainerStyle to our custom control when the property types to match. The Margin property is a perfect example, we use the padding of the container style for the margin of the TextBlock, this will make more sense towards the end of the tutorial. Okay, now it’s time to do a Build (F6) so that your style’s TargetType will resolve.

This is what your Style should look like:

StepTwo3

Step Three: Create a horizontal ItemsPanel

In order to tell the ListView to render the items horizontally, we need an ItemsPanel, however since we want the content of the tab to be in the center but also stretch to fill the available space, we can’t use a simple StackPanel. So, let’s make our own. Right click on your project and select Add > New > Class and name it HorizontalStretchPanel.

StepThree1

Explaining the process of calculating the available space and arranging the items is outside the scope of this article, but in a nutshell, we take the full width and divide it by the number of items then arrange to get the most space for each item. Here’s the code to copy/paste:


public class HorizontalStretchPanel : Panel
{
protected override Size ArrangeOverride(Size finalSize)
{
var rect = new Rect(0, 0, finalSize.Width, finalSize.Height);
var width = finalSize.Width / Children.Count;

foreach(var tab in Children)
{
rect.Width = width;
rect.Height = tab.DesiredSize.Height > finalSize.Height ? tab.DesiredSize.Height : finalSize.Height;
tab.Arrange(rect);
rect.X = width + rect.X;
}

return finalSize;
}

protected override Size MeasureOverride(Size availableSize)
{
if(Children.Count == 0)
return base.MeasureOverride(availableSize);

var finalSize = new Size { Width = availableSize.Width };
availableSize.Width = availableSize.Width / Children.Count;

foreach(var tab in Children)
{
tab.Measure(availableSize);
var desiredSize = tab.DesiredSize;
finalSize.Height = desiredSize.Height > finalSize.Height ? desiredSize.Height : finalSize.Height;
}

if(double.IsPositiveInfinity(finalSize.Height) || double.IsPositiveInfinity(finalSize.Width))
return Size.Empty;

return finalSize;
}
}

 

Step Four: Create a ListView Configuration and ItemContainerStyle

Now it’s time to go back to the ListView we added to the top of PivotPage.xaml . Before working on the ListView, Give the parent Grid a height of 50 and a good background that will contrast with white, I went with Blue. Now, onto the ListView. Let’s set the ListView.ItemsPanel to use our new HorizontalStretchPanel. Next, add some ListViewItems containing your new HeaderTab control. You’ll want one ListViewItem for each PivotItem you have. While you’re there, set the FontSize of your HeaderTab to 20.

Now, bind the SelectedIndex of the ListView to the SelectedIndex of the Pivot using an ElementName binding and set VerticalAlignment to bottom.

Here’s what it should look like thus far

StepFour1

Now, it’s time to add some style and animation to the ListViewItemContainer. To begin, extract the ListView’s default ItemContainerStyle, this screenshot shows how:

StepFour2

Give a name, I chose HeaderListViewItemContainerStyle, once you click Ok, the ListView will get a StaticResource reference to the style in the page’s Resources. Scroll up to the top of the page and expand the style. Yeah, it’s pretty long. the part I want you to get to is the Template property. Within here you’ll see some animations, but go past them until you see the ContentControl. This is what shows your HeaderTab control, I like to give my template parts names with strong prefixes, you don’t have to, but it’s easier for identification when it comes to animation.

Now, let’s edit that template to add an extra Grid so we can act on it to get some cool fading animation when the user changes tabs. What we’re going to do is put the new Grid behind the ContentControl so that we don’t block the Text. To make this easier, here is what the XAML looks like after renaming the parts and adding the Grid.

StepFour3

Lastly, I went with White for the Style’s foreground property, this gets inherited by the TextBlock in your HeaderTab control. It will contrast well against the Blue background of the page header Grid.

Step Five: Animating the Container’s Parts

This is something that you’ll want to play with and where Blend can help you get the exact results you’re looking for. What we’re going to do is add some keyframes to the existing States: UnselectedSelected and SelectedFocused. Here’s where the string naming of the template parts comes in handy. First, in the Unselected state we want to style it they way we want it to look when the tab is not in focus. In this state I want my new Grid to have zero height. Here’s what that looks like:

StepFive1

Now let’s go to the Selected and SelectedFocused states (they’re the same in my scenario). In this state I want the new Grid to be the full height of the tab and more importantly to have a white background.

StepFive2

Lastly, the sugar that adds the magic… the transition animation. The cool thing about states is that you don’t have to write long storyboards, just set a Default Transition for a particular state. You can add these right to the VisualStageGroups directly (don’t forget to add some Easing). Here’s what it looks like

StepFive3

 

Almost done! Go through the Pivot and PivotItems and delete all the x:UID properties, these will change your UI at runtime because of localization, best to get them out of the way now. Whew! now it’s time to fire up the emulator and take it for a spin. This is what you should be seeing, if not, download the sample app from here and see what went wrong.

Happy coding!

FinalDemoResult

 

Page Transitions for Universal XAML Pages

Normally, if you want different page transitions (NavigationThemeTransition) for your Universal XAML Windows Phone 8.1 app, you’d set it on the page’s XAML directly. For example, let’s do a ContinuumTransition:


<Page.Transitions>
<TransitionCollection>
<NavigationThemeTransition>
<NavigationThemeTransition.DefaultNavigationTransitionInfo>
<ContinuumNavigationTransitionInfo />
</NavigationThemeTransition.DefaultNavigationTransitionInfo>
</NavigationThemeTransition>
</TransitionCollection>
</Page.Transitions>

However, if you have a XAML page in your Universal app’s shared folder, you can’t use XAML because page transitions are not available for Windows 8.1 apps. Since there isn’t a conditional compilation for XAML, we’ll need to do it from the code behind.

In your OnNavigatedTo event, set up an #ifdef statement to check if the page is being used on PC or phone. Now with the ability to run platform specific code, we can programmatically add the transition to the Page. Here is the result:


#if WINDOWS_PHONE_APP
//phone code

this.Transitions = new TransitionCollection
{
new NavigationThemeTransition
{
DefaultNavigationTransitionInfo = new ContinuumNavigationTransitionInfo()
}
};
#else
//PC code

#endif

Now you can have the same transition effect you use for the rest of the phone app’s pages, enjoy!

WinRT MediaCapture Tips

As we approach Windows 10, many of you are considering updating your SL 8.0 apps to WinRT. In fact, Larry Lieberman and team recommend you do this and have shared some resources to help facilitate the move. I’ve done this for a couple apps so far and wanted to share some of my experience while migrating Silverlight AudioVideoCaptureDevice API to WinRT MediaCapture, because you’ll need to rewrite your approach.

The WinRT documentation helps with a lot of stuff, but there are holes that I had to discover for myself. To help ease the process, I’m sharing some of the solutions that I’ve discovered, uncovered and smash-my-head-on-the-desk about. Let’s get started:

MediaCapture class

This is your home base of media capture operations. Since it is a better description of what the class does, you’ll see name “mediaCaptureManager” used often. You’ll see it used throughout my code below (before starting, see the “gotchas” Suspension section).

Enumerating Devices (i.e. get front camera)

To get the current video devices attached to the device, first you need to enumerate over the phone/pc’s available video devices using the DeviceClass enum. The user’s device might be a desktop PC with a webcam, it could be a Surface Pro or a Lumia 520, you need to consider the possibilities and be prepared for them.

mediaCaptureManager = new MediaCapture(); //class scope
var devices = await DeviceInformation.FindAllAsync(DeviceClass.VideoCapture);

So instead of the old way of looking for the camera by name { i.e. if(deviceName.Contains(“front”) || deviceName.Contains(“ffc”)) }, you can now use the EnclosureLocation enum. I like to hold the results in a class-wide DeviceInformation object, one for the front cam and one for the rear (rear is also my default to catch webcams and the like), this lets me quickly switch later without having to reiterate over the list. Once you have your chosen camera, use it to initialize the MediaCapture object. You could use a switch statement like this:

foreach (var device in devices)
{
    switch(device.EnclosureLocation.Panel)
    {
    case Windows.Devices.Enumeration.Panel.Front:
        frontCamera = device; //frontCamera is of type DeviceInformation
        isUsingFrontCam = true;
        break;
    case Windows.Devices.Enumeration.Panel.Back:
        rearCamera = device; //rearCamera is of type DeviceInformation
        break;
    default:
        //you can also check for Top, Left, right and Bottom
        break;
    }
}

await mediaCaptureManager.InitializeAsync(new MediaCaptureInitializationSettings { VideoDeviceId = frontCamera.Id });

You have many MediaCaptureInitialization parameters available, but you only need the Id to start the camera. WARNING: If the device is using an attached WebCam (i.e. USB camera), EnclosurePanel will be null. Check for a valid device.Name.

MediaCapture Properties and Showing Preview

Next you want to consider the sensor rotation of the camera. If it is the front camera, you need to rotate it 270 degrees. This used to be a HUGE problem where you had to apply a transform to the UI control that is using the VideoBrush and again on the playback page. Since this only worked on the device, if you viewed the file on another device, it would still be rotated!!!

Thanks to WinRT’s VideoRotation enum, you can rotate the frames for both previewing and recording frames. This is also the time to hook into the following events: Failed (obvious) and RecordLimitationExceeded (save the video and let user know it got cut short).


if(!string.IsNullOrEmpty(mediaCaptureManager.MediaCaptureSettings.VideoDeviceId) &amp;amp;amp;&amp;amp;amp; !string.IsNullOrEmpty(mediaCaptureManager.MediaCaptureSettings.AudioDeviceId))
{
   //rotate the video feed according to the sensor
    mediaCaptureManager.SetPreviewRotation(VideoRotation.Clockwise270Degrees);
    mediaCaptureManager.SetRecordRotation(VideoRotation.Clockwise270Degrees);

    //hook into MediaCapture events
    mediaCaptureManager.RecordLimitationExceeded += RecordLimitationExceeded;
    mediaCaptureManager.Failed += Failed;

    //device initialized successfully
    }
    else
    {
    //no cam found
    }
}

Now that you have the device initialized and any advanced properties set, it’s time to push frames to the UI. Here is the most straightforward way:


VideoCaptureElement.Source = mediaCaptureManager;
await mediaCaptureManager.StartPreviewAsync();

//video frames are being pushed to the CaptureElement (instantiated in XAML)

Switching Cameras and Sensor rotation

Now that CaptureElement is showing the video preview, let’s say you want to change cameras. You have to consider two main considerations: stopping current preview and setting up the next device. Here is how I do it (note that I am using Portrait orientation for this page)


private async Task SwitchCameras()
{
   await mediaCaptureManager.StopPreviewAsync();
   mediaCaptureManager.Dispose();
   mediaCaptureManager = null;
   mediaCaptureManager = new MediaCapture();

   if (isUsingFrontCam)
   {
      await mediaCaptureManager.InitializeAsync(new MediaCaptureInitializationSettings { VideoDeviceId = rearCamera.Id });

      mediaCaptureManager.SetRecordRotation(VideoRotation.Clockwise90Degrees);
      mediaCaptureManager.SetPreviewRotation(VideoRotation.Clockwise90Degrees);
   }
   else
   {
      await mediaCaptureManager.InitializeAsync(new MediaCaptureInitializationSettings { VideoDeviceId = frontCamera.Id });

      mediaCaptureManager.SetRecordRotation(VideoRotation.Clockwise270Degrees);
      mediaCaptureManager.SetPreviewRotation(VideoRotation.Clockwise270Degrees);
   }

   isUsingFrontCam = !isUsingFrontCam;

   PreviewMediaElement.Source = mediaCaptureManager;
   await mediaCaptureManager.StartPreviewAsync();
}

Disabling Screen Timeout

One thing you might not realize until you’ve gotten user feedback is the screen timeout. You do not want the user’s device to lock on them while they’re recording (or playing) media. This is accomplished with a DisplayRequest. One word of caution, make sure you are releasing the request when done or other unexpected app close. There have been reports (unconfirmed, but worth consideration) that this API is causing problems with the power button on user’s phones.

Here is how I do it:


//on the class level
private DisplayRequest dRequest;

//in your OnNavigatedTo event
if (dRequest == null)
{
   //disables timeout
   dRequest = new DisplayRequest();
   dRequest.RequestActive();
}

//IMPORTANT! In your OnNavigatedFrom (or other last opportunity)
if (dRequest != null)
{
   dRequest.RequestRelease();
   dRequest = null;
})

Available Resolutions and Frame Rates

A full explanation is outside the scope of this article, however a high overview will help. Essentially, every video capture device reports it’s available resolutions (via firmware) to the OS. Here is a snippet from my app where I get all the available resolutions for the user’s cameras. This is so the user can select a preferred option, this is especially helpful for me because lower memory phones don’t have the horse power to process all the MFT frames (video effects). A lower frame rate allows me to provide a better end user experience for those users.

In this sample, I iterate over the options, save a pointer to each in my ViewModel via a custom object and use it later for when the user selects an option.


var mediaCaptureManager = new MediaCapture();
var devices = await DeviceInformation.FindAllAsync(DeviceClass.VideoCapture);

//GET CAMERAS HERE- same approach to get cameras as at the beginning of this article

if(rearCamera != null)
{ 
   await mediaCaptureManager.InitializeAsync(new MediaCaptureInitializationSettings { VideoDeviceId = rearCamera.Id });
   var mediaEncodingPropertiesList = mediaCaptureManager.VideoDeviceController.GetAvailableMediaStreamProperties(MediaStreamType.VideoPreview);

   if(AvailableResolutions.Count &amp;amp;gt; 0) AvailableResolutions.Clear();

   if (mediaEncodingPropertiesList.Count &amp;amp;gt;= 1)
   {
       foreach (var mediaEncodingProperties in mediaEncodingPropertiesList)
       {
         //I store list in custom collection and let user pick preferred item
         AvailableResolutions.Add(await CreateUserResolutionPropertyAsync((VideoEncodingProperties)mediaEncodingProperties));
       }
    }
}

//if front camera available
if(hasFrontCamera)
 {
    mediaCaptureManager.Dispose();
    mediaCaptureManager = null;
    mediaCaptureManager = new MediaCapture();

    if(AvailableFrontResolutions.Count &amp;amp;gt; 0) AvailableFrontResolutions.Clear();

    await mediaCaptureManager.InitializeAsync(new MediaCaptureInitializationSettings { VideoDeviceId = frontCamera.Id });

    var frontPropertiesList = mediaCaptureManager.VideoDeviceController.GetAvailableMediaStreamProperties(MediaStreamType.VideoPreview);

    if(frontPropertiesList.Count &amp;amp;gt;= 1)
    {
       foreach(var mediaEncodingProperties in frontPropertiesList)
       {
         AvailableFrontResolutions.Add(await CreateUserResolutionPropertyAsync((VideoEncodingProperties)mediaEncodingProperties));
       }
    }
}

I store the user’s selected preference and use it when setting up the camera. If you’re doing this and get stuck, shoot me an email and I’ll share my approach with you.

Gotchas

Thumbnail

For some reason, when saving an .mp4 file created by the MediaCapture API, the file has a 0 length thumbnail. So, if you try to use GetThumbnailAsync on the saved file is a no-go. To workaround this on Phone, I use the Windows Phone MediaComposition API to create the final file that contains a valid thumbnail.

For Windows 8.1, I use the MediaCapture API itself to take a photo at the beginning of the video. I have reported this to the proper people, hopefully it will be fixed in Windows 10.

Suspension

In order to properly handle suspension, it is recommended that you have a handle in App.xaml.cs for the MediaCapture object. This will let you manage it’s state properly when Resuming. For example, after newing-up, in the view do this:


MediaCapture mediaCaptureManager = new MediaCapture();

(App.Current as App).MediaCapture = mediaCaptureManager;

Conclusion

There are a lot of cool things you can do with the new MediaCapture API, the approach above is just my first attempt. I’m sure I’ll continue tweaking it to get the best performance. The lesson learned? It was completely worth the effort to migrate to WinRT.

To see what I’ve done so far, check out my app Video Diary (WP 8.1 or above) http://bit.ly/video-diary ( try the real-time effects, editing and next update will include user settable resolutions and framerates )

Report progress – IAsyncActionWithProgress

One of the best things you can do for your app’s users is to report the progress of an operation. Showing a progress bar can greatly increase the patience of the user, not knowing how long something is going to take can make the operation just feel longer.

Luckily, many WinRT Tasks will return an IAsyncActionWithProgress. I’ve seen many blog posts about this topic, but most are deeply involved and weren’t suited for a quick lookup. This post will show you a quick example, which you can apply in your app..

A quick summary is that you have two main options with one of these actions; await the action result directly or don’t await and hook into the Progress event and Completed event. As an example, I will use the MediaComposition class available for Windows Phone 8.1.

If you wanted to save the composition but still want to catch render failure, you’d do something like this:


var transcodeFailureReason = await mediaComposition.RenderToFileAsync(storageFile);

if(transcodeFailureReason == TranscodeFailureReason.None)
{
//success!
}

However, the rendering could take a long time, it’s better to show the user the progress of the operation. RenderToFileAsync will also give you an IAsyncActionWithProgress if you don’t use await. You’d hook in to the events I mentioned above. Here is what that looks like:


var result = mediaComposition.RenderToFileAsync(storageFile);
result.Progress += Progress;
result.Completed += Completed;

The progress event actually gives you the percentage completed of the operation in the second parameter. Just make sure you marshal back to the UI thread when updating the UI. Here is an example of using a TextBlock and ProgressBar to report progress.


private void Progress(IAsyncOperationWithProgress&lt;TranscodeFailureReason, double&gt; asyncInfo, double progressInfo)
{
Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =&gt;
{
ProgressTextBlock.Text = string.Format(&quot;{0}% complete&quot;, progressInfo);
ProgressBar.Value = progressInfo;
});
}

Finally, in the Completed event, make sure the rendering happened without error and move on. Note that you are still on a different thread, if you have a list of items in the ViewModel to update you need to marshal it as well.


private async void Completed(IAsyncOperationWithProgress&lt;TranscodeFailureReason, double&gt; asyncInfo, AsyncStatus asyncStatus)
{
if (asyncInfo.GetResults() != TranscodeFailureReason.None)
{
//operation failed
}

Dispatcher.RunAsync(CoreDispatcherPriority.Normal, async () =&gt;
{
await UpdateMyViewModelCollectionWithNewThing();
});
}

Showing the user progress adds professionalism to your app and makes the user’s experience much better.

Enjoy!