[Update on 12/26/2012] Live SDK 5.3 is now available on Live Connect Developer Center! Many new features in this release, most notably new .Net SDKs for both classic desktop and Asp.Net. It also include an updated Windows Phone SDK targeting the new Windows Phone 8.  Even better, all our SDKs including the Windows and Windows Phone SDKs are now open source. Check out our LiveServices github depot, download the source code and party.  This post is now updated to use code samples for Windows Phone 8.  If you are looking for the starter guide for Windows Phone 7.x, please refer to the older post.

Live Connect provides developers a set of controls and APIs that enable applications to integrate sign-in with the user’s Microsoft account and access user information stored in Windows services such as SkyDrive and Hotmail. In this post, I will walk through the steps for creating a simple Live Connect powered Windows Phone application. Once you get you app started with the basic stuff, you can move on to learn more about our SkyDrive API and how to use it to cloud power your application.

A few words on the behind the scene stuff before I start the step-by-step guide. When building Windows Store apps on Windows 8, Single-Sign-On (SSO) is achieved with support from the OS. (To learn more about how to implement SSO for Windows Store apps, check out our //BUILD 2012 talk or my blog post for “Powering your apps and websites with Microsoft accounts”.) On Windows Phone, however, such support is not available for third party apps. To provide a good sign-in experience on mobile devices, Live Connect allows a mobile client to obtain a refresh token and use it to exchange for an access token. This provides a way for mobile clients to implement a Sign-In-Once experience and avoid the need to ask user for password every time the app is activated. To opt-in for this experience, your app needs to satisfy two criteria:

  1. The app must be provisioned as a mobile app.
  2. User must grant the app offline access permission.

We will discuss the details on how to meet these two criteria in the following step-by-step guide.

Pre-requisite:

Let’s start by creating a new Windows Phone application.

1. Create a new HelloWorldPhone Windows Phone application in Microsoft Visual Studio 2010 or Microsoft Visual Studio 2010 Express for Windows Phone using the Visual C# -> Silverlight for Windows Phone -> Windows Phone Application project template. Choose Windows Phone 8.0 as your target platform.

image_thumb2_thumb

2. Bring up the Add Reference dialog and go to the Assemblies –> extensions tab. Find the Microsoft.Live and Microsoft.Live.Controls assemblies. Add them to your project.

image_thumb4_thumb

3. Open MainPage.xaml in the designer. Bring the Toolbox in view and right-click to select Choose Items… Under Windows Phone Components tab, find the SignInButton control in the Microsoft.Live.Control namespace and add to your toolbox (You only need to do this once). You will see two entries here, choose the one that’s for Windows Phone 8 by examining the directory of the component dll. It should be something like C:\Program Files (x86)\Microsoft SDKs\Live\v5.0\Windows Phone 8.0\References.

image_thumb7_thumb

The SignInButton control should now show up in your toolbox.

PhoneToolBoxItem

4. Drag the SignInButton onto your designer surface. In your xaml file, change the generated xml for the SignInButton to the following:

<Controls:SignInButton Name="btnLogin" Scopes="wl.signin wl.basic wl.offline_access" 
SessionChanged="btnLogin_SessionChanged" HorizontalAlignment="Left" Margin="155,217,0,0" VerticalAlignment="Top"/>

5. Add a couple TextBlock elements to display the greeting and the error message (in case something goes wrong). Here’s the complete xaml for

<phone:PhoneApplicationPage
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
    xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:Controls="clr-namespace:Microsoft.Live.Controls;assembly=Microsoft.Live.Controls"
    x:Class="HelloWorldPhone.MainPage"
    mc:Ignorable="d"
    FontFamily="{StaticResource PhoneFontFamilyNormal}"
    FontSize="{StaticResource PhoneFontSizeNormal}"
    Foreground="{StaticResource PhoneForegroundBrush}"
    SupportedOrientations="Portrait" Orientation="Portrait"
    shell:SystemTray.IsVisible="True">
 
    <!--LayoutRoot is the root grid where all page content is placed-->
    <Grid x:Name="LayoutRoot" Background="Transparent">
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>
 
        <!--TitlePanel contains the name of the application and page title-->
        <StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="12,17,0,28">
            <TextBlock Text="Hello World" Margin="9,-7,0,0" Style="{StaticResource PhoneTextTitle1Style}"/>
        </StackPanel>
 
        <!--ContentPanel - place additional content here-->
        <Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
            <Controls:SignInButton ClientId="[Enter your Client ID]" Scopes="wl.signin wl.basic wl.offline_access" HorizontalAlignment="Left" Margin="10,10,0,0" VerticalAlignment="Top" SessionChanged="btnLogin_SessionChanged"/>
            <TextBlock x:Name="tbGreeting" Text="Hello " HorizontalAlignment="Left" Margin="24,149,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Height="82" Width="394" FontSize="36"/>
            <TextBlock x:Name="tbError" HorizontalAlignment="Left" Margin="24,397,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Height="82" Width="394" FontSize="36"/>
        </Grid>
    </Grid>
 
</phone:PhoneApplicationPage>

6. Add the following code in your MainPage.xaml.cs file.

using System;
using Microsoft.Phone.Controls;
 
using Microsoft.Live;
using Microsoft.Live.Controls;
 
namespace HelloWorldPhone
{
    public partial class MainPage : PhoneApplicationPage
    {
        private LiveConnectClient liveClient;
 
        public MainPage()
        {
            InitializeComponent();
        }
 
        private void btnLogin_SessionChanged(object sender, LiveConnectSessionChangedEventArgs e)        
        {            
            if (e != null && e.Status == LiveConnectSessionStatus.Connected)            
            {                
                this.liveClient = new LiveConnectClient(e.Session);                
                this.GetMe();            
            }            
            else            
            {                
                this.liveClient = null;                
                this.tbError.Text = e.Error != null ? e.Error.ToString() : string.Empty;            
            }        
        }        
        
        private async void GetMe()        
        {
            try
            {
                LiveOperationResult operationResult = await this.liveClient.GetAsync("me");
                var jsonResult = operationResult.Result as dynamic;
                string firstName = jsonResult.first_name ?? string.Empty;
                string lastName = jsonResult.last_name ?? string.Empty;
                this.tbGreeting.Text = "Welcome " + firstName + " " + lastName;
            }
            catch (Exception e)
            {
                this.tbError.Text = e.ToString();
            }
        }
    }
}

Before proceeding, let’s take a look at what the above code does.

  • The xaml definition of the SignInButton control specifies the scopes that the app needs to ask user permissions for. We’re including 3 scopes here: wl.sign, wl.basic and wl.offline_access. Together these 3 scopes give the app access to user’s basic profile information and allows the app to access data even when the user is not actively using the app. For more information on Live Connect scopes, read here.
  • The xaml definition also adds an event handler for the SessionChanged event on the SignInButton. This event is fired when the sign-in process has finished.
  • If access is granted and the LiveConnectSession object indicates the LiveConnectSessionStatus as Connected, a new instance of the LiveConnectClient class is created with the current Session object.
  • In the function GetMe(), the code talks to the Live Connect REST API to retrieve user’s basic profile information by calling LiveConnectClient.GetAsync on “me”.LiveConnectClient.Async is implemented as an async operation using the Task async pattern. use the keyword “await” to call this API.
  • When the result comes back, the app can then obtain user’s first and last names through the operatonResult.Result IDictionary object. In this example, we cast operationResult.Result to a “dynamic” object so you can access the dictionary values through the .key syntax.

7. Before you can run the app, you need to provision it with Live Connect. Go to the application management site and click the Create Application link. Create an application called HelloWorldPhone.

PhoneNewApp

8. After you click “I accept”, an application is created for you with a client id and a client secret (values removed for discretion).

PhoneAppCreated

9. Go to Application Settings Page and click on the API Settings tab. Check “Yes” for “Mobile client app” and save.

PhoneAppCreated

10. The app is now provisioned and ready to go. Go back to your MainPage.xaml, and add the ClientId property on the SignInButton.

<my:SignInButton Name="btnLogin" ClientId="[Your Client ID here]" HorizontalAlignment="Left" SessionChanged="btnLogin_SessionChanged" Scopes="wl.signin wl.basic wl.offline_access" />

11. You’re done. Hit F5 and run the app in the emulator. Click the “Sign In” button and type in a username and password to sign into Windows Live. Next you will see a screen asking user permission to access data.

image_thumb1

13. Click Yes. Notice that the SignInButton has changed to “Sign Out” state and a greetings with your name is displayed.

image_thumb2[1]

14. At this point, the app can continue to access user data until user signs out or until the refresh token is expired. A refresh token is valid for one year and is reset every time a new access token is issued. The user will not be asked for credentials again as long as the app is activated at least once a year.

For more Live Connect code samples, visit our github site at https://github.com/liveservices/livesdk.