Live Connect SDK for Windows Phone 8–authenticating and basic info

Live SDK makes it easy for you as a developer to use Live services from inside your Windows Phone 8 app. More than 500 million people use services like SkyDrive, Hotmail, Messenger etc. There are some things which you don’t want to store locally when building apps, such as data that needs to be used from any device that a person has, calendars and events, people etc. When you use Live SDK, it synchronizes beautifully in the Cloud and becomes available on all the devices. I’ll try to cover some basic Windows Phone 8 Live Connect stuff in 3 days. This is day 1.

This is how I’ll cover it:

Day 1 – Live Connect core concepts – authentication + getting basic information about the user

Day 2 – Hotmail – working with contacts and calendar (events)

Day 3 – SkyDrive – working with files (photos, documents etc.)

Possible questions

1. Why 3 days?

Because it makes it easy to separate the problem of working with Live SDK in 3 main topic: basic, core concepts of Live SDK, Hotmail and SkyDrive.

2. OK, but why not day 4 and Windows Live Messenger?

Well, according to Microsoft and the official Live SDK website:

We recently announced that we’ll begin to encourage Messenger users to start using Skype. As a result, the Messenger developer program will end. Existing implementations that use Extensible Messaging and Presence Protocol (XMPP) will continue to work until October 2013. Existing implementations that use MSP will continue to work until March 2014.

In other words, Windows Live Messenger will very soon become forgotten, so we might as well skip it.

3. Is there a difference between the Windows Phone 7 & Windows Phone 8 Live SDK?

Perhaps not in the SDK itself, but what’s different is how you make the calls. In WP7 you may have used async calls with callback methods, but in WP8 you use the async/await pattern which makes the code simpler and cleaner. So unless you used Async CTP in your WP7 projects, there’s a difference.

4. I am a Android/iOS/Symbian/something developer. Can I use it in my apps?

YES! There is an SDK for iOS and Android platform available, as well as the possibility to use REST services, so Live SDK can be used on pretty much any platform today!

Day 1 – core Live SDK (authentication, basic user info)

In order to develop Windows Phone 8 apps, you need to install the official SDK, available here:

https://dev.windowsphone.com/en-us/downloadsdk

Next, you need to download and install Live SDK:

http://www.microsoft.com/en-us/download/details.aspx?id=35754

The latest version at the moment of writing this blog post is 5.3, available since 11/15/2012

Create a new Windows Phone 8 project, or use the old one you have. Add the Live SDK reference:

image

The Microsoft.Live is the main reference, and the Microsoft.Live.Controls can even be excluded – it gives you a so called Sign-In button control, which you may or may not use inside your app. I won’t be using it in this tutorial.

One more step is needed to be able to start using the SDK in your app. You need to register your app and get the Client ID which is needed to get your app recognized by the Live services. Go to:

https://manage.dev.live.com/

Then click on My apps and then click on Create application:

imageAdd the application name and choose language and accept the terms of use.

Set the needed settings for your app, and you’ll get the very important Client ID:

image

You need to keep your Client ID and Client Secret a secret. We will only need Client ID.

* Note:  If you’re developing Windows 8 apps, you just need to create a Windows 8 app in your DEV dashboard (reserve app name at least), and then associate your app in Visual Studio app with the app you created through Dashboard. You don’t need to use the Client ID.

Add the following XAML code in your MainPage.xaml

<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">  
    <StackPanel Orientation="Horizontal"
                             HorizontalAlignment="Center"
                             VerticalAlignment="Top">
        <Image Name="profileImage"
                       Width="32" Height="32"
                       VerticalAlignment="Center"
                       Margin="12,0"/>
        <TextBlock Name="infoText" FontSize="22" VerticalAlignment="Center" TextWrapping="Wrap" Margin="12"/>
    </StackPanel>
</Grid>

The Image will hold the image of the user who logs in, and the textblock will hold a message about the user who logged in or about any errors that occurred.

In the MainPage.xaml.cs add the following code

LiveAuthClient auth;

        public MainPage()
        {
            InitializeComponent();
            this.Loaded += MainPage_Loaded;
        }

LiveAuthClient is the object we’ll be using for authenticating with Live services, and we’ll do everything in the MainPage_Loaded event handler:

async void MainPage_Loaded(object sender, RoutedEventArgs e)  
{
    try
    {
        bar.Visibility = Visibility.Visible;
        auth = new LiveAuthClient("YOUR_APP_CLIENT_ID_GOES_HERE");
        LiveLoginResult result = await auth.InitializeAsync(new string[] { "wl.basic", "wl.offline_access", "wl.signin" });
        if (result.Status != LiveConnectSessionStatus.Connected)
            result = await auth.LoginAsync(new string[] { "wl.basic", "wl.offline_access", "wl.signin" });

        if (result.Status == LiveConnectSessionStatus.Connected)
        {
            this.infoText.Text = "Signed in";
        }
    }
    catch (LiveAuthException exc)
    {
        this.infoText.Text = "Error: " + exc.Message;
    }
    finally
    {
        bar.Visibility = Visibility.Collapsed;
    }
}

‘bar’ object is a simple ProgressBar which we hide and show when needed. We create the LiveAuthClient object using the Client ID as constructor parameter. LiveLoginResult is a result object I get after trying to sign in. There are two ways of signing in – if we already have a valid session from before using InitializeAsync method should establish the connection and sign us in quietly. If not, the result status will not be Connected but either Disconnected or Unknown, after which we call the LoginAsync method.

