Posts

One of the more frustrating things for me is not being able to debug a problem. After updating my UWP app’s Target SDK to 18362 (Windows 10 1903), I was no longer able to compile. I got a very vague error. that I had to dig out of the msbuild logs:

Child node "2" exited prematurely. Shutting down.

So I dug into the msbuild logs and found the original error message

Unhandled Exception: System.AccessViolationException: Attempted to read or write protected memory. This is often an indication that other memory is corrupt.
at Microsoft.Windows.UI.Xaml.Build.Tasks.NativeMethodsHelper.Write(…)
at Microsoft.Xaml.XBF.XbfGenerator.GenerateXbfFromStreams(…)

After several hours try trying different things to isolate what was causing the issue, I reached out to the engineering team at Microsoft. They took over and dug deeper, which actually required the WDG group to investigate (big shout out to Alan!).

The problem stems from using a property of a custom base class in XAML. For example, if you have a custom control, for example a Telerik control. You need to have the base class listed in the xmlns of the XAML, even if you aren’t explicitly using it.

To make this simple, let’s use an example. This is the specific scenario that caused my error, but it can happen with any custom control. Look at the code sample below. As you can see on Line 5 the xml namespace is defined as input, and it is used on Line 10 for the RadRangeSlider.

Notice the Minimum and Maximum properties, those are actually defined in a base class, not in the RadRangeSlider class… this is what causes the exception in the latest SDK.

This will be fixed in a future UWP SDK release, but for now the workaround is to define the xmlns of the base class, even though you’re not explicitly using it. Here’s the fixed version of that code, notice Line 6.

In this tutorial, I’ll show you how to draw your own pie chart just using lines and a list of data items. The code itself is in C#, but the concept can be used on any platform that has a drawing library and ArcSegments.

Setting Up

The first thing you’ll need to understand is how the platform’s drawing library makes arcs. In this code, I’ll be using RadPath from Telerik UI for Xamarin most libraries work the same way. RadPath lets you use a custom Geometry which has RadArcSegmentobject, which has helpful StartAngle and SweepAngle properties.

Let’s start with the data model, with simple Title and Value properties:

Part 1 – Creating the Slices

Now that we have some items, lets move on to generating and drawing the slices. First, we’ll create a container to put the pie and legend into. A Grid is convenient option because we can have two rows, one for the pie and one for the legend.

Now we can start calulating the slice sizes, to do this, we need a total value to get a percentage of that total. We also need a variable to hold the current position on the 360 degree arc where the slices are rendered.

// Sum up all the values to be displayed
var totalValue = dataPoints.Sum(d => d.Value);
// Variable to keep track of where each slice ended.
double currentPosition = 0;

Now for the guts of the operation. We need iterate over the data points and create the arc segments using the data point’s Value property. The code comments will guide you through what each line does, in a nustshell here’s the lifecycle

Calculate the data item’s percentage of the total sum

Use that percentage to get what percent of 360 degree pie that slice needs

Create the RadArcSegment using the current position for the StartAngle and the angle percentage as the SweepAngle

Construct the RadPath using the ArgSegment’s geometry and a color from the colors list

At this point, you now have a full 360 degree chart, with colored slices for each of the data points representing their percentage of the whole.

Part 2 – Creating the Legend

The next phase of the operation is to create the legend. This needs to create text for each slice, as well as a marker that matches the same color of that slice. This could have been done in the same loop as creating the slice, but having a separate loop lets you decide to use a legend or not.

Again, we iterate over the data points. This time we use the Title property of the data point to create the text. To match the color, we use the same modulus to get index and assign it to a RadBorder that creates a thick bar underneath the text.

The last thing to do is add the entire container to the UI. In this example, I’m just setting the entire page’s content to the container Grid..

this.Content = container;

Wrapping Up

I hope this is useful for those times when you need ultimate control over rendering of a chart. If you need more complex setup, I recommend the RadPieChart itself, which is far more feature complete than drawing a few arcs 🙂

There are many scenarios where a UI component might not have a Command or bindable property available for certain features that you need to access from the view model. There is a simple, but powerful, thing you can do to allow this and not break MVVM or testing capability, leverage the Interface.

Scenario

Let’s imagine the scenario where we have a special ListView control that has a HighlightItem method that can only be called with a direct reference to that control. There isn’t a Command or DependencyProperty (aka BindableProperty in Xamarin.Forms) alternative, so it has to be done in the code behind.

I have an open source UWP project that relies on the Ad SDK and Engagement SDK to be installed to Visual Studio. This normally isn’t a problem, because you can just run the MSI on your PC (see installation instructions here and here).

I decided to move the project into DevOps so that I get some of that CI/CD goodness to build and publish new releases automatically to the Microsoft Store. However, there was a problem, when trying to build the project in a DevOps build pipeline, you’ll get the following error:

This means that the Hosted VS2017 Agent that DevOps uses to build a UWP project doesn’t have the Extensions SDKs installed. I have two choices to move forward:

Use a private Agent (this uses your local PC to build the project via a server connection )

Find a way to install the SDK into the Hosted agent

I did try the first option. I set up the Windows Agent on my Surface Book, connected it to DevOps and it works nicely (this is why you see that early successful build early in the first screenshot above). However, it’s not a solution for me because it means my PC has to be always on and network-connected.

My friend, and MVP peer, Oren Novotny mentioned that you can actually use a PowerShell script to download the MSI file and install it to the Hosted VS2017, this was the break I was looking for!

To implement this, I downloaded the MSI files I needed from the Visual Studio Marketplace and put them into an Azure Blob. It provides me with two reliable URLs to download the files in the PowerShell script.

