(X) Hide this
    • Login
    • Join
      • Generate New Image
        By clicking 'Register' you accept the terms of use .

Connecting Windows 8 applications with services: Part 6: Integrating the cloud through the Live SDK and roaming data

(1 votes)
Gill Cleeren
>
Gill Cleeren
Joined Apr 02, 2010
Articles:   48
Comments:   4
More Articles
0 comments   /   posted on Nov 05, 2012
Tags:   windows-8 , gill-cleeren
Categories:   Windows 8
Tweet

In the previous part of this series, we looked at working with public APIs such as Facebook. We learned that using the WebAuthenticationBroker class, authentication with these APIs is very simple. In this 6th part, we’ll start by looking at the Live SDK and the integration we can build around Live. The options offered by this SDK are interesting mainly because of the features it brings in terms of single sign-on capabilities we can easily add to an app.

Secondly, we’ll leverage the cloud some more for our apps when we look at roaming data. Through roaming data, we can synchronize settings between apps, giving the user an experience that’s far beyond what we can offer today.

Working with the Live SDK

Windows Live is more than what we think initially. While many relate it to the Live ID (now known as the Microsoft account by the way) and Hotmail (which is now replaced by Outlook.com), it offers a number of services that we can work with in our applications. These include of course Outlook, but also SkyDrive and Messenger. We’ll be using these later in this article. For developing apps, you’ll need to download the Live SDK, which is available for free from here.

The Live SDK offers us another great benefit: we can leverage the Live ID authentication within our applications. This way, we can easily build a single sign-on mechanism in Windows 8 Store Apps. The user is (in most cases) already logged on with a Live ID. If so, we can, using the Live SDK, get hold of the logged-in account in the system. This account (the Live ID) we can then use as a means to authenticate the user in our own server-side authentication mechanism. This is shown in the figure below.

Initially, using the Live SDK, the app gets access to the logged-in user (gill@test.com). This account is verified, we are sure, based on Live ID, that the user is who he/she claims to be. This value is now sent to the server-side, where it can optionally be matched to an account in the database/Active Directory. At no point did the user of the Windows Store app have to do a sign-in process.

For this to work, the user of course has to use a Live ID to sign in to his machine. Secondly, the machine must also be trusted. In the screenshot below, the above process wouldn’t work since the machine isn’t trusted yet.

Let’s now build an app that uses single sign-on capabilities.

Registering your app to use Live services

The very first step we need to do is registering the application with Microsoft so it is allowed to integrate with Live services. For this, a developer account is needed since Windows 8 was released (previously, this could be done for free). If you don’t have an account, you won’t be able to test the following steps.

Head over to your dashboard and register the app you want to build. In my case, I named the app SilverlightShowSDKTest.

Now go to Advanced Features.

In that page, click on “Push notifications and Live Connect services info”. Once there, you can configure Live Connect services as well as Push Notifications. You’ll get the values to manually update your application manifest file or you can continue from Visual Studio. In this sample, I’ll use the second option. In VS2012, right-click on the Project node in the Solution Explorer and select Store à Associate app with store.

In the wizard, select your app. Visual Studio will update your manifest accordingly.

We’re now ready to work on the app itself.

Single sign-on with Live ID

The next thing we need to do is bringing the Live SDK into our application (you should have it installed by now!). Add a reference to the Live SDK, which can be found under Windows à Extensions in the Add Reference Dialog.

An app like ours that integrates with the Live SDK needs to have a control, the Live SignInButton. This control allows the user to sign in (quite logical) but also will trigger the authentication automatically the next time the user runs the app.

On this control, we specify the scopes. A scope is basically a permission that the app requests from the user: it will allow the app to perform certain actions on different levels. A full list of permissions can be found here. Common scopes include wl.basic (allows reading the basic information of the user’s profile as well as contacts list access) and wl.signin (allows the signle sign-in behaviour to work within the app).

To add this control to our app, we can drag it from the Toolbox.