Note how both the InitializeAsync and LoginAsync use IEnumerable of strings in constructor parameter, in my case an array of strings. Those arrays of string define a scope – what does a user allow my app to touch. In the basic, core scenario I use 3 scopes:

wl.basic - Read access to basic profile info of the user

wl.offline_access – this enables the app to access user info even when the user is not using it. It’s important because it gives the app an additional code called refresh token which the app can use to get the new access token whenever it needs one, typically for up to a year.

wl.signin – this enables single sign on – if the user signed in to your app, he’s also signed in to your app’s website

These three scopes are called core scopes, and there are other called extended scopes which ask for permission to get some other data from the user, and also use both read and write access. I’ll cover those in the next posts.

If the authentication fails and there’s an exception, the exception thrown is LiveAuthException. Let’s see what happens when I run this sample.

image

Because my emulator is not connected to my Microsoft Account, I am first asked to sign in using my credentials. After I do that, I get the following screen:

image

I am asked to give permission to this app to do some things which are defined by the scope.

After I click Yes, I am signed in:

image

If I exit the app and get back later, I simply get signed in automatically, and don’t have to repeat the steps from above.

After the user is signed in, I can do some pretty cool stuff – for example just access user’s profile info. Let’s see how to do that:

try  
{
    bar.Visibility = Visibility.Visible;
    auth = new LiveAuthClient("YOUR CLIENT ID GOES HERE");
    LiveLoginResult result = await auth.InitializeAsync(new string[] { "wl.basic", "wl.offline_access", "wl.signin" });
    if (result.Status != LiveConnectSessionStatus.Connected)
        result = await auth.LoginAsync(new string[] { "wl.basic", "wl.offline_access", "wl.signin" });

    if (result.Status == LiveConnectSessionStatus.Connected)
    {
        var connect = new LiveConnectClient(auth.Session);
        var opResult = await connect.GetAsync("me");
        dynamic nameResult = opResult.Result;
        this.infoText.Text = "Hello " + nameResult.name + ", you are signed in";

        var photoResult = await connect.GetAsync("me/picture");
        dynamic photoResultdyn = photoResult.Result;
        var image = new BitmapImage(new Uri(photoResultdyn.location, UriKind.Absolute));
        this.profileImage.Source = image;
    }
}
catch (LiveAuthException exc)  
{
    this.infoText.Text = "Error: " + exc.Message;
}
catch (LiveConnectException connExc)  
{
    this.infoText.Text = "Error making request: " + connExc.Message;
}
finally  
{
    bar.Visibility = Visibility.Collapsed;
}

Obviously we repeat the steps for signing in like above. After we are connected, we create a LiveConnectClient object using the session as a constructor parameter. This means that the session has been created and that we use the existing one to make calls to Live services. What calls are available?

  • GETawait GetAsync(string) – get a resource
  • POSTawait PostAsync(string, IDictionary<String, Object>) – post a resource
  • PUTawait PutAsync(string, IDictionary<String, Object>) – edit resource or create if non existing
  • DELETE - await DeleteAsync(string) – delete a resource
  • MOVEawait MoveAsync(string, string) – move a resource
  • COPY await CopyAsync(string, string) – copy a resource

Each of those has at least a string as a parameter. What is this string parameter? It means a path to certain resources. Examples of paths are:

  • me – basic information about the user who signed in
  • me/picture – picture of the user signed in
  • USER_ID/picture – public picture of some user defined by user ID
  • me/skydrive/files – lists SkyDrive files
  • FOLDER_ID/files – lists file in a certain folder, defined by folder ID
  • me/events – lists events of a user who signed in
  • CALENDAR_ID/events – lists events from a particular calendar defined by calendar ID

and so on.

What is the IDictionary<string,object> parameter? You’ll notice that it’s used only in POST and PUT. This immediately tells you that you use it for defining a resource you will upload to Live services. For example, if you were creating a new event, you would define it like a dictionary of string-object key value pairs, like this:

var calEvent = new Dictionary<string, object>();  
calEvent.Add("name", "MSCommunity 54. sastanak DEV UG");  
calEvent.Add("description", "Jubilarni 52. sastanak");  
calEvent.Add("start_time", "2012-12-13T17:30:00-08:00");  
calEvent.Add("end_time", "2012-12-13T20:30:00-08:00");  
calEvent.Add("location", "Somewhere in Croatia");  
calEvent.Add("is_all_day_event", false);  
calEvent.Add("availability", "busy");  
calEvent.Add("visibility", "public");  
var addEventResult = await connect.PostAsync("me/events", calEvent);

Let’s get back to the sample above.

All the methods have their async implementation in the SDK, so that’s what I use – GetAsync call which is awaitable. I use me path to get the details about the user who signed in. I get a LiveOperationResult as a result of my GET request, which holds the data in a dictionary, in a form similar to the above of a calendar event. I can easily create a dynamic type and access properties like with any other type (unfortunately, we need to know the names of the properties – the dynamic types get created during runtime so they are not available through IntelliSense).

I do the same with the picture – using me/picture path I get the URI of the image of the user who signed in. Here’s what happens when I run the sample:

image

The application greets me. And that’s it.

You have now conquered the core concepts of Live SDK in Windows Phone 8. What’s really cool is that the same code can be used for Windows 8 Store apps (C#+XAML), so you can reuse the code you write for Windows Phone 8 in your Windows 8 app and vice versa (the difference is only in associating the app with Live services – explained above).

In the next article we’ll see how to use the Live SDK with Hotmal – calendars, events, contacts.

comments powered by Disqus