Next, I wrote the very simple script. It has two phases: a download phase and an install phase (with a quiet switch “/q”). Here’s what that looks like:

Next, you need to add a Powershell step to your DevOps Build pipeline and paste in the script. Here’s a screenshot to help guide you:

Now, when the build is triggered, it will download and install the missing SDKs before building the project! Here’s the result of that build step in the Hosted agent’s console:

I hope this post finds you as soon as you need help. It took me several days, a dozen different documentation articles (some are hyperlinked above) and my MVP peers to find a good simple solution that didn’t require my PC .

Almost every developer I speak with agrees that getting a nicely working OAuth flow can be difficult. After much trial and error, I’ve built a UWP ContentDialog that makes this easy and has built-in refresh token support.

Using the LoginDialog

This is very simple to use, when the app launches, instantiate the dialog by passing your Live SDK ClientID and let the LoginDialog do the heavy lifting:

// Pass your app's OAuth ClientId (sometimes called an AppId)
var loginDialog = new LoginDialog("YourAppClientId");
// *** Perform login **** //
// Case 1 - If the user was previously signed in, there is a refresh_token stored and no user-entered credentials are needed.
// Case 2 - If the access token fails, or if it's the first sign-in, the user will see a popup to enter credentials.
await loginDialog.SignInAsync();
if(!string.IsNullOrEmpty(loginDialog.Authentication))
{
// This will be the access token you can use for API calls.
var accessToken = loginDialog.Authentication;
// Make your API calls with the accessToken, for example:
var user = await apiService.GetUSerProfileAsync(accessToken);
}

This works just like a MessageDialog, but instead will show a WebView for the user to sign in, or automatically sign them in silently if they were previously logged in.

Operational Summary

Explaining OAuth 2.0 is outside the scope of this article, but to summarize there are a couple round trip to the authentication endpoints.

Load the sign-in landing page and the user signs in with their credentials.

In the redirect after successful sign-in, you’ll get an access_token and a refresh_token for that authenticated user.

The access_token is what is used in all of your API calls that verifies the application is operating on the behalf of that user. The access_token expires after a preset amount of time (e.g. 60 minutes), after which time you have to request another access_token.

Here is where the refresh_token comes in handy. You could go back to step #1 above, but this would require the user re-enter their credentials. Instead, you can just use the refresh_token you already have for the user to get a new access_token without ever interrupting them to show a WebView.

This is what the LoginDialog does for you, when you call SignInAsync() the following happens:

Checks to see if there is a refresh_token stored locally. If there isn’t one, show the WebView and have the user sign in for the first time.

If there is a refresh_token stored locally, then use that to automatically get a new access_token without showing the dialog

Since this is general OAuth 2.0 workflow, you could probably adapt the dialog to work for other OAuth 2 endpoints by changing the dialog’s _signInUri, _signOutUri and _redirectUrl values.

Wrapping Up

The LoginDialog lets you have the least amount of interruption to the user while quickly getting an access token for your API use.

My friends at Microsoft have put together an amazing compilation of resources of all the new stuff available in the Windows 10 October 2018 Update (aka RS5). Below is a list of some of those resources relevant to developers and enthusiasts, enjoy!

Photo Editor C++/WinRT Sample has been updated to build with the RS5 SDK and to use the new single_threaded_observable_vector function to create an IObservableVector for data binding. An additional performance update will be coming out in a couple weeks.

Data binding and MVVM is a new topic that was identified as a need based on the Code First program. The topic describes the benefits of using the MVVM design pattern and how it has been applied to the sample apps.

This post will walk you through setting up a Xamarin Platform Effect and show you how to wire up an event handler so you can leverage native APIs in the case that the Xamarin.Forms wrapper doesn’t yet have. For this example, I’ll use the Telerik UI for Xamarin RadCalendar.

I get frequently asked how to enable RangeSelection (aka Multiple Selection) for the RadCalendar. The native platform calendar controls all have Range Selection available, so we only need to create a Platform Effect to access that native feature.

Note: If you’re not familiar with Effects, I recommend visiting this article first to understand the fundamentals (it’s a quick tutorial).

Class Library

Now we can move on to the Effect definition that lives in the class library project. The class defines the rest of items I listed above, I’ve called out how the event is invoked, thus subscribers to the vent will have their event handlers executed.

But we can’t run it just yet. It’s time to implement the native Effect classes., it’s where the magic happens. I’ll go through each platform separately instead of hitting you over the head with it all at once.

UWP

The next thing to consider is how to actually set the date range. This is done using the SelectedDateRange property to an instance of CalendarDateRange. This is what we needed the event for! You’ll see that when the Effect is Attached to the control

And that’s it! All three platform’s Calendar control now will show range selection.

Disclaimer

This isn’t production-ready code, it’s proof of concept and there are no defensive techniques in place (i.e. try/catch). I wanted to keep it as simple as possible to focus on the concepts.

If you want to use the code for your app, I’m happy I could help (MIT license). Just please don’t copy-paste it all and call it a day, then ping me on Twitter later and say “it’s broken!”. The native platform logic should be inside try catch blocks and I would make sure the DateTime conversions are accurate for your needs.

These Playlists will continue to be reordered and updated in real time as new content becomes available. However, the links will always remain the same and you can refresh the playlist page to get any updated ordering/content.

If you’re a Xamarin Forms developer, you’ve likely used PCLStorage (or other Dependency Service) to interact with the target platform’s file system in the portable class library’s code. However, since November 2017, Xamarin.Forms now uses a .NET Standard 2.0 class library and PCLStorage is no longer supported.