We can specify the scopes we require, in this case, we’ll use wl.basic and wl.signin. Additionally, we need to register for the SessionChanged event.

<Controls:SignInButton x:Name="MySignInButton" 
  Scopes="wl.signin wl.basic" SessionChanged="MySignInButton_SessionChanged_1" />

In the MySignInButton_SessionChanged_1, we need to write some code. Note that this code will trigger when the user clicks the Button the first time. Subsequent runs of the app (assuming the user has agreed with allowing the app to access his Live data) will trigger authentication automatically and therefore run this code automatically as well.

First, we’ll use a LiveConnectClient instance. This class exposes the most basic fuctionality of the Live Connect service endpoints such as getting the user information.

private LiveConnectClient liveConnectClient;

Next, we’ll check if we are connected. If so, we pass the created Session (for this authentication process) instance to the LiveConnectClient. Using a specific query syntax, we can access different objects. In this case, we simply specify that we want to access the user profile, accessible by using “me”.

if (e.Status == LiveConnectSessionStatus.Connected)
{
  liveConnectClient = new LiveConnectClient(e.Session);
  LiveOperationResult operationResult = await liveConnectClient.GetAsync("me");
  ...
}
else
{
  infoTextBlock.Text = "You are not signed in";
}

Things get a bit more dirty ahead, as we’ll need to go and use dynamic code. In the code below, we are getting the user first name and last name.

dynamic result = operationResult.Result;
if (result.first_name != null && result.last_name != null)
{
  infoTextBlock.Text = "Signed in as " + result.first_name + " " + result.last_name + "!";
}
else
{
  infoTextBlock.Text = "Signed in, but you don't have a name specified!";
}

When we now run the application, we initially see the following (remember that your app needs to be registered in the Store for this to work).

When we click on the Sign in button the first time, we are shown the following screen. This is a comparable behavior to what we got with the Web Authenication Broker which we discussed in the previous article. The overlay shows the permissions the app is requesting.

Once agreed, the app can access basic information, such as the firstname and lastname.

Storing information in the cloud: roaming application data

We’ve now seen how we can build applications that use a Live ID to log in. In Windows 8, it’s possible to leverage the cloud also when storing information for an application. This is possible using SkyDrive (which is accessible through the Live SDK as well) and by using roaming data.

Many built-in apps such as the Photos, News and People are storing information along with Windows itself in the cloud. This information is Settings-related in the first place. For example, Windows leverages this roaming of settings by synchronizing your IE browser history between devices. Of course, this information is again tight to the logged-in user, requiring that for this to work, the user is required to be logged-in using a Live ID.

By using roaming of settings and other info, the user experience will dramatically improve: the idea is configure once, use everywhere. That’s why Microsoft is suggesting that we as app developers leverage this functionality within our applications as well. This is possible by using roaming data, one of the 3 ways of interacting with the Application Data API (the 2 others are local and temporary).

Using roaming data results in the fact that app developers can very easily store information (limited to 100K per app per user) that will automatically synchronize between devices. Building this would require a lot of work as well as a lot of work to get this right. Roaming data within Windows 8 solves all this and abstracts it away for the developer, making it a very straightforward process to work with.

Roaming data, just like local data, can be used in 2 ways. Either we work with regular files. In that case, we need to create and manages physical files in a folder, the Roaming Folder. Otherwise, it’s also possible to work with Roaming Settings. In that case, we’re basically working with a dictionary (key-value pairs) which will be syncing over the cloud.

What would you then store in this roaming data block? As mentioned, settings should be stored there if they are useful to be synced to other devices. Documents are probably not a good candidate: they might be too large; in this case, SkyDrive might be a better solution.

Let’s take a look at a sample application where we are using roaming data. First, we’ll instantiate a reference to both the roaming settings and the roaming folder.

private Windows.Storage.ApplicationDataContainer roamingSettings = 
  Windows.Storage.ApplicationData.Current.RoamingSettings;
