[Update on 12/27/2012] If you’re looking for the starter guide for Live SDK on Windows Phone 8, please refer to this post.  If you’re looking for the starter guide for Live SDK on Windows 8 or Asp.Net, please refer to this post.

[Update on 4/17/2012] We now have an iOS SDK and an Android SDK as well. Check it out! The 5.1 release is now live on Live Connect Developer Center. This release fixes some known issues with the 5.0 release. It also include a version of the SDK for Windows 8 that’s compatible with the Windows 8 Consumer Preview.

Live Connect provides developers a set of controls and APIs that enable applications to integrate sign in with the user’s Microsoft account and enable users to access information from SkyDrive, Hotmail, and Messenger. In my previous posts, I talked about how to integrate Live Connect using the Live SDK in Metro style apps written in JavaScript and in Metro style apps written in C#. If you’re a Windows Phone developer, the same SDK also supports integrating Live Connect in a Windows Phone app. In this post, I will walk through the steps for creating a simple Live Connect powered Windows Phone application.

A few words on the behind the scene stuff before I start the step-by-step guide. When building Metro style apps on Windows 8 Consumer Preview, Single-Sign-On (SSO) is achieved with support from the OS. 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:

  • Download and install the latest Windows Phone Developer Tools from App Hub.
  • Download and install Live SDK.

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.

PhoneNewProj

2. Bring up the Add Reference dialog and go to the .Net tab. Scroll down to find the Microsoft.Live and Microsoft.Live.Controls assemblies. Add them to your project.

PhoneAddRef

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).

PhoneToolBoxChooseItem

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:

<my:SignInButton Name="btnLogin" HorizontalAlignment="Left" Scopes="wl.signin wl.basic wl.offline_access" 
SessionChanged="btnLogin_SessionChanged" />

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 MainPage.xaml.

<phone:PhoneApplicationPage 
x:Class="HelloWorldPhone.MainPage"
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"
mc:Ignorable="d" d:DesignWidth="480" d:DesignHeight="768"
FontFamily="{StaticResource PhoneFontFamilyNormal}"
FontSize="{StaticResource PhoneFontSizeNormal}"
Foreground="{StaticResource PhoneForegroundBrush}"
SupportedOrientations="Portrait" Orientation="Portrait"
shell:SystemTray.IsVisible="True" xmlns:my="clr-namespace:Microsoft.Live.Controls;assembly=Microsoft.Live.Controls">

<!--LayoutRoot is the root grid where all page content is placed-->
<Grid x:Name="LayoutRoot" Background="Transparent">
<Grid.RowDefinitions>
<RowDefinition Height="129"/>
<RowDefinition Height="639*"/>
</Grid.RowDefinitions>

<!--TitlePanel contains the name of the application and page title-->
<StackPanel x:Name="TitlePanel" Margin="12,17,0,0">
<TextBlock x:Name="ApplicationTitle" Text="Hello World" Style="{StaticResource PhoneTextNormalStyle}"/>
<my:SignInButton Name="btnLogin" Scopes="wl.signin wl.basic wl.offline_access" SessionChanged="btnLogin_SessionChanged" HorizontalAlignment="Left" />
</StackPanel>

<!--ContentPanel - place additional content here-->
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
<TextBlock Name="tbGreeting" FontSize="40" Height="80" HorizontalAlignment="Left" Margin="20,30,0,0" Text="Hello" VerticalAlignment="Top" Width="418" />
<TextBlock Name="tbError" FontSize="24" Height="80" HorizontalAlignment="Left" Margin="20,130,0,0" Text="No Errors." VerticalAlignment="Top" Width="418" />
</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 void GetMe()
{
this.liveClient.GetCompleted += OnGetMe;
this.liveClient.GetAsync("me", null);
}

private void OnGetMe(object sender, LiveOperationCompletedEventArgs e)
{
this.liveClient.GetCompleted -= OnGetMe;
if (e.Error == null)
{
string firstName = e.Result.ContainsKey("first_name") ? e.Result["first_name"] as string : string.Empty;
string lastName = e.Result.ContainsKey("last_name") ? e.Result["last_name"] as string : string.Empty;

this.tbGreeting.Text = "Welcome " + firstName + " " + lastName;
}
else
{
this.tbError.Text = e.Error.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. In addition, the documentation you can download from the Live SDK download site includes updated information on this release.
  • 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”.
  • When the result comes back, the GetCompleted event on LiveConnectClient is fired, the app can then obtain user’s first and last names through the e.Result IDictionary object.

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.

PhoneConsent

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

PhoneSuccess

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.