private Windows.Storage.StorageFolder roamingFolder = 
  Windows.Storage.ApplicationData.Current.RoamingFolder;

If we want to create a setting, we can do so as follows:

roamingSettings.Values["GillTestSetting"] = "Hello SilverlightShow";

If we want to retrieve this settings, the following code can be used:

if (roamingSettings.Values.ContainsKey("GillTestSetting"))
  testSetting = roamingSettings.Values["GillTestSetting"].ToString();

If we want to work with a composed value, we can do so using a Composite Value:

Windows.Storage.ApplicationDataCompositeValue composite = 
  new Windows.Storage.ApplicationDataCompositeValue();
composite["intVal"] = 1;
composite["strVal"] = "A nice string!";
roamingSettings.Values["GillTestCompositeSetting"] = composite;

It’s also possible to store settings in containers. A container can be seen as a folder to group the settings. In the following code, we are creating a container and then adding a value to it.

Windows.Storage.ApplicationDataContainer container =
roamingSettings.CreateContainer("GillTestContainer", 
  Windows.Storage.ApplicationDataCreateDisposition.Always);
if (roamingSettings.Containers.ContainsKey("GillTestContainer"))
{
  roamingSettings.Containers["GillTestContainer"].Values["GillContainerSetting"] = 
    "Hello SilverlightShow from a container";
}

As mentioned, we can work with files as well. These would then go in the RoamingFolder. From then on, it’s pretty simple IO code that needs to be written. In the following code, we are creating a roaming file.

Windows.Globalization.DateTimeFormatting.DateTimeFormatter formatter = 
  new Windows.Globalization.DateTimeFormatting.DateTimeFormatter("longtime");
StorageFile sampleFile = await roamingFolder.CreateFileAsync("dataFile.txt", 
  CreationCollisionOption.ReplaceExisting);
await FileIO.WriteTextAsync(sampleFile, formatter.Format(DateTime.Now));

When we want to read the file, we can use the following code.

try
{
  StorageFile sampleFile = await roamingFolder.GetFileAsync("dataFile.txt");
  String timestamp = await FileIO.ReadTextAsync(sampleFile);
  WaitingForDataTextBlock.Text = timestamp;
}
catch (Exception)
{
  WaitingForDataTextBlock.Text = "Something went wrong...";
}

As can be seen, this code is pretty simple, but enables really advanced scenarios that would have been really complex to manage ourselves.

Summary

In this part, we looked at two more ways to integrate the cloud in our apps. We looked at working with the Live ID, enabling a single sign-on mechanism. Secondly, we looked at storing information in the cloud using roaming settings.

In the last part of this series, we’ll look at working with sockets. Stay tuned!

About the author

Gill Cleeren is Microsoft Regional Director (www.theregion.com), Silverlight MVP (former ASP.NET MVP) and Telerik MVP. He lives in Belgium where he works as .NET architect at Ordina (http://www.ordina.be/). Passionate about .NET, he’s always playing with the newest bits. In his role as Regional Director, Gill has given many sessions, webcasts and trainings on new as well as existing technologies, such as Silverlight, ASP.NET and WPF at conferences including TechEd Berlin 2010, TechDays Belgium – Switzerland - Sweden, DevDays NL, NDC Oslo Norway, SQL Server Saturday Switserland, Spring Conference UK, Silverlight Roadshow in Sweden, Telerik RoadShow UK… He’s also the author of many articles in various developer magazines and for SilverlightShow.net and he organizes the yearly Community Day event in Belgium. He also leads Visug (www.visug.be), the largest .NET user group in Belgium. Gill is the author of “Silverlight 4 Data and Services Cookbook”. In 2012, the second edition, “Silverlight 5 Data and Services Cookbook” is released.

You can find his blog at www.snowball.be.

Twitter: @gillcleeren


Subscribe

Comments

No comments

Add Comment

Login to comment:
  *      *       

From this series