Live Connect Preliminary Documentation

[This documentation is preliminary and is subject to change.]

November 2012

This document supports a preliminary release of a software product that may be changed substantially prior to final commercial release. This document is provided for informational purposes only and Microsoft makes no warranties, either express or implied, in this document. Information in this document, including URL and other Internet Web site references, is subject to change without notice. The entire risk of the use or the results from the use of this document remains with the user. Unless otherwise noted, the companies, organizations, products, domain names, email addresses, logos, people, places, and events depicted in examples herein are fictitious. No association with any real company, organization, product, domain name, email address, logo, person, place, or event is intended or should be inferred. Complying with all applicable copyright laws is the responsibility of the user. Without limiting the rights under copyright, no part of this document may be reproduced, stored in or introduced into a retrieval system, or transmitted in any form or by any means (electronic, mechanical, photocopying, recording, or otherwise), or for any purpose, without the express written permission of Microsoft Corporation.

Microsoft may have patents, patent applications, trademarks, copyrights, or other intellectual property rights covering subject matter in this document. Except as expressly provided in any written license agreement from Microsoft, the furnishing of this document does not give you any license to these patents, trademarks, copyrights, or other intellectual property.

Microsoft, Hotmail, SkyDrive, Windows, and Windows Live are trademarks of the Microsoft group of companies.

All other trademarks are property of their respective owners.

Build date: 11/15/2012

© 2012 Microsoft. All rights reserved.


Live SDK developer guide

Introducing Live Connect

More than 500 million people use services like Microsoft SkyDrive, Hotmail, and Windows Live Messenger. When you build apps that work with these services, you give your users new ways to engage with your products and services. To help you create this value and build successful apps that your customers enjoy, we offer Live Connect—a collection of APIs that help you integrate your apps quickly and easily with compatible services like SkyDrive, Hotmail, and Messenger.

The Live Connect APIs use industry standard protocols such as OAuth 2.0, JavaScript Object Notation (JSON), and Extensible Messaging and Presence Protocol (XMPP). To call the APIs, you primarily use Representational State Transfer (REST) requests that return info formatted in JSON. This architecture enables us to support a variety of platforms, including those for web, desktop, and mobile apps, like those for the iOS and Android operating systems. In addition, there are Microsoft software development kits (SDKs) for developing apps for Windows Phone and Windows 8.

Live Connect exposes info from these services:

  • SkyDrive for working with documents and media. Your apps can use the Live Connect APIs to create, read, update, and delete a SkyDrive user's folders, files, albums, photos, and videos, and to read, create, and delete any associated tags and comments.
  • Hotmail for working with contacts and calendars. With the Live Connect APIs, your apps can create and read a Hotmail user's contacts, and can create, read, update, and delete the user's calendars and their associated events.
  • Messenger for instant messaging. Your apps can exchange instant messages with a Messenger user's buddies, communicate the user's current presence, display the user's current status message, and more.
  • Live for authenticating users and accessing their profile info.

In this guide, we begin with a brief overview of the open standards that we use in Live Connect. Then we describe how to start integrating your own apps with Live Connect, and we show you some code that introduces a few of the things that the Live Connect APIs can do. At the end of this guide, we provide pointers to our complete documentation and code samples.

Contents

  • Open standards
  • Getting started
  • Getting user permission
  • Signing users in
  • Hotmail: contacts and calendars
  • SkyDrive: files and photos
  • Messenger: instant messaging
  • Sharing status
  • Next steps

Open standards

When you use open standards, you can spend less time learning new concepts and more time writing code and being productive. That's why Live Connect is built upon many open standards that you probably already use in apps that you write today. And, if this the first time you've added a social component to an app, it's likely that the code you write with Live Connect can also be used with APIs from other services.

Before you start coding, you should be aware of a few open standards that are important to Live Connect: OAuth 2.0, Representational State Transfer (REST), JSON, and XMPP.

  • OAuth 2.0 is the latest version of the OAuth protocol, an open standard for authenticating users' credentials. Live Connect, along with other social networking APIs, has adopted OAuth 2.0 as its authentication standard. At its core, OAuth 2.0 enables users to be authenticated by the Live Connect authorization web services without sharing their confidential sign-in credentials with your apps. Although the OAuth 2.0 specification contains info about a variety of authentication scenarios, or flows, Live Connect focuses on three:

    • The implicit grant flow, for client-server authentication
    • The authorization code flow, for server-to-server authentication
    • The sign-in control flow, a Live Connect-specific implementation of the implicit grant flow that enables you to use our APIs to start the authentication process from within your apps

    For more info about OAuth 2.0, see The OAuth 2.0 Authorization Protocol.

    For details about how we use this open standard, see OAuth 2.0.

  • REST is an architectural style that's become popular in web services. Our use of REST makes it easy for you to request users' info through the Live Connect APIs. This REST implementation supports standard HTTP methods like GET, PUT, POST, and DELETE. We also include a few shortcuts to make certain requests even simpler to implement. For example, to get info about the signed-in user, you can use our shortcut me in your request.

    For more info about REST, see Representational state transfer.

    For details about requesting and updating user info, see REST reference.

    Tip

    Although our REST API handles the bulk of the work, we also offer a Live Software Development Kit (SDK) for Windows 8, Windows Phone, iOS, and Android as well as a JavaScript web API to help make calling our REST API easier.

  • JSON is a popular means of representing info in web services. Live Connect exchanges user info in JSON format. For example, when your app requests a user's birth date, that info is returned in a response object that contains birth_day, birth_month, and birth_year structures.

    For more info about JSON, see Introducing JSON.

  • XMPP is an open standard for real-time communication. Your apps can use it to interact with a Messenger user and with his or her buddies.

    For more info about XMPP, see XMPP Standards Foundation - Extensible Messaging and Presence Protocol (XMPP): Core.

Top

Getting started

To have Live Connect recognize your app, you need to configure your app with a few settings, depending on your app's type. For Windows Store apps, you get these settings at the Windows Store Dashboard. For all other app types, you get these settings at the Live Connect app management site. At either site, sign in with a Microsoft account and follow the on-screen directions. For more info, see Configuring your app.

Top

Getting user permission

After you get a client ID, you can start thinking about what user info is necessary for your app. Live Connect organizes user info into categories that we call scopes. For example, if your app is to work with a user's Hotmail contacts list, it would request the wl.basic scope through Live Connect. Live Connect prompts the user to sign in to Hotmail (or to another service that is compatible with Live Connect, depending on the scope that your app requests). As part of sign-in, the user also sees a page that asks permission for your app to access the requested portions of their info. When the user gives permission, or consents, Live Connect gives your app a unique string of characters called an access token. Your app uses this access token to obtain the requested user info from the Live Connect-compatible service (in this example, Hotmail). The access token uniquely represents the combination of a specific client ID, a specific signed-in user, and the specific set of scopes that the user consented to. Also, the access token is valid only for a specific period of time.

Tip Your app can request the wl.offline_access scope to ask the user if it's okay for your app to get a refresh token. A refresh token is a separate, unique string of characters that your app can use to get a replacement access token when the original expires. The replacement access token covers the same combination of client ID, user, and scopes as the original, enabling your app to access the user's info even if he or she is offline. The refresh token can keep doing this until the user intentionally revokes consent for the wl.offline_access scope.

We recommend that you keep the number of scopes that you request to a minimum, because we think it provides a better user experience. It might be tempting to create an app that simply requests access to any and all user info that your app might possibly need. It's likely, however, that users will hesitate when they see how much access your app wants. The better solution is to request consent to only a few key scopes—those that closely match the context of your app. For example, if you are creating a photo-sharing app, it would make sense to request access to the wl.photos, wl.contacts_photos, or wl.skydrive scope. Later on, if a user wants to use a part of your app that requires a different scope—accessing a Hotmail calendar, for example—you can request the user's consent to the wl.calendars or wl.calendars_update scope at that time. If you request additional consent from a user, remember that your app must also request a new access token, which your app must then use instead of the old one.

For a complete list of available scopes, see Scopes and permissions.

Top

Signing users in

When you create a personalized experience for your users, you increase the likelihood of user satisfaction and loyalty. You can bring this experience to millions of users by using Live Connect. In this section, we'll talk about the first step in creating a personalized experience: adding a way for the user to sign in with his or her Microsoft account credentials and then greeting the signed-in user by name.

Live Connect includes several ways to add sign-in functionality to your app by using JavaScript, C#, Objective-C, Java, and REST. We'll briefly cover them here.

JavaScript

If you're writing a Windows Store app or a client-side webpage that uses JavaScript, you can display a Live Connect sign-in control to start the sign-in process. You can also use an existing HTML element, like a button, to start the sign-in process.

To add a sign-in control, you use the WL.ui method. Here's the relevant code extracted from a larger code sample, which we'll explain shortly.

HTML
WL.Event.subscribe("auth.login", onLogin);
HTML
WL.init({
    client_id: APP_CLIENT_ID,
    redirect_uri: REDIRECT_URL,
    scope: "wl.signin",
    response_type: "token"
});
HTML
WL.ui({
    name: "signin",
    element: "signin"
});
HTML
function onLogin() {
    document.getElementById("infoLabel").innerText = "Signed in.";
}

To connect the sign-in control to an HTML element on your web page, you can simply add a <div> tag with an id attribute of, in this case, "signin".

To start the sign-in process from an HTML element like a button, as mentioned previously, you use the WL.login method. Here's the relevant code for that.

HTML
function moreScopes_onClick() {
    WL.login({
        scope: ["wl.signin", "wl.basic"]
    }).then(
        function (session) {
            document.getElementById("infoLabel").innerText = "Signed in.";
        },
        function (sessionError) {
            document.getElementById("infoLabel").innerText =
                "Error signing in: " + sessionError.error_description;
        }
    );
}

This approach is ideal for situations in which the sign-in control does not meet the needs of your app, or in which the user must provide additional consent for your app to get more user info (because the sign-in control typically includes only an initial consent level).

Let's look at the code so far. The WL.Event.subscribe method instructs the code to use the onLogin callback method after the user completes the sign-in and consent process; the WL.login method uses inline functions instead. (Note that auth.login events are raised whenever the user's sign-in status changes from "unknown" or "notConnected" to "connected".) The WL.login method instructs the code to use the anonymous methods after .then to determine whether the user successfully signed in and consented to the requested scopes. The scopes are represented by the anonymous method after .then with the session parameter. The wl.signin scope enables a user to automatically sign in to Live services from an app if the user has previously signed in to Live services. The additional wl.basic scope in the WL.init method provides access to basic info like the user's display name.

After the user signs in, you could use the wl.basic scope, along with the WL.api method, to greet the user by name as shown in the following example.

JavaScript
function greetUser_onClick() {
    WL.login({
        scope: "wl.basic"
    }).then(
        function (response)
        {
            WL.api({
                path: "me",
                method: "GET"
            }).then(
                function (response){
                    document.getElementById("infoArea").innerText =
                        "Hello, " + response.first_name + " " +
                        response.last_name + "!";
                },
                function (responseFailed){
                    document.getElementById("infoArea").innerText =
                        "Error calling API: " + responseFailed.error.message;
                }
            );
        },
        function (responseFailed){
            document.getElementById("infoArea").innerText =
                "Error signing in: " + responseFailed.error_description;
        }
    );
}

In this example, the WL.api method uses our shortcut me to call the Live Connect APIs to get info about the signed-in user. If the HTTP GET method successfully calls the APIs, the user's first name and last name are displayed, based on the contents of the response object.

C#

If you're writing a Windows Store app or a Windows Phone app using C#, you can display a Live Connect sign-in control by using Extensible Application Markup Language (XAML) code. Then you write C# code that starts the sign-in process when the user clicks the control. Following is the relevant XAML code in an example of a Windows Store app.

XAML
<Page
    x:Class="CSharpCodeSample.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:CSharpCodeSample"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d"
    xmlns:live="using:Microsoft.Live.Controls">

    <Grid Background="{StaticResource ApplicationPageBackgroundBrush}">
    <live:SignInButton x:Name="btnSignin" Scopes="wl.signin wl.basic" SessionChanged="btnSignin_SessionChanged" />
        <TextBlock Height="32" Foreground="White" HorizontalAlignment="Left" Margin="8,76,0,0" Name="infoTextBlock" VerticalAlignment="Top" Width="419" />
    </Grid>
</Page>

Note The XAML code for a Windows Phone app looks almost the same. Instead of a <Page> element, you must use a <phone:PhoneApplicationPage> element with different attributes. Also, in the <live:SignInButton> element, you must at least add a ClientId attribute.

This XAML code specifies that the btnSignin_SessionChanged event handler is to be called after the user completes the sign-in and consent process.

And here's the C# code for a Windows Store app.

C#
using System;
using System.IO;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Microsoft.Live;
using Microsoft.Live.Controls;

namespace CSharpCodeSample
{
    public sealed partial class MainPage : Page
    {
        private LiveAuthClient auth;
        private LiveConnectClient client;
        private LiveConnectSession session;

        public MainPage()
        {
            this.InitializeComponent();
        }

        private void btnSignin_SessionChanged(object sender, LiveConnectSessionChangedEventArgs e)
        {
            if (e.Status == LiveConnectSessionStatus.Connected)
            {
                session = e.Session;
                client = new LiveConnectClient(session);
                infoTextBlock.Text = "Signed in.";
            }
            else
            {
                infoTextBlock.Text = "Not signed in.";
                client = null;
            }
        }
    }
}

Note The code for Windows Phone looks almost the same. You must declare additional using statements, and the MainPage class must inherit the PhoneApplicationPage class.

In this code example, the LiveConnectSessionChangedEventsArgs variable named e determines whether the user successfully signed in and consented to the requested scopes, which is represented here by the LiveConnectSessionStatus.Connected enumeration.

You can also start the sign-in process from a different control, like a button. Here's the relevant code.

C#
private async void btnMoreScopes_Click(object sender, RoutedEventArgs e)
{
    try
    {
        LiveAuthClient auth = new LiveAuthClient();
        LiveLoginResult loginResult = await auth.LoginAsync(new string[] { "wl.basic" });
        if (loginResult.Status == LiveConnectSessionStatus.Connected)
        {
            this.infoTextBlock.Text = "Signed in.";
        }
    }
    catch (LiveAuthException exception)
    {
        this.infoTextBlock.Text = "Error signing in: " + exception.Message;
    }
}

In this code example, the LiveAuthClient.LoginAsync method, instead of the btnSignin_SessionChanged method in the previous example, starts the sign-in and consent process. If this process succeeds, the LiveLoginResult variable named loginResult checks for the LiveConnectSessionStatus.Connected enumeration.

To extend this code example, you could use the wl.basic scope and the GetAsync method to greet the user by name. The code would look like this.

[C# for Windows Store apps]

C#
private async void btnGreetUser_Click(object sender, RoutedEventArgs e)
{
    try
    {
        LiveAuthClient auth = new LiveAuthClient();
        LiveLoginResult initializeResult = await auth.InitializeAsync();
        try
        {
            LiveLoginResult loginResult = await auth.LoginAsync(new string[] { "wl.basic" });
            if (loginResult.Status == LiveConnectSessionStatus.Connected)
            {
                LiveConnectClient connect = new LiveConnectClient(auth.Session);
                LiveOperationResult operationResult = await connect.GetAsync("me");
                dynamic result = operationResult.Result;
                if (result != null)
                {
                    this.infoTextBlock.Text = string.Join(" ", "Hello", result.name, "!");
                }
                else
                {
                    this.infoTextBlock.Text = "Error getting name.";
                }
            }
        }
        catch (LiveAuthException exception)
        {
            this.infoTextBlock.Text = "Error signing in: " + exception.Message;
        }
        catch (LiveConnectException exception)
        {
            this.infoTextBlock.Text = "Error calling API: " + exception.Message;
        }
    }
    catch (LiveAuthException exception)
    {
        this.infoTextBlock.Text = "Error initializing: " + exception.Message;
    }
}

In this C# for Windows Store apps code example, the GetAsync method calls the Live Connect APIs to get info about the signed-in user. If the GetAsync method successfully calls the Live Connect APIs, the user's first name and last name are displayed.

Let's now look at the Windows Phone versions of how to start the sign-in process from a control's click event and how to greet the user by name.

[C# for Windows Phone apps]

C#
private void moreScopes_Click(object sender, RoutedEventArgs e)
{
    auth = new LiveAuthClient(btnSignin.ClientId);
    auth.LoginCompleted +=
        new EventHandler<LoginCompletedEventArgs>(MoreScopes_LoginCompleted);
    auth.LoginAsync(new string[] { "wl.signin", "wl.basic" });
}

void MoreScopes_LoginCompleted(object sender, LoginCompletedEventArgs e)
{
    if (e.Status == LiveConnectSessionStatus.Connected)
    {
        session = e.Session;
        client = new LiveConnectClient(session);
        infoTextBlock.Text = "Signed in.";
    }
    else if (e.Error != null)
    {
        infoTextBlock.Text = "Error signing in: " + e.Error.ToString();
    }
}

In this C# for Windows Phone apps example, the LoginAsync method starts the sign-in and consent process, and the LoginCompleted event handler named MoreScopes_LoginCompleted determines whether the user successfully signed in and consented to the requested scopes.

To extend this code example, you could use the wl.basic scope, along with the GetAsync method, to greet the user by name. The code would look like this.

[C# for Windows Phone apps]

C#
private void greetUser_Click(object sender, RoutedEventArgs e)
{
    auth = new LiveAuthClient(btnSignin.ClientId);
    auth.LoginCompleted +=
        new EventHandler<LoginCompletedEventArgs>(greetUser_LoginCompleted);
    auth.LoginAsync(new string[] { "wl.basic" });
}

void greetUser_LoginCompleted(object sender, LoginCompletedEventArgs e)
{
    if (e.Status == LiveConnectSessionStatus.Connected)
    {
        LiveConnectClient connect = new LiveConnectClient(e.Session);
        connect.GetCompleted +=
            new EventHandler<LiveOperationCompletedEventArgs>(greetUser_GetCompleted);
        connect.GetAsync("me");
    }
    else
    {
        infoTextBlock.Text = "Not signed in.";
    }
}

void greetUser_GetCompleted(object sender, LiveOperationCompletedEventArgs e)
{
    if (e.Error == null)
    {
        infoTextBlock.Text = "Hello, " + e.Result["name"].ToString() + "!";
    }
    else
    {
        this.infoTextBlock.Text = "Error calling API: " + e.Error.ToString();
    }
}

In this C# for Windows Phone apps example, the GetAsync method calls the Live Connect APIs to get info about the signed-in user. After the Live Connect APIs are called, the GetCompleted event handler named GreetUser_GetCompleted displays the user's name (or an error if the call was unsuccessful).

Objective-C

If you're writing an iOS app, you can sign the user in when the app starts. Here's how.

ObjectiveC
- (void)viewDidLoad
{
    [super viewDidLoad];
    self.liveClient = [[LiveConnectClient alloc] initWithClientId:APP_CLIENT_ID
                                                         delegate:self
                                                        userState:@"genesis"];
}

- (void) authCompleted:(LiveConnectSessionStatus)status
               session:(LiveConnectSession *)session
             userState:(id)userState
{
    if (session != nil) {
        self.statusLabel.text = @"You are signed in.";
    }
}

- (void) authFailed:(NSError *)error
          userState:(id)userState
{
    // Failed.
}

In this example, the variable named liveClient is of type LiveConnectClient and represents the Live Connect session. This code is part of a larger interface that implements LiveAuthDelegate, which means that when the LiveConnectClient variable calls its initWithClientId:delegate:userState method, the LiveAuthDelegate interface's authCompleted:session:userState (for success) or authFailed:userState (for failure) method is called. (Note that, although not shown here, the code's parent interface implements LiveAuthDelegate. Because it does this, the example code can pass self as a delegate parameter. Alternatively, your code can implement a class that itself implements LiveAuthDelegate and pass that class as a delegate parameter.)

You can also start the sign-in process from a different control, like a button. Here's the relevant code.

ObjectiveC
- (IBAction)onClickSignInButton:(id)sender {
    if (self.liveClient.session == nil)
    {
        [self.liveClient login:self
                        scopes:[NSArray arrayWithObjects:@"wl.signin", nil ]
                      delegate:self
                     userState:@"signin"];
    }
    else
    {
        [self.liveClient logoutWithDelegate:self
                                  userState:@"signout"];
    }
}

- (void) authCompleted:(LiveConnectSessionStatus)status
               session:(LiveConnectSession *)session
             userState:(id)userState
{
    [self updateButtons];
    if (session != nil) {
        self.statusLabel.text = @"You are signed in.";
    }
}

- (void) authFailed:(NSError *)error userState:(id)userState
{
    // Failed.
}

- (void) updateButtons {
    LiveConnectSession *session = self.liveClient.session;
    NSString *signInButtonText = (session == nil)? @"Sign in": @"Sign out";
    [self.signInButton setTitle:signInButtonText
                       forState:UIControlStateNormal];
}

In this example, it is assumed that a UIButton object named signInButton has already been declared, synthesized, and connected to the onClickSignInButton method. This button, when clicked, calls the LiveConnectClient variable's login:scopes:delegate:userState method as before. The userState parameter, when set to @"signin", is used to confirm the sign-in process in the authCompleted:session:userState method as before.

After sign-in, you could use the wl.basic scope in this example to call a getMe method to greet the user by name. The code would look like this.

ObjectiveC
- (void) getMe
{
    if (self.liveClient) {
        [self.liveClient getWithPath:@"me"
                            delegate:self
                           userState:@"me"];
        [self.liveClient getWithPath:@"me/picture"
                            delegate:self
                           userState:@"me-picture"];
    }
}

- (void) liveOperationSucceeded:(LiveOperation *)operation
{
    if ([operation.userState isEqual:@"me"]) {
        self.nameLabel.text = [operation.result objectForKey:@"name"];
        self.genderLabel.text = [operation.result objectForKey:@"gender"];
        self.profileLinkLabel.text = [operation.result objectForKey:@"link"];
    }
    if ([operation.userState isEqual:@"me-picture"]) {
        NSString *location = [operation.result objectForKey:@"location"];
        if (location) {
            NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:location]];
            self.profilePictureView.image = [UIImage imageWithData:data];
        }
    }
}

In this example, the LiveConnectClient variable's getWithPath:delegate:userState method calls the Live Connect APIs to get info about the signed-in user. If the call is successful, this code is part of a larger interface that implements the LiveOperationDelegate interface, which means its liveOperationSucceeded method is called if successful; otherwise the liveOperationFailed:operation method is called. Note that you can set the userState property, to @"me" or @"me-picture" to find the correct logic to call to get the user's name, gender, and profile link, and to get the user's profile picture, and to display them in the correct controls.

Java

If you're writing an Android app, you can sign the user in when the app starts. Here's how.

Java
package com.live.dev;

import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
import java.util.Arrays;
import com.microsoft.live.LiveAuthException;
import com.microsoft.live.LiveAuthListener;
import com.microsoft.live.LiveAuthClient;
import com.microsoft.live.LiveConnectSession;
import com.microsoft.live.LiveConnectClient;
import com.microsoft.live.LiveStatus;

public class JavaCodeSample extends Activity implements LiveAuthListener {

    private LiveAuthClient auth;
    private LiveConnectClient client;
    private TextView resultTextView;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        this.resultTextView = (TextView)findViewById(R.id.resultTextView);
        this.auth = new LiveAuthClient(this, MyConstants.APP_CLIENT_ID);
    }

    @Override
    protected void onStart() {
        super.onStart();
        Iterable<String> scopes = Arrays.asList("wl.signin", "wl.basic");
        this.auth.login(scopes, this);
    }

    public void onAuthComplete(LiveStatus status, LiveConnectSession session, Object userState) {
        if(status == LiveStatus.CONNECTED) {
            this.resultTextView.setText("Signed in.");
            client = new LiveConnectClient(session);
        }
        else {
            this.resultTextView.setText("Not signed in.");
            client = null;
        }
    }

    public void onAuthError(LiveAuthException exception, Object userState) {
        this.resultTextView.setText("Error signing in: " + exception.getMessage());
        client = null;
    }
}

In this example, the LiveAuthListener interface's onAuthComplete and onAuthError methods determine whether the user successfully signed in and consented to the requested scopes.

You can also start the sign-in process from a different control, like a button. Here's the relevant code.

Java
public void moreScopes() {
    auth.login(this, Arrays.asList(new String[] { "wl.basic" }), new LiveAuthListener() {
        public void onAuthComplete(LiveStatus status, LiveConnectSession session, Object userState) {
            if (status == LiveStatus.CONNECTED) {
                resultTextView.setText("Signed in.");
                client = new LiveConnectClient(session);
            } else {
                resultTextView.setText("Not signed in.");
                client = null;
            }
        }
        public void onAuthError(LiveAuthException exception, Object userState) {
            resultTextView.setText("Error signing in: " + exception.getMessage());
            client = null;
        }
    });
}

In this example, the LiveAuthClient variable named auth represents the sign-in and consent process. The initialize method starts the sign-in and consent process. If this process succeeds, the LiveConnectSession argument variable named session represents the sign-in session, and the LiveConnectClient variable named client represents the connection to this session.

After sign-in, you could use the wl.basic scope in this example, along with the LiveConnectClient variable named client and the getAsync method, to greet the user by name. The code would look like this.

Java
public void greetUser() {
    client.getAsync("me", new LiveOperationListener() {
        public void onComplete(LiveOperation operation) {
            JSONObject result = operation.getResult();
            resultTextView.setText("Hello, " + result.optString("name") + "!");
        }
        public void onError(LiveOperationException exception, LiveOperation operation) {
            resultTextView.setText("Error getting name: " + exception.getMessage());
        }
    });
}

In this example, the getAsync method calls the Live Connect APIs to get info about the signed-in user. If the getAsync method successfully calls the Live Connect APIs, the user's first name and last name are displayed.

REST

If you're coding directly in REST, your app must begin by initiating the user authentication and consent process at our OAuth web service endpoint. To do this, direct the user to the following URL. (In this example we're using the authorization code grant flow.)

https://login.live.com/oauth20_authorize.srf?client_id=CLIENT_ID&scope=SCOPES&response_type=code&redirect_uri=REDIRECT_URL

In the preceding example, notice that you add the parameters client_id, scope, response_type, and redirect_uri to the query string. The client ID (represented here by CLIENT_ID) is the one that you received when you registered your app in the Live Connect app management site. The value of the scope parameter depends on the type of information that you want to access. (For a complete list of the different types of info that you can request to access by using Live Connect, see Scopes and permissions.) The value of the response_type parameter is set to code, which requests an authorization code. The value of the redirect_uri parameter (represented here by REDIRECT_URL) is the URL that Live Connect returns users to after they sign in.

Here's an example of an actual URL.

https://login.live.com/oauth20_authorize.srf?client_id=00000000603E1700&scope=wl.signin%20wl.basic&response_type=code&redirect_uri=http%3A%2F%2Fwww.contoso.com%2Fcallback.htm

After the user successfully signs in and consents to the requested scopes, the Live Connect authorization web service uses the value of the redirect Uniform Resource Identifier (URI) to return the user to your site, and gives your app an authorization code as represented here by the string of characters that follow ?code=.

http://www.contoso.com/callback.htm?code=2bd12503-7e88-bfe7-c5c7-82274a740ff

You can now use this authorization code to obtain an access token—the unique string of characters that allows your app to get a user's info from a service that is compatible with Live Connect. To request an access token, your app must include its client ID, a redirect URI, its client secret, the authorization code, and the grant_type parameter set to authorization_code, like this.

POST https://login.live.com/oauth20_token.srf

Content-type: application/x-www-form-urlencoded

client_id=CLIENT_ID&redirect_uri=REDIRECT_URL&client_secret=CLIENT_SECRET&code=AUTHORIZATION_CODE&grant_type=authorization_code

Note that for web apps, the domain portion of the redirect URI here must match the domain portion of the redirect URI that you specified when you requested your client ID on the Live Connect app management site.

Here's an example that includes an actual URL.

POST https://login.live.com/oauth20_token.srf

Content-type: application/x-www-form-urlencoded

client_id=00000000603E1700&redirect_uri=http%3A%2F%2Fwww.contoso.com%2Fcallback.htm&client_secret=MdIepdja8Qkopfrsy8kzmHkU2VEKCLLo&code=2bd12503-7e88-bfe7-c5c7-82274a740ff&grant_type=authorization_code

If this REST call succeeds, the response from the Live Connect authorization web service contains a JSON-formatted object that contains the access token represented by the string of characters that follows "access_token":. (Note that the access token doesn't include the beginning and ending quotation marks.) The JSON-formatted object looks similar to the following (except that the particularly long access token string is shortened here for readability).

{
    "access_token":"EwBQ... ...AA==",
    "authentication_token":"eyJh... ...kdcs";
    "expires_in":3600,
    "scope":"wl.signin wl.basic",
    "token_type":"bearer"
}

Note The access token is valid for only the number of seconds that is specified in the expires_in structure.

At this point, you can use the Live Connect REST API to request user info. For each request, you must append an access_token parameter that contains the access token, where REST_PATH represents the REST path (like me), and ACCESS_TOKEN represents the actual access token. Here's an example of the URL syntax.

https://apis.live.net/v5.0/REST_PATH?access_token=ACCESS_TOKEN

And here's an example of an actual URL (with the access token string shortened again for readability):

https://apis.live.net/v5.0/me?access_token=EwBQ... ...AA==

If this REST call succeeds, the response from Live Connect contains a JSON-formatted object that contains the user's public info. The JSON-formatted object looks similar to the following.

{
   "id": "b6b2a7e8f2515e5",
   "name": "Apurva Dalia",
   "first_name": "Apurva",
   "last_name": "Dalia",
   "link": "http://cid-b6b2a7e8f2515e5.profile.live.com/",
   "gender": null,
   "locale": "en_US",
   "updated_time": "2011-08-02T21:13:05+0000"
}

You can use your JSON-compatible API of choice to parse these results as needed and work with them from there. (Our JavaScript, Objective-C, Java, and C# APIs provide JSON-friendly methods and shortcuts to help you parse these results.)

Top

Hotmail: contacts and calendars

Users store a lot of contacts and calendar events in Hotmail. Enabling users to access their contacts and events from your app can help you build a strong connection with them, encouraging them to use your app often and to share it with their friends. You can use the Live Connect APIs to do the following things in Hotmail:

  • Create new contacts, and read existing ones, in a user's contacts list.
  • Create, read, update, and delete a user's calendars and the calendars' associated events.
  • Subscribe a user to a public calendar, such as a list of holidays.
  • Use the friend finder feature to discover whether any of a users' contacts are also registered users of your website.

Note For user privacy reasons, we do not provide access to the email and address info of a user's contacts.

In this section, we'll briefly show JavaScript, C#, Objective-C, Java, and REST code examples for creating a new contact and for deleting a calendar. Unless otherwise noted in these code examples, we assume here that the user has already signed in and consented to the wl.contacts_create and wl.calendars_update scopes. For more info, scenarios, and code examples, see Hotmail (contacts and calendars).

Creating a new contact

To create a new contact by using JavaScript, you use code like this.

JavaScript
function createContact_onClick() {
    WL.login({
        scope: "wl.contacts_create"
    }).then(
        function (response) {
            WL.api({
                path: "me/contacts",
                method: "POST",
                body: {
                    first_name: "William",
                    last_name: "Flash"
                }
            }).then(
                function (response) {
                    document.getElementById("resultDiv").innerHTML =
                        "ID: " + response.id +
                        "<br/> Name: " + response.first_name +
                        " " + response.last_name;
                },
                function (responseFailed) {
                    document.getElementById("infoArea").innerText =
                        "Error calling API: " + responseFailed.error.message;
                }
            );
        },
        function (responseFailed) {
            document.getElementById("infoArea").innerText =
                "Error signing in: " + responseFailed.error_description;
        }
    );
}

In this example, in the call to WL.api, the path me/contacts represents the signed-in user's contacts list. The HTTP POST method is used to post the new contact's info. The anonymous methods following .then with the response and responseFailed parameters determine whether the Live Connect APIs are successfully called, and if so, display some info about the new contact.

In C#, you use code like the following.

[C# for Windows Store apps]

C#
private async void btnCreateContact_Click(object sender, RoutedEventArgs e)
{
    try
    {
        var contact = new Dictionary<string, object>();
        contact.Add("first_name", "Roberto");
        contact.Add("last_name", "Tamburello");
        LiveConnectClient liveClient = new LiveConnectClient(this.session);
        LiveOperationResult operationResult = await liveClient.PostAsync("me/contacts", contact);
        dynamic result = operationResult.Result;
        this.infoTextBlock.Text = string.Join(" ", "Contact:", result.name, "ID:", result.id);
    }
    catch (LiveConnectException exception)
    {
        this.infoTextBlock.Text = "Error creating contact: " + exception.Message;
    }
}

In this example, the PostAsync method is used to post the new contact's info. The PostAsync method determines whether the Live Connect APIs are successfully called, and if so, displays some info about the new contact.

[C# for Windows Phone apps]

C#
private void btnCreateContact_Click(object sender, RoutedEventArgs e)
{
    LiveConnectClient createContact = new LiveConnectClient(session);
    var contact = new Dictionary<string, object>();
    contact.Add("first_name", "Roberto");
    contact.Add("last_name", "Tamburello");
    createContact.PostCompleted +=
        new EventHandler<LiveOperationCompletedEventArgs>(CreateContactProperties_PostCompleted);
    createContact.PostAsync("me/contacts", contact);
}

void CreateContactProperties_PostCompleted(object sender, LiveOperationCompletedEventArgs e)
{
    if (e.Error == null)
    {
        infoTextBlock.Text = "Contact" +
            e.Result["first_name"].ToString() + " " + e.Result["last_name"].ToString() +
            " created with ID " +
            e.Result["id"].ToString();
    }
    else
    {
        infoTextBlock.Text = "Error calling API: " + e.Error.ToString();
    }
}

In this example, the PostAsync method is used to post the new contact's info. The PostCompleted event handler named CreatContactProperties_PostCompleted determines whether the Live Connect APIs are successfully called, and if so, displays some info about the new contact.

In Objective-C, you use code like the following.

ObjectiveC
- (void) createContact
{
    NSString *firstName = firstNameTextField.text;
    NSString *lastName = lastNameTextField.text;
    NSDictionary *postBody = [NSDictionary dictionaryWithObjectsAndKeys:
                              firstName, @"first_name",
                              lastName, @"last_name", nil];
    [self.liveClient postWithPath:@"me/contacts"
                         dictBody:postBody
                         delegate:self
                        userState:@"create contact"];
}

- (void) liveOperationSucceeded:(LiveOperation *)operation
{
    if ([operation.userState isEqual:@"create contact"]) {
        NSString *contactId = [operation.result objectForKey:@"id"];
        NSString *firstName = [operation.result objectForKey:@"first_name"];
        NSString *lastName = [operation.result objectForKey:@"last_name"];
        self.statusLabel.text = [NSString stringWithFormat: @"The contact(id: %@, first_name: %@, last_name: %@) was created.", contactId, firstName, lastName];
    }
}

- (void) liveOperationFailed:(NSError *)error
                   operation:(LiveOperation *)operation
{
    if ([operation.userState isEqual:@"create contact"]) {
        self.statusLabel.text = @"The contact creation failed.";
    }
}

In this example, the postWithPath:dictBody:delegate:userState method is used to post the new contact's info. The liveOperationSucceeded and liveOperationfailed:operation methods determine whether the Live Connect APIs are successfully called, and if so, displays some info about the new contact.

In Java, you use code like the following.

Java
public void createContact() {
    JSONObject contact = new JSONObject();
    try {
        contact.put("first_name", "Roberto");
        contact.put("last_name", "Tamburello");
    } catch (JSONException e) {
        resultTextView.setText("Error building contact: " + e.getMessage());
        return;
    }
    client.postAsync("me/contacts", contact, new LiveOperationListener() {
        public void onComplete(LiveOperation operation) {
            JSONObject result = operation.getResult();
            resultTextView.setText("Contact created. Contact ID = " + result.optString("id") +
                ", name = " + result.optString("name"));
        }
        public void onError(LiveOperationException exception, LiveOperation operation) {
            resultTextView.setText("Error creating contact: " + exception.getMessage());
        }
    });
}

In this example, the postAsync method is used to post the new contact's info. The onComplete and onError methods determine whether the Live Connect APIs are successfully called, and if so, display some info about the new contact.

In REST, you use code like the following, where POST is the HTTP method, Authorization and Content-Type are the request headers, ACCESS_TOKEN represents your actual access token, and the content starting with the left brace ("{") and ending with the right brace ("}") is the request body.

POST https://apis.live.net/v5.0/me/contacts

Authorization: Bearer ACCESS_TOKEN
Content-Type: application/json

{
    "first_name": "Roberto",
    "last_name": "Tamburello"
}

Deleting a calendar

To delete a calendar by using JavaScript, you use code like this.

JavaScript
function onDeleteCalendar() {
    WL.login({
        scope: "wl.calendars_update"
    }).then(
        function (response) {
            WL.api({
                path: "calendar.a6b2a7e8f2515e5e.11a088a04c28495e8672ecf2bf645461",
                method: "DELETE"
            }).then(
                function (response) {
                    document.getElementById("resultDiv").innerHTML = "Deleted.";
                },
                function (responseFailed) {
                    document.getElementById("infoArea").innerText =
                        "Error calling API: " + responseFailed.error.message;
                }
            );
        },
        function (responseFailed) {
            document.getElementById("infoArea").innerText =
                "Error signing in: " + responseFailed.error_description;
        }
    );
}

In this example, the calendar ID identifies the calendar to be deleted. The HTTP DELETE method is used to delete the calendar. The anonymous methods following .then with the response and responseFailed parameters determine whether the Live Connect APIs are successfully called, and if so, display a confirmation message.

In C#, you use code like this.

[C# for Windows Store apps]

C#
private async void btnDeleteCalendar_Click(object sender, RoutedEventArgs e)
{
    try
    {
        LiveConnectClient liveClient = new LiveConnectClient(this.session);
        LiveOperationResult operationResult =
            await liveClient.DeleteAsync("calendar.a6b2a7e8f2515e5e.212e9b5c4fce4662bfda971a10519b8b");
        this.infoTextBlock.Text = "Calendar deleted.";
    }
    catch (LiveConnectException exception)
    {
        this.infoTextBlock.Text = "Error deleting calendar: " + exception.Message;
    }
}

In this example, the DeleteAsync method is used to delete the calendar. The DeleteAsync method determines whether the Live Connect APIs are successfully called, and if so, displays a confirmation message.

[C# for Windows Phone apps]

C#
private void btnDeleteCalendar_Click(object sender, RoutedEventArgs e)
{
    LiveConnectClient deleteCalendar = new LiveConnectClient(session);
    deleteCalendar.DeleteCompleted +=
        new EventHandler<LiveOperationCompletedEventArgs>(DeleteCalendar_DeleteCompleted);
    deleteCalendar.DeleteAsync("calendar.8c8ce076ca27823f.8315cd6909b241f29f22c25f75d717b6");
}

void DeleteCalendar_DeleteCompleted(object sender, LiveOperationCompletedEventArgs e)
{
    if (e.Error == null)
    {
        infoTextBlock.Text = "Deleted.";
    }
    else
    {
        infoTextBlock.Text = "Error calling API: " + e.Error.ToString();
    }
}

In this example, the DeleteAsync method is used to delete the calendar. The DeleteCompleted event handler named DeleteCalendar_DeleteCompleted determines whether the Live Connect APIs are successfully called, and if so, displays a confirmation message.

In Objective-C, you use code like the following.

ObjectiveC
- (void) deleteCalendar
{
    NSString *calendarId = @"calendar.1234567890";
    [liveClient deleteWithPath:calendarId
                      delegate:self
                     userState:@"delete calendar"];
}

- (void) liveOperationSucceeded:(LiveOperation *)operation
{
    if ([operation.userState isEqual:@"delete calendar"]) {
        self.statusLabel.text = [NSString stringWithFormat: @"The calendar (%@) was deleted.", operation.path];
    }
}

- (void) liveOperationFailed:(NSError *)error
                   operation:(LiveOperation *)operation
{
    if ([operation.userState isEqual:@"delete calendar"]) {
        self.statusLabel.text = @"The request to delete the calendar failed.";
    }
}

In this example, the deleteWithPath:delegate:userState method is used to delete the calendar. The liveOperationSucceeded and liveOperationfailed:operation methods determine whether the Live Connect APIs are successfully called, and if so, display a confirmation message.

In Java, you use code like the following.

Java
public void deleteCalendar() {
    client.deleteAsync("calendar.a6b2a7e8f2515e5e.f69bbd89e2cd42859a8e44a36f9e8f7d", new LiveOperationListener() {
        public void onComplete(LiveOperation operation) {
            resultTextView.setText("Calendar deleted.");
        }
        public void onError(LiveOperationException exception, LiveOperation operation) {
            resultTextView.setText("Error deleting calendar: " + exception.getMessage());
        }
    });
}

In this example, the deleteAsync method is used to delete the calendar. The onComplete and onError methods determine whether the Live Connect APIs are successfully called, and if so, display a confirmation message.

With REST, you use code like this.

DELETE https://apis.live.net/v5.0/calendar.407a520a616e43438ab87875b064c290?access_token=ACCESS_TOKEN

Top

SkyDrive: files and photos

Users store a lot of documents and media on SkyDrive. Enabling users to access their documents and media from your app can help increase the time they spend using your app and encourage them to share your app with their contacts. You can use the Live Connect APIs to do the following things in SkyDrive:

  • Create, read, update, and delete folders and albums. (An album is a special type of SkyDrive folder that's designed to work especially well with photo and video files.)
  • Upload and download files.
  • Read and update file properties.
  • Get an embedded link, a read-only link, or a read-write link, to a folder or a file. (An embedded link is a small amount of HTML code that you can embed in a webpage; it enables users to work with a folder or file in SkyDrive from directly within that webpage.)
  • Move and copy folders and files.
  • Read tags that users add to photos and videos.
  • Read comments that users add to folders, files, albums, photos, videos, and audio files.

In this section, we'll briefly show JavaScript, C#, Objective-C, Java, and REST code examples for reading a folder's properties and for moving a file from one folder to another. Unless otherwise noted in these code examples, we assume here that the user has already signed in and consented to the wl.skydrive scope (for reading a folder's properties) or to the wl.skydrive_update scope (for moving a file). For more info, scenarios, and code examples, see SkyDrive (files and photos).

Reading a folder's properties

To read a folder's properties by using JavaScript, you use code like this.

JavaScript
function readFolderProperties_onClick() {
    WL.login({
        scope: "wl.skydrive"
    }).then(
        function (response) {
            WL.api({
                path: "folder.a6b2a7e8f2515e5e.A6B2A7E8F2515E5E!164",
                method: "GET"
            }).then(
                function (response) {
                    document.getElementById("infoArea").innerText =
                        "Folder properties: name = " + response.name + ", ID = " + response.id;
                },
                function (responseFailed) {
                    document.getElementById("infoArea").innerText =
                        "Error reading folder properties: " + responseFailed.error.message;
                }
            );
        },
        function (responseFailed) {
            document.getElementById("infoArea").innerText =
                "Error signing in: " + responseFailed.error_description;
        }
    );
}

In this example, the folder ID identifies the folder of which you want to read the properties. The HTTP GET method is used to get the folder's properties. The anonymous methods following .then with the response and responseFailed parameters determine whether the Live Connect APIs are successfully called, and if so, display some of the folder's properties.

In C#, you use code like this.

[C# for Windows Store apps]

C#
private async void btnReadFolder_Click(object sender, RoutedEventArgs e)
{
    try
    {
        LiveConnectClient liveClient = new LiveConnectClient(this.session);
        LiveOperationResult operationResult =
            await liveClient.GetAsync("folder.8c8ce076ca27823f.8C8CE076CA27823F!126");
        dynamic result = operationResult.Result;
        infoTextBlock.Text = "Folder name: " + result.name + ", ID: " + result.id;
    }
    catch (LiveConnectException exception)
    {
        infoTextBlock.Text = "Error getting folder info: " + exception.Message;
    }
}

In this example, the GetAsync method is used to get the folder's properties. The GetAsync method determines whether the Live Connect APIs are successfully called, and if so, displays some of the folder's properties.

[C# for Windows Phone apps]

C#
private void btnGetFolderProperties_Begin(object sender, RoutedEventArgs e)
{
    if (session == null)
    {
        infoTextBlock.Text = "You must sign in first.";
    }
    else
    {
        LiveConnectClient client = new LiveConnectClient(session);
        client.GetCompleted +=
            new EventHandler<LiveOperationCompletedEventArgs>(getFolderProperties_Completed);
        client.GetAsync("folder.8c8ce076ca27823f.8C8CE076CA27823F!158");
    }
}

void getFolderProperties_Completed(object sender, LiveOperationCompletedEventArgs e)
{
    if (e.Error == null)
    {
        IDictionary<string, object> folder = e.Result;
        infoTextBlock.Text = "Folder name: " + folder["name"].ToString() +
            "\nID: " + folder["id"].ToString();
    }
    else
    {
        infoTextBlock.Text = "Error calling API: " + e.Error.Message;
    }
}

In this example, the GetAsync method is used to get the folder's properties. The GetCompleted event handler named getFolderProperties_Completed determines whether the Live Connect APIs are successfully called, and if so, displays some of the folder's properties.

In Objective-C, you use code like the following.

ObjectiveC
- (void) getFolderInfo
{
    NSString *folderId = @"folder.2e82e8a5445fe036";
    [self.liveClient getWithPath:folderId
                        delegate:self
                       userState:@"get folder"];
}

- (void) liveOperationSucceeded:(LiveOperation *)operation
{
    if ([operation.userState isEqual:@"get folder"]) {
        self.folderIdLabel.text = [operation.result objectForKey:@"id"];
        self.folderNameLabel.text = [operation.result objectForKey:@"name"];
        self.folderUploadPathLabel.text = [operation.result objectForKey:@"upload_location"];
        self.folderLinkLabel.text = [operation.result objectForKey:@"link"];
        self.folderTypeLabel.text = [operation.result objectForKey:@"type"];
    };
}

- (void) liveOperationFailed:(NSError *)error
                   operation:(LiveOperation *)operation
{
    if ([operation.userState isEqual:@"get folder"]) {
        self.statusLabel.text = @"The request to read the SkyDrive folder information failed.";
    };
}

In this example, the getWithPath:delegate:userState method is used to get the folder's properties. The liveOperationSucceeded and liveOperationfailed:operation methods determine whether the Live Connect APIs are successfully called, and if so, display some of the folder's properties.

In Java, you use code like the following.

Java
public void readFolder() {
    client.getAsync("folder.a6b2a7e8f2515e5e.A6B2A7E8F2515E5E!125", new LiveOperationListener() {
        public void onComplete(LiveOperation operation) {
            JSONObject result = operation.getResult();
            resultTextView.setText("Folder ID = " + result.optString("id") +
                ", name = " + result.optString("name"));
        }
        public void onError(LiveOperationException exception, LiveOperation operation) {
            resultTextView.setText("Error reading folder: " + exception.getMessage());
        }
    });
}

In this example, the getAsync method is used to get the folder's properties. The onComplete and onError methods determine whether the Live Connect APIs are successfully called, and if so, display some of the folder's properties.

With REST, you use code like this.

GET http://apis.live.net/v5.0/folder.a6b2a7e8f2515e5e.A6B2A7E8F2515E5E!114?access_token=ACCESS_TOKEN

Moving a file from one folder to another

To move a file by using JavaScript, you use code like this.

JavaScript
function moveFile_onClick() {
    WL.login({
        scope: "wl.skydrive_update"
    }).then(
        function (response) {
            WL.api({
                path: "file.a6b2a7e8f2515e5e.A6B2A7E8F2515E5E!141",
                method: "MOVE",
                body: {
                    destination: "folder.a6b2a7e8f2515e5e.A6B2A7E8F2515E5E!125"
                }
            }).then(
                function (response) {
                    document.getElementById("infoArea").innerText = "Item moved.";
                },
                function (responseFailed) {
                    document.getElementById("infoArea").innerText =
                        "Error calling API: " + responseFailed.error.message;
                }
            );
        },
        function (responseFailed) {
            document.getElementById("infoArea").innerText =
                "Login error: " + responseFailed.error_description;
        }
    );
}

In this example, the file ID and folder ID identify the file to be moved and the folder to move the file to. The HTTP MOVE method is used to move the file. The anonymous methods following .then with the response and responseFailed parameters determine whether the Live Connect APIs are successfully called, and if so, display a confirmation message.

In C#, you use code like this.

[C# for Windows Store apps]

C#
private async void btnMoveFile_Click(object sender, RoutedEventArgs e)
{
    try
    {
        LiveConnectClient moveFileClient = new LiveConnectClient(this.session);
        LiveOperationResult operationResult =
            await moveFileClient.MoveAsync("file.9d24497f7fef8f33.9D24497F7FEF8F33!748",
                "folder.9d24497f7fef8f33.9D24497F7FEF8F33!265");
        this.infoTextBlock.Text = "File moved.";
    }
    catch (LiveConnectException exception)
    {
        this.infoTextBlock.Text = "Error moving file: " + exception.Message;
    }
}

In this example, the MoveAsync method is used to move the file. The MoveAsync method determines whether the Live Connect APIs are successfully called, and if so, displays a confirmation message.

[C# for Windows Phone apps]

C#
private void btnMoveFile_Begin(object sender, RoutedEventArgs e)
{
    if (session == null)
    {
        infoTextBlock.Text = "You must sign in first.";
    }
    else
    {
        LiveConnectClient client = new LiveConnectClient(session);
        client.MoveCompleted +=
            new EventHandler<LiveOperationCompletedEventArgs>(MoveFile_MoveCompleted);
        client.MoveAsync("file.8c8ce076ca27823f.8C8CE076CA27823F!138",
            "folder.8c8ce076ca27823f");
    }
}

void MoveFile_MoveCompleted(object sender, LiveOperationCompletedEventArgs e)
{
    if (e.Error == null)
    {
        infoTextBlock.Text = "File or folder move completed.";
    }
    else
    {
        infoTextBlock.Text = "Error calling API: " + e.Error.ToString();
    }
}

In this example, the MoveAsync method is used to move the file. The MoveCompleted event handler named MoveFile_MoveCompleted determines whether the Live Connect APIs are successfully called, and if so, displays a confirmation message.

In Objective-C, you use code like the following.

ObjectiveC
- (void) moveFile
{
    NSString *folderId = @"folder.2e82e8a5445fe036";
    NSString *fileId = @"file.445fe0362e82e8a5";
    [self.liveClient moveFromPath:fileId
                    toDestination:folderId
                         delegate:self
                        userState:@"move a file"];
}

- (void) liveOperationSucceeded:(LiveOperation *)operation
{
    if ([operation.userState isEqual:@"get folders"]) {
        self.statusLabel.text = @"Skydrive folders are loaded.";
    }
    if ([operation.userState isEqual:@"get folder"]) {
    };
    if ([operation.userState isEqual:@"move a file"]) {
        self.statusLabel.text = [NSString stringWithFormat: @"The file (id: %@) was moved successfully.", operation.path];
    };
}

In this example, the moveFromPath:toDestination:delegate:userState method is used to move the file. The liveOperationSucceeded method determines whether the Live Connect APIs are successfully called, and if so, displays a confirmation message.

In Java, you use code like the following.

Java
public void moveFile() {
    client.moveAsync("file.a6b2a7e8f2515e5e.A6B2A7E8F2515E5E!120",
            "folder.a6b2a7e8f2515e5e.A6B2A7E8F2515E5E!145", new LiveOperationListener() {
        public void onComplete(LiveOperation operation) {
            resultTextView.setText("File moved.");
        }
        public void onError(LiveOperationException exception, LiveOperation operation) {
            resultTextView.setText("Error moving file: " + exception.getMessage());
        }
    });
}

In this example, the moveAsync method is used to move the file. The onComplete and onError methods are used to determine whether the Live Connect APIs are successfully called, and if so, display a confirmation message.

With REST, you use code like this.

MOVE https://apis.live.net/v5.0/file.a6b2a7e8f2515e5e.A6B2A7E8F2515E5E!126

Authorization: Bearer ACCESS_TOKEN
Content-Type: application/json

{
    "destination": "folder.a6b2a7e8f2515e5e.A6B2A7E8F2515E5E!114"
}

Top

Messenger: instant messaging

You can use XMPP, an open standard for real-time communication, to enable your apps to interact with a Messenger user and with his or her buddies.

To do this, your app must first follow the instructions in Getting started and Signing users in. After the user signs in and consents to the wl.messenger scope, your app receives an access token, which it must have to sign in to the Messenger XMPP service on behalf of the consenting user.

After your app signs in to the XMPP service, it can use a compatible XMPP library to do things like exchange instant messages with the user's buddies, communicate a user's current presence, and display a user's current status message. For details and code examples, see Messenger (instant messaging).

Top

Sharing status

Social apps should give users the opportunity to share what they're doing with their friends and contacts. Whether they are posting a collection of their latest vacation pictures, creating a reminder of an important event, or excited about the high game score they just achieved, users enjoy sharing what they're doing online. And the more they can share from within your app, the more likely they are to use it. Live Connect enables users to share their status with others.

In this section, we'll briefly show JavaScript, C#, Objective-C, Java, and REST code examples for sharing a video with others by means of a status message update. Unless otherwise noted in these code examples, we assume here that the user has already signed in and consented to the wl.share scope. For more info, scenarios, and code examples, see Sharing a user's status.

To share a video by using JavaScript, you use code like this.

JavaScript
function shareUserStatus_onClick() {
    WL.login({
        scope: "wl.share"
    }).then(
        function (response) {
            WL.api({
                path: "me/share",
                method: "POST",
                body: {
                    message: "Hello, Windows Live!"
                }
            }).then(
                function (response) {
                    document.getElementById("infoArea").innerText =
                        "Status: " + response.message;
                },
                function (responseFailed) {
                    document.getElementById("infoArea").innerText =
                        "Error calling API: " + responseFailed.error.message;
                }
            );
        },
        function (responseFailed) {
            document.getElementById("infoArea").innerText =
                "Error signing in: " + responseFailed.error_description;
        }
    );
}

In this example, the path me/share represents the signed-in user's status message queue. The HTTP POST method is used to post the new status message. The anonymous methods following .then with the response and responseFailed parameters determine whether the Live Connect APIs are successfully called, and if so, display a confirmation message.

In C#, you use code like this.

[C# for Windows Store apps]

C#
private async void btnShareStatus_Click(object sender, RoutedEventArgs e)
{
    try
    {
        var message = new Dictionary<string, object>();
        message.Add("message", "Hello, Windows Live!");
        LiveConnectClient liveClient = new LiveConnectClient(this.session);
        LiveOperationResult operationResult = await liveClient.PostAsync("me/share", message);
        dynamic result = operationResult.Result;
        this.infoTextBlock.Text = string.Join(" ", "Status", result.message, "shared with your friends.");
    }
    catch (LiveConnectException exception)
    {
        this.infoTextBlock.Text = "Error sharing status: " + exception.Message;
    }
}

In this example, the PostAsync method is used to post the new status message. The PostAsync method determines whether the Live Connect APIs are successfully called, and if so, displays a confirmation message.

[C# for Windows Phone apps]

C#
private void shareUserStatus_Click(object sender, RoutedEventArgs e)
{
    if (session == null)
    {
        infoTextBlock.Text = "You must sign in first.";
    }
    else
    {
        client = new LiveConnectClient(session);
        var status = new Dictionary<string, object>();
        status.Add("message", "Double Rainbow - Windows Live Photo Gallery");
        status.Add("link", "http://www.youtube.com/watch?v=8jXz7NrfzsI");
        status.Add("description", "Watch \"Double Rainbow Guy\" edit his pictures by using Windows Live Photo Gallery. (0:43)");
        status.Add("picture", "http://res2.explore.live.com/resbox/en/Live%20Explore/Main/2/f/2f70d4d7-1640-4414-9298-9957ab5e01c3/2f70d4d7-1640-4414-9298-9957ab5e01c3.png");
        status.Add("name", "Wow -- It's a Double Rainbow!");
        status.Add("source", "http://www.youtube.com/v/8jXz7NrfzsI?version=3");
        client.PostCompleted +=
            new EventHandler<LiveOperationCompletedEventArgs>(ShareUserStatus_PostCompleted);
        client.PostAsync("me/share", status);
    }
}

void ShareUserStatus_PostCompleted(object sender, LiveOperationCompletedEventArgs e)
{
    if (e.Error == null)
    {
        infoTextBlock.Text = "Activity shared.";
    }
    else
    {
        infoTextBlock.Text = "Error calling API: " + e.Error.ToString();
    }
}

In this example, the PostAsync method is used to post the new status message. The PostCompleted event handler named ShareUserStatus_PostCompleted determines whether the Live Connect APIs are successfully called, and if so, displays a confirmation message.

In Objective-C, you use code like the following.

ObjectiveC
- (void) shareStatus
{
    NSDictionary *postBody = [NSDictionary dictionaryWithObjectsAndKeys:
                              messageInputTextField.text, @"message",
                              nil];
    [self.liveClient postWithPath:@"me/share"
                         dictBody:postBody
                         delegate:self
                        userState:@"share status"];
}

- (void) liveOperationSucceeded:(LiveOperation *)operation
{
    if ([operation.userState isEqual:@"share status"]) {
        self.statusLabel.text = @"The message was posted successfully.";
    }
}

- (void) liveOperationFailed:(NSError *)error
                   operation:(LiveOperation *)operation
{
    if ([operation.userState isEqual:@"share status"]) {
        self.statusLabel.text = @"The message posting request failed.";
    }
}

In this example, the postWithPath:dictBody:delegate:userState method is used to post the new status message. The liveOperationSucceeded and liveOperationfailed:operation methods determine whether the Live Connect APIs are successfully called, and if so, display a confirmation message.

In Java, you use code like the following.

Java
public void shareUserStatus() {
    JSONObject status = new JSONObject();
    try {
        status.put("message", "Double Rainbow - Windows Live Photo Gallery");
        status.put("link", "http://www.youtube.com/watch?v=8jXz7NrfzsI");
        status.put("description", "Watch \"Double Rainbow Guy\" edit his pictures by using Windows Live Photo Gallery. (0:43)");
        status.put("picture", "http://res2.explore.live.com/resbox/en/Live%20Explore/Main/2/f/2f70d4d7-1640-4414-9298-9957ab5e01c3/2f70d4d7-1640-4414-9298-9957ab5e01c3.png");
        status.put("name", "Wow -- It's a Double Rainbow!");
        status.put("source", "http://www.youtube.com/v/8jXz7NrfzsI?version=3");
    } catch (JSONException e) {
        resultTextView.setText("Error building status message: " + e.getMessage());
        return;
    }
    client.postAsync("me/share", status, new LiveOperationListener() {
        public void onComplete(LiveOperation operation) {
            JSONObject result = operation.getResult();
            resultTextView.setText("Status shared. Message = " + result.optString("message"));
        }
        public void onError(LiveOperationException exception, LiveOperation operation) {
            resultTextView.setText("Error sharing status: " + exception.getMessage());
        }
    });
}

In this example, the postAsync method is used to post the new status message. The onComplete and onError methods determine whether the Live Connect APIs are successfully called, and if so, display a confirmation message.

With REST, you use code like this.

POST https://apis.live.net/v5.0/me/share

Authorization: Bearer ACCESS_TOKEN
Content-Type: application/json

{
    "message": "Double Rainbow - Windows Live Photo Gallery",
    "link": "http://www.youtube.com/watch?v=8jXz7NrfzsI",
    "description": "Watch \"Double Rainbow Guy\" edit his pictures by using Windows Live Photo Gallery. (0:43)",
    "picture": "http://res2.explore.live.com/resbox/en/Live%20Explore/Main/2/f/2f70d4d7-1640-4414-9298-9957ab5e01c3/2f70d4d7-1640-4414-9298-9957ab5e01c3.png",
    "name": "Wow -- It's a Double Rainbow!",
    "source": "http://www.youtube.com/v/8jXz7NrfzsI?version=3"
}

Top

Next steps

This guide has briefly introduced some of the basic features that are available to you in Live Connect. To learn more about what you can do to enrich your apps with the Live Connect APIs, explore these resources:

  • Live Connect Documentation (in the Live Connect Developer Center)—Descriptions of a variety of scenarios, each with code examples, that show you how to make the most of Live Connect.
  • Live Connect API reference—A collection of reference topics that provide details about our JavaScript, Objective-C, Java, and Managed APIs.
  • Live Interactive SDK—An online resource where you can see working code as it uses the Live Connect APIs in real time.

Top


Getting started

In this article

  • Identity API
  • Hotmail API
  • SkyDrive API
  • Messenger API
  • Learn more

Live Connect provides a set of APIs that enable your apps to work with info in Hotmail, Windows Live Messenger, Microsoft SkyDrive, and other services that are compatible with Live Connect. Here's what you can do with these APIs, how to get the settings that your apps need to call the APIs, and how to begin writing code to call the APIs.

Identity API

  • Profiles. Get a user's profile info. A profile includes info that a user provides about himself or herself, such as first name, last name, gender, and birth date.
  • Personalization. Enable a user to sign in to a website, personalize the signed-in user's experience on that website, and easily register a user on that website.

To learn more, see Identity (profiles).

Hotmail API

  • Contacts. Read and create contacts. You can also enable a website to determine which of a user's contacts is also a user of that website.
  • Calendars. Work with calendars and events.

To learn more, see Hotmail (contacts and calendars).

SkyDrive API

  • Folders, files, and more. Work with folders, files, albums, photos, videos, audio, tags, and comments.

To learn more, see SkyDrive (files and photos).

Messenger API

  • Instant messaging. Exchange instant messages between Messenger users.
  • Users and buddies. Get a user's info and his or her buddies' info, including things like their friendly names, presence info, and status messages.
  • Status updates. Update a user's status message, a personal message that the user chooses to share with others (for example, participating in a web-based game).

To learn more, see Messenger (instant messaging).

Top

Learn more

To get going, start here:

  • What's new

    What's new in the latest releases.

  • Configuring your app

    How to get the settings your apps need to begin calling the Live Connect APIs.

  • Windows Store apps

    How Windows Store apps can call the Live Connect APIs.

  • Windows Phone apps

    How Windows Phone apps can call the Live Connect APIs.

  • iOS apps

    How apps for the iOS operating system for Apple devices can call the Live Connect APIs.

  • Android apps

    How apps for the Google Android mobile technology platform can call the Live Connect APIs.

  • Web apps

    How client-side and server-side websites and scripts can call the Live Connect APIs.

  • Working with the code examples

    How to work with the smaller code examples throughout this documentation in the context of larger reference code samples.

  • Mobile and Windows desktop apps

    How mobile apps and Windows desktop apps can call the Live Connect APIs.

  • Community resources

    Links to helpful tools, code samples, blogs, and more.

Top


What's new

Here are the features and functionality that were added, removed, and changed for each release of Live Connect.

  • December 2012 release
  • August 2012 release
  • April 2012 release
  • December 2011 release
  • May 2011 release

December 2012 release

The December 2012 release of Live Connect adds or changes these features and functionality since the August 2012 release:

  • Live SDK update: The Live Software Development Kit (SDK) v5.3 for Windows and Windows Phone supports apps built to run on Windows 8 and Windows Phone 7.0, 7.5, and 8.0. For more info, see Live Connect Downloads and Referencing the APIs.
  • Live SDK for PHP

August 2012 release

The August 2012 release of Live Connect adds or changes these features and functionality since the April 2012 release:

  • Live SDK update: The Live SDK v5.2 for Windows and Windows Phone supports apps built to run on Windows 8 and Windows Phone 7.0 and 7.5. For more info, see Live Connect Downloads and Referencing the APIs.
  • Settings management: The Live Connect app management site and the Windows Store Dashboard restrict by default the issuing of JavaScript Object Notation (JSON) Web Tokens (JWTs) to Windows Store apps only. However, you can override this setting to enable the issuing of JWTs to all apps. For more info, see Single sign-on for apps and websites.
  • REST API: Updates to the Live Connect Representational State Transfer (REST) API include support for:
    • Getting available camera attributes—such as the camera's make and model, if they are available—for photos.
    • Getting previews of items in Microsoft SkyDrive by calling /get_item_preview with the url query parameter.
    • Getting multiple display resolutions (if they are available) for users' profile pictures by calling /picture with the type query parameter.
    • Getting a list of a user's recently-used documents in SkyDrive by calling /skydrive/recent_docs.
    • Using the overwrite query parameter to automatically rename a file as it's uploaded to SkyDrive, if a file with same file name already exists.
    • Using the download query parameter to instruct the user's web browser to prompt the user to save a file that SkyDrive is downloading, instead of having the web browser try to download and display the file directly in the browser.
    • Using the redirect_uri query parameter to instruct SkyDrive to notify a web browser after a file is uploaded. You can also use the state query parameter to attach a unique identifier to each upload request, so that you can identify a particular file if you are uploading multiple files in quick succession.
    For more info, see REST reference and SkyDrive core concepts.
  • JavaScript API (Windows 8 only): The WL.init method now provides an optional redirect_uri parameter that enables Windows Store apps using JavaScript to retrieve an authentication token for single sign-on scenarios. For more info, see WL.init and Single sign-on for apps and websites.
  • JavaScript API (web only):
    • Web apps that use our JavaScript API along with certain web browsers can use the WL.download, WL.upload, WL.ui, and WL.fileDialog functions to download and upload files from and to SkyDrive. The WL.fileDialog function is new; it enables web apps to display a robust and consistent UI for users to select files to download and upload to SkyDrive. For details, see Folders and files, WL.download (web), WL.upload (web), WL.ui, and WL.fileDialog (web).
    • The WL.login and WL.ui functions include a state parameter that can be used to track a web app's calling state on the server side. Note that this applies to the WL.ui function only when its name parameter is set to "signin". For more info, see WL.login and WL.ui.
  • Managed API (Windows 8 only): The Microsoft.Live.LiveAuthClient constructor now provides an overload that takes a string representing a redirect URI. This enables Windows Store apps using C# to retrieve an authentication token for single sign-on scenarios. For more info, see LiveAuthClient(String) constructor and Single sign-on for apps and websites.
  • Windows Phone apps: Apps built to run on Windows Phone 7.5 can use certain members of the LiveConnectClient class with SkyDrive to start file download and upload requests that should finish even if the app is suspended or quits (a feature also known as background transfer). Those members are the AttachPendingTransfers method, BackgroundDownloadAsync method, BackgroundDownloadCompleted event, BackgroundDownloadProgressChanged event, BackgroundUploadAsync method, BackgroundUploadCompleted event, and BackgroundUploadProgressChanged event. For more info, see Windows Phone apps, Folders and files, and the corresponding topics in LiveConnectClient class (Windows 8).
  • SkyDrive: There are no longer any restrictions on the types of files that can be programmatically uploaded to SkyDrive.
  • Breaking changes: The following are breaking changes since the April 2012 release:
    • JavaScript API (Windows 8 and web): The WL.ui method includes the onloggedin, onloggedout, and onerror parameters that specify the functions to call after the user successfully or unsuccessfully signs in or signs out by using the Live Connect sign-in button. The callback parameter is no longer used to handle user sign-in actions; instead, callback specifies the function to call after the button is initialized. For more info, see WL.ui.
    • JavaScript API (Windows 8 only): The names and parameters of the following methods have changed.
      Previous name | New name
      WL.download | WL.backgroundDownload
      WL.upload | WL.backgroundUpload

      For more info, see WL.backgroundDownload and WL.backgroundUpload.
    • Managed API (Windows 8 only):
      • The names of most of the methods in the Microsoft.Live.LiveAuthClient and Microsoft.Live.LiveConnectClient classes have changed, and the parameters of a few of these methods have also changed. Here are the method-name changes.
        Previous name | New name
        Microsoft.Live.LiveAuthClient.Initialize() | Microsoft.Live.LiveAuthClient.InitializeAsync()
        Microsoft.Live.LiveAuthClient.Initialize(IEnumerable<String>) | Microsoft.Live.LiveAuthClient.InitializeAsync(IEnumerable<String>)
        Microsoft.Live.LiveAuthClient.Login(IEnumerable<String>) | Microsoft.Live.LiveAuthClient.LoginAsync(IEnumerable<String>)
        Microsoft.Live.LiveConnectClient.Copy(String, String) | Microsoft.Live.LiveConnectClient.CopyAsync(String, String)
        Microsoft.Live.LiveConnectClient.Copy(String, String, CancellationToken) | Microsoft.Live.LiveConnectClient.CopyAsync(String, String, CancellationToken)
        Microsoft.Live.LiveConnectClient.Delete(String) | Microsoft.Live.LiveConnectClient.DeleteAsync(String)
        Microsoft.Live.LiveConnectClient.Delete(String, CancellationToken) | Microsoft.Live.LiveConnectClient.DeleteAsync(String, CancellationToken)
        Microsoft.Live.LiveConnectClient.Download(String) | Microsoft.Live.LiveConnectClient.BackgroundDownloadAsync(String)
        Microsoft.Live.LiveConnectClient.Download(String, CancellationToken, IProgress<LiveOperationProgress>) | Microsoft.Live.LiveConnectClient.BackgroundDownloadAsync(String, CancellationToken, IProgress<LiveOperationProgress>)
        Microsoft.Live.LiveConnectClient.Download(String, IStorageFile) | Microsoft.Live.LiveConnectClient.BackgroundDownloadAsync(String, IStorageFile)
        Microsoft.Live.LiveConnectClient.Download(String, IStorageFile, CancellationToken, IProgress<LiveOperationProgress>) | Microsoft.Live.LiveConnectClient.BackgroundDownloadAsync(String, IStorageFile, CancellationToken, IProgress<LiveOperationProgress>)
        Microsoft.Live.LiveConnectClient.Get(String) | Microsoft.Live.LiveConnectClient.GetAsync(String)
        Microsoft.Live.LiveConnectClient.Get(String, CancellationToken) | Microsoft.Live.LiveConnectClient.GetAsync(String, CancellationToken)
        Microsoft.Live.LiveConnectClient.Move(String, String) | Microsoft.Live.LiveConnectClient.MoveAsync(String, String)
        Microsoft.Live.LiveConnectClient.Move(String, String, CancellationToken) | Microsoft.Live.LiveConnectClient.MoveAsync(String, String, CancellationToken)
        Microsoft.Live.LiveConnectClient.Post(String, IDictionary<String, Object>) | Microsoft.Live.LiveConnectClient.PostAsync(String, IDictionary<String, Object>)
        Microsoft.Live.LiveConnectClient.Post(String, IDictionary<String, Object>, CancellationToken) | Microsoft.Live.LiveConnectClient.PostAsync(String, IDictionary<String, Object>, CancellationToken)
        Microsoft.Live.LiveConnectClient.Post(String, String) | Microsoft.Live.LiveConnectClient.PostAsync(String, String)
        Microsoft.Live.LiveConnectClient.Post(String, String, CancellationToken) | Microsoft.Live.LiveConnectClient.PostAsync(String, String, CancellationToken)
        Microsoft.Live.LiveConnectClient.Put(String, IDictionary<String, Object>) | Microsoft.Live.LiveConnectClient.PutAsync(String, IDictionary<String, Object>)
        Microsoft.Live.LiveConnectClient.Put(String, IDictionary<String, Object>, CancellationToken) | Microsoft.Live.LiveConnectClient.PutAsync(String, IDictionary<String, Object>, CancellationToken)
        Microsoft.Live.LiveConnectClient.Put(String, String) | Microsoft.Live.LiveConnectClient.PutAsync(String, String)
        Microsoft.Live.LiveConnectClient.Put(String, String, CancellationToken) | Microsoft.Live.LiveConnectClient.PutAsync(String, String, CancellationToken)
        Microsoft.Live.LiveConnectClient.Upload(String, String, IStorageFile) | Microsoft.Live.LiveConnectClient.BackgroundUploadAsync(String, String, IStorageFile)
        Microsoft.Live.LiveConnectClient.Upload(String, String, IStorageFile, Bool) | Microsoft.Live.LiveConnectClient.BackgroundUploadAsync(String, String, IStorageFile, Bool)
        Microsoft.Live.LiveConnectClient.Upload(String, String, IStorageFile, Bool, CancellationToken, IProgress<LiveOperationProgress>) | Microsoft.Live.LiveConnectClient.BackgroundUploadAsyncUpload(String, String, IStorageFile, Bool, CancellationToken, IProgress<LiveOperationProgress>)
        Microsoft.Live.LiveConnectClient.Upload(String, String, Stream) | Microsoft.Live.LiveConnectClient.BackgroundUploadAsync(String, String, IInputStream)
        Microsoft.Live.LiveConnectClient.Upload(String, String, Stream, Bool) | Microsoft.Live.LiveConnectClient.BackgroundUploadAsync(String, String, IInputStream, Bool)
        Microsoft.Live.LiveConnectClient.Upload(String, String, Stream, Bool, CancellationToken, IProgress<LiveOperationProgress>) | Microsoft.Live.LiveConnectClient.BackgroundUploadAsync(String, String, IInputStream, Bool, CancellationToken, IProgress<LiveOperationProgress>)

        For more info, see the corresponding topics in LiveAuthClient class (Windows 8) and LiveConnectClient class (Windows 8).
      • The following properties of the Microsoft.Live.LiveConnectSession class have been removed: Expires, RefreshToken, and Scopes.
    • Deprecation of Messenger Connect/Live Connect, v4.1: As was announced in June 2011, Live Connect v4.1 (formerly called Messenger Connect) has been deprecated, and as of June 25, 2012, the corresponding v4.1 APIs no longer work. For info about migrating your v4.1 apps to v5.0, see Migrating your Live Connect v4.1 app to v5.0.

Top

April 2012 release

The April 2012 release of Live Connect added or changed these features and functionality since the December 2011 release:

  • Live SDK update: The Live SDK v5.1 supports apps built to run on Windows 8 Consumer Preview and Windows Phone 7.0. For details, see Live SDK v5.1.
  • Migrating apps: We've created a quick-reference guide to help you move any of your apps that are based on Live Connect, v4.1 to this release. For details, see Migrating your Live Connect v4.1 app to v5.0.
  • Settings management: To get package identities for Windows Store apps, if you have a Windows Store registration code, you can use the Windows Store Dashboard. Otherwise, you can continue to use the Live Connect app management site for Windows Store apps. (The Live Connect app management site continues to be available for you to create and manage client IDs for app types other than Windows Store apps as well as manage associated settings for any of your existing client IDs and package identities.) For more info, see Configuring your app.
  • Support for additional app types: The Live Connect APIs now provide support for apps written in Objective-C and Java for the iOS operating system for Apple devices and the Google Android mobile technology platform, respectively, and can make coding for these app types easier than it is with only the REST API. For details, see iOS apps, Android apps, iOS API, Android API, Referencing the APIs, and REST reference.
  • Improved asynchronous coding: Windows Store apps using JavaScript and web apps can use the promise model and then method to make asynchronous programming easier than before. Windows Store apps using C# can use new keywords (for example, await, async, and dynamic), along with new Live Connect APIs methods, to help with asynchronous programming. You can also experiment with Windows Phone apps by trying out the await and async keywords, along with new methods (for example, Get instead of GetAsync), by using the unsupported Microsoft Visual Studio Async Community Technology Preview (CTP). Although we still support the programming patterns that were introduced in the December 2011 release for these app types, we are documenting only the new patterns and we strongly recommend that you use the new patterns as much as possible in these app types. For more info, see Windows Store apps, Windows Phone apps, Web apps, Referencing the APIs, JavaScript API (Windows 8 and web), and Managed API (Windows 8 and Windows Phone).
  • REST API: Updates to the Live Connect Representational State Transfer (REST) API include support for:
    • Uploading a display logo for a specific client ID.
    • Getting the email address that a user has associated with his or her Microsoft account.
    • Getting a user's SkyDrive storage quota info.
    • Getting more details about Audio objects.
    • Getting location coordinates for Photo objects.
    • Getting links to open Microsoft Office OneNote notebooks stored in SkyDrive.
    • Using human-readable names instead of folder IDs to access certain common SkyDrive folders, such as My Documents.
    • Creating and deleting comments and tags on various SkyDrive file types.
    For more info, see REST reference and SkyDrive core concepts.
  • OAuth 2.0: If your app makes direct calls to the Live Connect REST APIs for user authentication and for access and refresh token management, you'll want to change the base URL you're calling and make other minor updates to your calling syntax. Although we still support the former base URL and calling syntax for now, we strongly recommend that you use the new base URL and calling syntax as much as possible. For more info, see OAuth 2.0, Signing users in, and Server-side scenarios.
  • Breaking changes: The following are breaking changes since the December 2011 release.
    • Managed API (Windows 8 and Windows Phone):
      • The Microsoft.Live.LiveAuthClient(String, String) constructor that takes a client ID and a redirect Uniform Resource Identifier (URI) has been replaced with the Microsoft.Live.LiveAuthClient(String) constructor that takes a client ID only.
      • The Microsoft.Live.LiveAuthClient.ResponseType property has been removed.
      • The Microsoft.Live.Controls.SignInButton.RedirectUri property and Microsoft.Live.Controls.SignInButton.RedirectUriProperty property have been removed (applies to Windows Phone apps only).
    • JavaScript API (Windows 8 only): the WL.init function’s redirect_uri and response_type parameters have been removed.
    • Windows Live Messenger: All apps that interact with a Messenger user and the user's buddies by using Extensible Messaging and Presence Protocol (XMPP) must now support see-other-host. This is a breaking change since the December 2011 release. Apps that don't support see-other-host will no longer work. For details, see Getting started using Messenger with XMPP and Messenger XMPP reference.

Top

December 2011 release

The December 2011 release of Live Connect added or changed these features and functionality since the May 2011 release.

  • Contacts: Apps can create contacts. This is in addition to reading contact info and friend info in the previous release. For details, see Contacts (Live Connect API).
  • Calendar: Apps can create, read, update, and delete a Hotmail user's calendars and calendar events. Apps can also subscribe to publicly available calendars like holidays. For details, see Calendars (Live Connect API).
  • SkyDrive: Apps can create, read, update, and delete a SkyDrive user's folders, files, albums, photos, videos, and audio. Apps can also read comments and tags. For details, see SkyDrive (files and photos).
  • Messenger: Apps can exchange instant messages and interact with a Messenger user and the user's buddies by using XMPP, an open standard for real-time communication. For details, see Messenger (instant messaging).
  • Settings management: You can use the Live Connect app management site for Windows Store apps to create package identities for Windows Store apps. For details, see Configuring your app.
  • Support for additional app types. The Live Connect APIs now support Windows Store apps and Windows Phone apps. We continue to support client-side websites and scripts with JavaScript. For details, see Windows Store apps, Windows Phone apps, Web apps, Mobile and Windows desktop apps, Referencing the APIs, Managed API (Windows 8 and Windows Phone), JavaScript API (Windows 8 and web), and REST reference.

Top

May 2011 release

The May 2011 release of Live Connect (formerly known as Live Connect, Version 5.0) included these features and functionality:

  • OAuth 2.0: We support this open web authorization standard. This approach makes it easier for your apps to work with Hotmail, Messenger, SkyDrive, and other services that are compatible with Live Connect because it uses an authentication protocol that is also used by other web platforms like Facebook and Google. For details, see OAuth 2.0.
  • Single sign-on: When a user has signed in with their Microsoft account from Hotmail, SkyDrive, MSN, or elsewhere, they don't have to sign in again when they come to your website. For details, see Signing users in and Single sign-on for apps and websites.
  • Improved user experience: Compared to earlier releases, we're more explicit about each permission that the user grants to your app, which puts users in more control of their info. We also provide multiple versions of the UI where users give permission for apps to access their info. These UI options include a touch-friendly version. For details, see Obtaining user consent.
  • Profile: Apps can read a user's profile info. For details, see Identity (profiles).
  • Contacts: Apps can read a Hotmail user's contact and friend info. For details, see Contacts (Live Connect API). Apps can also determine which friends of a Hotmail user are also users of a website that both the user and the user's friends are members of. For details, see Friend finder.
  • Calendar: Apps can create events in a Hotmail user's default calendar. For details, see Calendars (Live Connect API).
  • Status updates: Apps can update a user's status message. For details, see Sharing a user's status.
  • SkyDrive: Apps can read a SkyDrive user's folder, album, photo, video, comment, and tag info. For details, see SkyDrive (files and photos).
  • App management: Compared to earlier releases, we simplified our Live Connect app management site. For details, see Configuring your app.
  • Easier coding and improved info transfer. Compared to earlier releases, we simplified our REST API by focusing on the JSON data format. At the same time, we decreased the average size of the info that you get back from the Live Connect APIs to speed up performance and decrease network traffic. We also redesigned our JavaScript implementation to require fewer lines of code to do common tasks. For details, see Referencing the APIs, JavaScript API (Windows 8 and web), and REST reference.

Top


Configuring your app

In this article

  • Get a package identity (Windows Store apps only)
  • Get a client ID (all app types except for Windows Store apps)
  • Specify a redirect domain
  • Get a client secret
  • Change a client secret
  • Specify consent page settings
  • Live Connect terms

Before your app can call the Live Connect APIs, you must register it and configure its settings. The settings your app needs depends on its type.

  • Windows Store apps need only a package identity.
  • Windows Phone apps, apps for the iOS operating system for Apple devices, and apps for the Google Android mobile technology platform need only a client ID.
  • All other apps need a client ID and a client secret, and you must specify a redirect domain.

How you register and manage your app's Live Connect configuration depends on the app's type.

  • Windows Store apps

    Configure and manage the Live Connect configuration for your Windows Store apps in your Windows Store Dashboard.

  • All other apps

    Configure and manage the Live Connect configuration for all other types of apps in the Live Connect app management site.

After you configure your app and get the necessary settings, you might also want to specify settings for the consent page or change a client secret.

Get a package identity (Windows Store apps only)

  1. Go to your Windows Store Dashboard.

    Note Do not go to the Live Connect app management site. That site is not designed to get package identities for Windows Store apps.

  2. If prompted, sign in with your Microsoft account credentials.

  3. Locate the app in your dashboard.

    • If you haven't entered this app in your Windows Store Dashboard, click Submit an app. Click App name and follow the on-screen directions to name your app. Save the changes to return to the app summary page.
    • If the app is already in your dashboard, find its tile in your dashboard, and click Edit.
  4. Click Advanced features.
  5. Click Push Notifications and Live Connect services info.
  6. Follow the on-screen directions following the heading If your app uses Live Connect services, review.
  7. Click Save.

Get a client ID (all app types except for Windows Store apps)

Caution If your app is a Windows Store app, don't follow these instructions, or else your client ID won't work. You must follow the instructions in the previous section instead.

  1. Go to the Live Connect app management site.
  2. If prompted, sign in with your Microsoft account credentials.
  3. If you are not immediately prompted to provide the app's display name and primary language, click Create application.
  4. Type the app's display name and select the app's primary language.
  5. Read the Live Connect Terms of Use and the privacy statement, and then click I accept. Live Connect creates, and then displays the client ID. It should look something like this: 00000000603E0BFE.

    Note If your app is a Windows Phone app, an iOS app, or an Android app, you must specify that your app is a mobile client app. (Live Connect uses a different OAuth 2.0 authentication flow for mobile client apps.) To do this, click Application Settings Page, click API Settings, click Yes next to Mobile client app, and then click Save.

Top

Specify a redirect domain

If your app is a Windows Store app, and the app has a companion website, do this:

  1. Go to your Windows Store Dashboard.
  2. If prompted, sign in with your Microsoft account credentials.
  3. Next to the name of your existing app, click Edit.
  4. Click Advanced features.
  5. Click Push Notifications and Live Connect services info.
  6. Click Representing your app to Live Connect users.
  7. In the Redirect Uri box, type the redirect domain.
  8. Click Save.

If your app is not a Windows Store app, do this:

  1. Go to the Live Connect app management site.
  2. If prompted, sign in with your Microsoft account credentials.
  3. Click the client ID of the app you want.
  4. Click Edit settings.
  5. In the Settings area, click API Settings.
  6. In the Redirect Domain box, type the domain that the Live Connect APIs will use to exchange tokens, data, and messages with your app (for example, http://www.contoso.com).
  7. Click Save.

Top

Get a client secret

If your app is a Windows Store app, do this:

  1. Go to your Windows Store Dashboard.
  2. If prompted, sign in with your Microsoft account credentials.
  3. Next to the name of your existing app, click Edit.
  4. Click Advanced features.
  5. Click Push Notifications and Live Connect services info.
  6. Click Authenticating your service.
  7. The client secret is displayed. It should look something like this: qXipuPomaauItsIsmwtKZ2YacGZtCyXD.

If your app is not a Windows Store app, do this:

  1. Go to the Live Connect app management site.
  2. If prompted, sign in with your Microsoft account credentials.
  3. Click the client ID of the app that you want.
  4. Click Edit settings.
  5. On the application summary page, the client secret is displayed. It should look something like this: qXipuPomaauItsIsmwtKZ2YacGZtCyXD.

Top

Change a client secret

You can swap your current client secret for a new client secret if you think your current client secret is compromised or if your organization requires you to change your client secret key periodically for security reasons.

If your app is a Windows Store app, do this:

  1. Go to your Windows Store Dashboard.
  2. If prompted, sign in with your Microsoft account credentials.
  3. Next to the name of your existing app, click Edit.
  4. Click Advanced features.
  5. Click Push Notifications and Live Connect services info.
  6. Click Authenticating your service.
  7. Click Create a new client secret > OK.
  8. After waiting at least 24 hours, return to this page and click Activate > OK.

    Caution After you click OK, the old client secret won't work anymore. This means that all copies of your app that rely on the old client secret won't work anymore, either.

If your app is not a Windows Store app, do this:

  1. Go to your Windows Store Dashboard.
  2. If prompted, sign in with your Microsoft account credentials.
  3. Click the client ID of the app that you want.
  4. Click Edit settings.
  5. In the Settings area, click API Settings.
  6. Click Create a new client secret.
  7. Click OK. A new client secret is created and displayed.

Note Both the old and new client secrets will continue to work until you follow the next set of steps.

When you're ready to stop using the old client secret, do this:

  1. Make sure that all copies of your app are using the new client secret.
  2. Go to the Live Connect app management site.
  3. If prompted, sign in with your Microsoft account credentials.
  4. Click the target client ID.
  5. Click Edit settings.
  6. In the Settings area, click API Settings.
  7. Click Create a new client secret.
  8. After waiting at least 24 hours, return to this page and click Activate.

    Caution After you click Activate, the old client secret won't work anymore. This means that all copies of your app that rely on the old client secret won't work anymore, either.

  9. Click OK.

Top

Specify consent page settings

After users sign in from your app to a service that is compatible with Live Connect, Live Connect displays the Allow access page (also called the consent page), which explains to the user the types of info that your app wants to access. (For more info about the consent page, see Obtaining user consent.) To customize the items in the consent page, if your app is a Windows Store app, do this:

  1. Go to your Windows Store Dashboard.
  2. If prompted, sign in with your Microsoft account credentials.
  3. Next to the name of your existing app, click Edit.
  4. Click Advanced features.
  5. Click Push Notifications and Live Connect services info.
  6. Click Representing your app to Live Connect users.
  7. Click the Website tab.
  8. Follow the on-screen directions, and then click Save.

If your app is not a Windows Store app, you specify these settings for your app in the Live Connect app management site. Here are the settings you can specify for the consent page.

Note The following table and screen shots show an English example of the UI. The actual UI that you see may differ depending on your locale.

Consent page | Live Connect app management site setting
1. Your app's logo | Basic Information page, Application logo image
2. Your app's domain name, which appears in several places in the consent page | API Settings page, Redirect Domain box
3. Your app's name, which appears in several places in the consent page | Basic Information page, Application name box
4. Your app's terms hyperlink | Basic Information page, Terms of service URL box
5. Your app's privacy statement hyperlink | Basic Information page, Privacy URL box

Note If the Terms of service URL and Privacy URL settings are not specified, the text | APPLICATION_NAME terms and privacy statement does not appear in the consent page.

The numbered items in the preceding table correspond to the items in the consent page, as shown here. (This page may look a bit different depending on your app type.)

Consent page with callouts

The numbered items also correspond to the items in the Live Connect app management site as shown here.

Note Again, the following screen shot shows an English example of the UI. The actual UI that you see may differ depending on your locale.

App management site pages with callouts

Top

Live Connect terms

client ID

A unique identifier that is assigned when you register your app with Live Connect.

client secret

A unique password that is created when you register your app with Live Connect.

consent page

A UI component that is displayed to a user so they can give your app permission to access the user's info.

package identity

The combination of a unique package name and publisher.

redirect domain

A domain that you assign for your app and that the Live Connect APIs use to exchange tokens, data, and messages directly with an app or with an app's companion website.

Top


Windows Store apps

In this article

  • Register your Windows Store app
  • Referencing the Live Connect APIs from your Windows Store app using JavaScript
  • Referencing the Live Connect APIs from your Windows Store app using XAML and C#
  • Code samples
  • Next steps

Windows Store apps can use the Live Software Development Kit (SDK) to enable single sign-on with Microsoft accounts and to work with info in Microsoft SkyDrive, Hotmail, and Windows Live Messenger. The Live SDK is available for Windows Store apps using JavaScript and managed programming languages like C# and Microsoft Visual Basic. Apps that use other programming languages can use other Live Connect APIs that are available for their app types, or they can use the Live Connect Representational State Transfer (REST) APIs and OAuth 2.0 endpoints directly.

Note This topic applies to you only if you want to add Live Connect services to a Windows Store app. If you want to add Live Connect services to another type of app, go to Mobile and Windows desktop apps or find your type of app in the menu on the right.

Register your Windows Store app

Before your Windows Store app can use the Live Connect APIs, you need to register it with the Windows Store as described in Configuring your app.

Referencing the Live Connect APIs from your Windows Store app using JavaScript

To reference the Live Connect APIs from a Windows Store app using JavaScript project in Microsoft Visual Studio Express 2012 for Windows 8, do this:

  1. Install the Live SDK, if you haven't already done so.
  2. In your project, in Solution Explorer, right-click References > Add Reference.
  3. Click Windows > Extension SDKs > Live SDK.
  4. Click Add, and then click Close.
  5. To enable Microsoft IntelliSense in default.html, add this <script> element in the <head> element.
    HTML
    <script src="///LiveSDKHTML/js/wl.js"></script>
  6. To enable IntelliSense in any other JavaScript (.js) file in your project, add this comment to the top of that .js file.
    JavaScript
    /// <reference path="///LiveSDKHTML/js/wl.js" />

Top

Referencing the Live Connect APIs from your Windows Store app using XAML and C#

To reference the Live Connect APIs from a Windows Store app project using C# in Visual Studio Express 2012 for Windows 8, do this:

  1. Install the Live SDK, if you haven't already done so.
  2. In your project, in Solution Explorer, right-click References > Add Reference.
  3. Click Windows > Extensions > Live SDK > OK.
  4. Add the corresponding using statements to your code, like this.
    C#
    using Microsoft.Live;
using Microsoft.Live.Controls;

Top

Code samples

Here are some code samples that show how to:

  • Invite a user to sign in.
  • Get permission from the signed-in users to access their basic profile info.
  • Greet signed-in users with their first and last names.

Signing users in from Windows Store apps using JavaScript

default.html

This code example displays the Windows 8 sign-in prompt when the app starts and requests access to the user's SkyDrive.

JavaScript
WL.Event.subscribe("auth.login", onLoginComplete);
WL.init();
WL.login({
    scope: ["wl.signin", "wl.skydrive"]
});

Note For more info about signing users in fromWindows Store apps using JavaScript, see Guidelines for the Microsoft account sign-in experience.

Signing users in from Windows Store apps using XAML and C#

The sign-in coding patterns that are appropriate for Windows Store apps using C# are described in the Guidelines for the Microsoft account sign-in experience.

Top

Next steps

You can learn more about using the Live Connect APIs from these topics:

  • Core concepts
  • Identity (profiles)
  • Hotmail (contacts and calendars)
  • SkyDrive (files and photos)
  • Watch the BUILD conference video that tells how to Power your app with Live services

Top


Windows Phone apps

In this article

  • Live Software Development Kit (SDK) Compatibility
  • Referencing the Live Connect APIs with C#
  • Code sample
  • Background transfer
  • Next steps

The Live Connect APIs enable Windows Phone 7.0, 7.5, and 8.0 apps to work with info in Hotmail, Windows Live Messenger, Microsoft SkyDrive, and other services that are compatible with Live Connect.

Note If you're working on a mobile app that doesn't run on Windows Phone, this is not the topic you need. Go to Mobile and Windows desktop apps.

Tip Before you can start coding Windows Phone apps, you need the right tools. For details, see Windows Phone Dev Center - Learn to build Windows Phone apps.

Before your Windows Phone app can use the Live Connect APIs, you'll need to get a client ID for it by Configuring your app.

Important When you configure your app and get its client ID, you must specify that you are configuring a mobile app. Mobile apps use a different OAuth 2.0 authentication flow. To do this, in the Live Connect app management site for your client ID, click Application Settings Page (or Edit settings, if you've already created your client ID), click API Settings, click Yes next to Mobile client app, and then click Save.

Live Software Development Kit (SDK) Compatibility

This table shows which Live Software Development Kit (SDK) version runs on which Windows Phone version.

This version of the Live SDK ... | Supports these Windows Phone versions
Live SDK V5.3 | Windows Phone 7.5 Windows Phone 7.8 Windows Phone 8.0
Live SDK V5.2 | Windows Phone 7.5 Windows Phone 7.8

Referencing the Live Connect APIs with C#

To reference the Live Connect APIs from a Windows Phone project in Microsoft Visual Studio 2010, do this.

  1. Install the Live SDK, if you haven't already done so.
  2. In your project, in Solution Explorer, right-click References > Add Reference.
  3. On the .NET tab, click Microsoft.Live.Controls, press and hold the CTRL key, and click Microsoft.Live.
  4. Click OK.
  5. Add the corresponding using statements to your code, like this.
    C#
    using Microsoft.Live;
using Microsoft.Live.Controls;

If the Live Connect sign-in control doesn't appear in the Microsoft Visual Studio Toolbox, do this to add it.

  1. In your project, if the Toolbox is not visible, with the Extensible Application Markup Language (XAML) designer open, click View > Toolbox.
  2. Right-click a blank area of the Toolbox, and click Choose Items.
  3. Click Browse.
  4. Go to the Live SDK install folder. From there, go to the \Windows Phone<version>\References\ folder, where <version> is the Windows Phone version for which you are building the app, such as 7.1 for Windows Phone 7.1. Click Microsoft.Live.Controls.dll > Open > OK.

    Note By default, the Live SDK is installed in the \Live\v5.0\ folder in \Program Files\Microsoft SDKs\ (on 32-bit computers) or \Program Files (x86)\Microsoft SDKs\ (on 64-bit computers).

Top

Code sample

These code samples show the basic code that you need to:

  • invite a user to sign in.
  • get permission from the signed-in user to access his or her basic profile info.
  • greet the signed-in user with their first and last names.

To run this code in your app, replace CLIENT_ID in the example with the client ID you got for your app by Configuring your app above.

MainPage.xaml

XAML
<phone:PhoneApplicationPage
    x:Class="WindowsPhoneCodeSample.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">
    <Grid x:Name="LayoutRoot" Background="Transparent">
        <my:SignInButton Name="btnSignin" ClientId="CLIENT_ID" Scopes="wl.signin wl.basic" Branding="Windows" TextType="SignIn" SessionChanged="btnSignin_SessionChanged" HorizontalAlignment="Left"  VerticalAlignment="Top" />
        <TextBlock Height="32" HorizontalAlignment="Left" Margin="12,78,0,0" Name="infoTextBlock" Text="" VerticalAlignment="Top" Width="419" />
    </Grid>
</phone:PhoneApplicationPage>

MainPage.xaml.cs

C#
using System;
using System.Windows;
using System.Collections.Generic;
using Microsoft.Phone.Controls;
using Microsoft.Live;
using Microsoft.Live.Controls;

namespace WindowsPhoneCodeSample
{
    public partial class MainPage : PhoneApplicationPage
    {
        private LiveConnectClient client;

        public MainPage()
        {
            InitializeComponent();
        }

        private async void btnSignin_SessionChanged(object sender, LiveConnectSessionChangedEventArgs e)
        {
            if (e.Status == LiveConnectSessionStatus.Connected)
            {
                client = new LiveConnectClient(e.Session);
                LiveOperationResult operationResult = await client.GetAsync("me");
                try
                {
                    dynamic meResult = operationResult.Result;
                    if (meResult.first_name != null &&
                        meResult.last_name != null)
                    {
                        infoTextBlock.Text = "Hello " +
                            meResult.first_name + " " +
                            meResult.last_name + "!";
                    }
                    else
                    {
                        infoTextBlock.Text = "Hello, signed-in user!";
                    }
                }
                catch (LiveConnectException exception)
                {
                    this.infoTextBlock.Text = "Error calling API: " +
                        exception.Message;
                }
            }
            else
            {
                infoTextBlock.Text = "Not signed in.";
            }
        }
    }
}

To learn what this code does, see Core concepts and Identity (profiles).

For additional code examples, look throughout this documentation for subsections starting with "[C#]".

Note

By default, any code example labeled for "[C#]" applies to both Windows Phone 8.0 apps and Windows Store apps using C#.

To learn how to use apply the code examples throughout this documentation in the context of a larger reference code sample, see Working with the code examples.

Top

Background transfer

Windows Phone 7.5 apps can start upload and download file requests with SkyDrive that continue even if the app that started the request is suspended or quits. This feature is known as background transfer. For more info, see the "Downloading files" and "Uploading files" sections—specifically the tips following the Windows Phone portion of each section—in Folders and files.

Top

Next steps

You can learn more about using the Live Connect APIs from these topics.

  • Core concepts
  • Identity (profiles)
  • Hotmail (contacts and calendars)
  • SkyDrive (files and photos)

Top


iOS apps

In this article

  • Referencing the iOS API with Objective-C
  • Code sample
  • Configuring your app to participate in the Microsoft SkyDrive app experience
  • Next steps

Live Connect provides an API for the iOS operating system for Apple devices. The iOS API enables your iPad, iPhone, and iPod Touch apps running on iOS 4.3 or higher to work with info in Hotmail, Windows Live Messenger, Microsoft SkyDrive, and other services that are compatible with Live Connect. Although you can still write code to call the Live Connect Representational State Transfer (REST) API directly, the iOS API now makes your coding tasks easier.

Note If you're working on a mobile app that runs on Windows Phone, this is not the topic you need. Go to Windows Phone apps.

Before you can start calling the Live Connect APIs, you need a client ID. For instructions, see Configuring your app.

Important You must specify that your client ID is associated with mobile apps such as those for the iOS operating system for Apple devices. (Mobile apps use a different OAuth 2.0 authentication flow.) To do this, in the Live Connect app management site for your client ID, click Application Settings Page (or Edit settings, if you've already created your client ID), click API Settings, click Yes next to Mobile client app, and then click Save.

Prerequisites

The iOS API requires Xcode 4.1 or later. Xcode 4.1 runs on Mac OS X Snow Leopard (version 10.6) and OS X Lion (version 10.7), while Xcode 4.2 runs only on OS X Lion (version 10.7).

Top

Referencing the iOS API with Objective-C

Before you can reference the Live Connect iOS API in an Xcode project, you must download the Live software development kit (SDK) for iOS. Here's how.

To download the Live SDK for iOS

  • Go to the website location where the Live Software Development Kit (SDK) for iOS is stored, and download the SDK for iOS.

    Note If you download the Live SDK for iOS as a zip file, you must extract the contents of the .zip file before you follow the steps in the next section.

You can now reference the iOS API.

To reference the iOS API

You can reference the iOS API in two ways. We recommend that you reference the iOS API framework. However, you can reference the iOS API source code directly if you need to modify it or want to see how it works.

To reference the iOS API framework

  1. Open your iOS project in Xcode, if you haven't already done so.
  2. In the Project Navigator, click your project.
  3. In the project editor, in the Targets area, click your project.
  4. Click Build Phases.
  5. Expand Link Binary With Libraries, and then click Add items (+).
  6. Click Add Other.
  7. Go to and select the LiveSDK.framework folder within the downloaded Live SDK for iOS, and then click Open.
  8. In the Project Navigator, drag the LiveSDK.framework node and drop it into Build Phases tab's Copy Bundle Resources table in the project editor.
  9. For each code file from which you want to reference the iOS API framework, add this import statement: #import "LiveSDK/LiveConnectClient.h".

Note If you reference the iOS API framework, you will be able to browse the framework's type and member definitions from your Xcode project. However, you may have difficulty browsing the underlying implementation code of the types and members because this code is stored in binary format within the framework.

To reference the iOS API source code directly

  1. Open your iOS project in Xcode, if you haven't already done so.
  2. Click File > Add Files to "Your Project Name".
  3. Go to and select the Library folder within the downloaded Live SDK for iOS, and then click Add.
  4. For each code file from which you want to reference the API source code, add this import statement: #import "LiveConnectClient.h".

Note If you reference the iOS API source code directly, you will be able to browse the underlying implementation code of the framework's types and members easily from your Xcode project. However, any changes that you make to this source code could result in design-time or run-time errors that are difficult to debug.

Important If you reference the iOS API source code directly and you use Xcode 4.2 or later, you must disable Automatic Reference Counting (ARC). This is because the iOS API source code uses manual reference counting to enable the greatest number of developers using Xcode to reference the iOS API source code directly. If you want to use ARC, you must reference the iOS API framework by following the steps in the previous section, or you must do an ARC conversion on the iOS API source code. To do an ARC conversion in Xcode:

  1. Follow the steps listed earlier in this section.
  2. On the Xcode menu, click Xcode > Preferences and select the Continue building after errors check box.
  3. On the Xcode menu, click Edit > Refactor > Convert to Objective-C ARC.
  4. Follow the on-screen directions.

Top

Code sample

To get you started, here's the basic code that shows how to reference the iOS APIs, invite a user to sign in, and get the signed-in user's permission to get his or her basic profile info.

ViewController.h

ObjectiveC
#import <UIKit/UIKit.h>
#import "LiveSDK/LiveConnectClient.h"

@interface ViewController : UIViewController<LiveAuthDelegate, LiveOperationDelegate, LiveDownloadOperationDelegate, LiveUploadOperationDelegate>
@property (strong, nonatomic) LiveConnectClient *liveClient;
@property (strong, nonatomic) IBOutlet UILabel *infoLabel;
@end

ViewController.m (where APP_CLIENT_ID is your app's client ID)

ObjectiveC
#import "ViewController.h"

@implementation ViewController
@synthesize liveClient;
@synthesize infoLabel;

NSString* APP_CLIENT_ID=@"000000004406774C";

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.liveClient = [[LiveConnectClient alloc] initWithClientId:APP_CLIENT_ID
                                                         delegate:self
                                                        userState:@"initialize"];
}

- (void)authCompleted:(LiveConnectSessionStatus) status
              session:(LiveConnectSession *) session
            userState:(id) userState
{
    if ([userState isEqual:@"initialize"])
    {
        [self.infoLabel setText:@"Initialized."];
        [self.liveClient login:self
                        scopes:[NSArray arrayWithObjects:@"wl.signin", nil]
                      delegate:self
                     userState:@"signin"];
    }
    if ([userState isEqual:@"signin"])
    {
        if (session != nil)
        {
            [self.infoLabel setText:@"Signed in."];
        }
    }
}

- (void)authFailed:(NSError *) error
         userState:(id)userState
{
    [self.infoLabel setText:[NSString stringWithFormat:@"Error: %@", [error localizedDescription]]];
}
@end

Top

Configuring your app to participate in the Microsoft SkyDrive app experience

There is a Microsoft SkyDrive app that users can install on an iPhone or iPad device. They can then use this app to upload files to, or view files from, their SkyDrive storage location. You can configure your app to participate in the file uploading and viewing experiences in the Microsoft SkyDrive app. This can save you coding time and make for a better user experience.

In one scenario, a user can upload a file from your app to his or her SkyDrive storage location by using the Microsoft SkyDrive app. This can save you time writing code in your app to upload the file directly; you can let the Microsoft SkyDrive app upload the file instead. Here's how it works. When the user is viewing a file (like a document or a photo) within your app, you can let the user open the file in the Microsoft SkyDrive app. Your app can use the UIDocumentInteractionController class to pass the file to the Microsoft SkyDrive app, in which the user can then choose where to upload the file. After the Microsoft SkyDrive app opens the file, the user taps the Upload command, taps the folder in his or her SkyDrive location to upload the file to, and then the Microsoft SkyDrive app uploads the file to that folder.

In another scenario, a user can use the Microsoft SkyDrive app to view a file from his or her SkyDrive storage location in your app. This enables a seamless user experience for viewing files, especially for custom file types that aren't associated with apps that might already be installed on the user's device. Here's how it works. In the Microsoft SkyDrive app, the user taps the file to open it from his or her SkyDrive location, and then taps the Open in Another App command that's displayed. The Microsoft SkyDrive app then displays a list of apps that the user can choose from to view the file. If your app is registered to work with that file's type, your app appears in the list. When the user taps your app in the list, your app then displays that file.

For details about how your apps can participate in these experiences, see About Document Interaction in the iOS Developer Library documentation.

Top

Next steps

From here, we suggest that you continue your learning with the info in Core concepts, Identity (profiles), Hotmail (contacts and calendars), SkyDrive (files and photos), and Messenger (instant messaging).

Top


Android apps

In this article

  • Referencing the Android API with Java
  • Code sample
  • Next steps

Live Connect provides an API for the Google Android mobile technology platform. The Android API enables your apps running on Froyo, Gingerbread, Honeycomb, and Ice Cream Sandwich versions of Android to work with info in Hotmail, Windows Live Messenger, Microsoft SkyDrive, and other services that are compatible with Live Connect. Although you can still write code to call the Live Connect Representational State Transfer (REST) API directly, the Android API now makes your coding tasks easier.

Note If you're working on a mobile app that runs on Windows Phone, this is not the topic you need. Go to Windows Phone apps.

Before you can start calling the Live Connect APIs, you need a client ID. For instructions, see Configuring your app.

Important You must specify that your client ID is associated with mobile apps such as those for the Google Android mobile technology platform. (Mobile apps use a different OAuth 2.0 authentication flow.) To do this, in the Live Connect app management site for your client ID, click Application Settings Page (or Edit settings, if you've already created your client ID), click API Settings, click Yes next to Mobile client app, and then click Save.

Prerequisites

You can use the Live Connect Android API to target Android platform versions 2.2 and later. Note that the Live Connect Android API requires use of the platform API level corresponding to the platform version that you're targeting, as shown here.

Platform name | Version | API level
Ice Cream Sandwich | 4.0 | 14
Honeycomb | 3.2 | 13
Honeycomb | 3.1 | 12
Honeycomb | 3.0 | 11
Gingerbread | 2.3.4 | 10
Gingerbread | 2.3.3 | 9
Froyo | 2.2 | 8

For info about the correct versions to use for the Java SE Development Kit (JDK), the Android software development kit (SDK), the Eclipse integrated development environment (IDE), and the Android Development Tools (ADT) plugin for Eclipse if you choose to use them, see the Android Developers website.

Top

Referencing the Android API with Java

Before you can reference the Live Connect Android API in an Eclipse Android project, you must download the Live SDK for Android and compile the Live Connect Android API source code. Here's how.

To download the Live SDK for Android and compile the Live Connect Android API source code

  • Go to the website location where the Live Software Development Kit (SDK) for Android is stored and download the SDK.

    Note If you download the Live SDK for Android as a zip file, you must extract the contents of the zip file before you follow the steps in the next section.

You must now compile the downloaded Android API source code.

To compile the Android API source code

After you download the Android API source code, you must compile it. You need to do this only once. After you compile the Android API source code on your computer, you can reference it from multiple Eclipse Android projects on that same computer.

  1. Start Eclipse, if it is not already running.
  2. Click File > Import.
  3. Expand General, click Existing Projects into Workspace, and then click Next.
  4. With the Select root directory option selected, click Browse.
  5. Go to and select the src folder within the downloaded Live SDK for Android, and then click OK.
  6. In the Projects box, select the LiveSdk check box.
  7. With the Copy projects into workspace check box selected, click Finish. Eclipse adds the LiveSdk project to the Package Explorer pane and then compiles the Android API source code in the background.

You can now reference the compiled Android API source code from your Eclipse Android projects.

To reference the compiled Android API source code in an Eclipse Android project

  1. In Eclipse, display the Package Explorer pane, if it is not already visible.
  2. Right-click your project's name, and then click Properties.
  3. In the list of project properties, click Android.
  4. In the Library area, click Add.
  5. Click LiveSdk and then click OK.
  6. Click OK. Eclipse sets a reference to the compiled Android API source code project, and you can now call the Live Connect Android API from your own Android project.

Note Before you run your project, you must add the Internet permission to your project's manifest, as shown in the following steps. If you don't add the Internet permission, your app may have problems accessing Live Connect web services later.

  1. With your project open, in the Package Explorer pane, open the AndroidManifest.xml file.
  2. In the editor, click the Permissions tab.
  3. Click Add.
  4. Click Uses Permission, and then click OK.
  5. In the Name list, click android.permission.INTERNET.
  6. Save the AndroidManifest.xml file.

Top

Code sample

To get you started, here's the basic code that shows how to reference the Android API, invite a user to sign in, and get the signed-in user's permission to get his or her basic profile info.

main.xml

none
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >
    <TextView
        android:id="@+id/resultTextView"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Results will display here." />
</LinearLayout>

JavaCodeSample.java

Java
package com.live.dev;

import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
import java.util.Arrays;
import com.microsoft.live.LiveAuthException;
import com.microsoft.live.LiveAuthListener;
import com.microsoft.live.LiveAuthClient;
import com.microsoft.live.LiveConnectSession;
import com.microsoft.live.LiveConnectClient;
import com.microsoft.live.LiveStatus;

public class JavaCodeSample extends Activity implements LiveAuthListener {

    private LiveAuthClient auth;
    private LiveConnectClient client;
    private TextView resultTextView;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        this.resultTextView = (TextView)findViewById(R.id.resultTextView);
        this.auth = new LiveAuthClient(this, MyConstants.APP_CLIENT_ID);
    }

    @Override
    protected void onStart() {
        super.onStart();
        Iterable<String> scopes = Arrays.asList("wl.signin", "wl.basic");
        this.auth.login(scopes, this);
    }

    public void onAuthComplete(LiveStatus status, LiveConnectSession session, Object userState) {
        if(status == LiveStatus.CONNECTED) {
            this.resultTextView.setText("Signed in.");
            client = new LiveConnectClient(session);
        }
        else {
            this.resultTextView.setText("Not signed in.");
            client = null;
        }
    }

    public void onAuthError(LiveAuthException exception, Object userState) {
        this.resultTextView.setText("Error signing in: " + exception.getMessage());
        client = null;
    }
}

MyConstants.java (where MY CLIENT ID is your app's client ID—for example, 00000000603E7410)

java
package com.live.dev;

final class MyConstants {
    static final String APP_CLIENT_ID = "MY CLIENT ID";
}

Top

Next steps

From here, we suggest that you continue your learning with the info in Core concepts, Identity (profiles), Hotmail (contacts and calendars), SkyDrive (files and photos), and Messenger (instant messaging).

Top


Web apps

In this article

  • Choosing an API implementation
  • Code samples
  • Testing web apps locally
  • Next steps

The Live Connect APIs enable client-side and server-side websites and scripts to work with info in Hotmail, Windows Live Messenger, Microsoft SkyDrive, and other services that are compatible with Live Connect. An example of a client-side or server-side website or script is a web browser or a web browser control that enables a user to interact with a website.

Note If you're working on a Windows Store app, a Windows Phone app, or a mobile app (even if those apps include website implementations), this is not the topic you need. Go to Windows Store apps, Windows Phone apps, or Mobile and Windows desktop apps, respectively.

Before you can start calling the Live Connect APIs, you need a client ID, a client secret, and a redirect domain. For instructions, see Configuring your app.

Choosing an API implementation

If you're working on a client-side website or script that uses JavaScript, you use our JavaScript implementation. If you're working on a server-side website or script, or if you're working on a client-side website or script that can't use JavaScript, you use our Representational State Transfer (REST) implementation. For details, see JavaScript API (Windows 8 and web) and REST reference.

Top

Code samples

To get you started, here's the basic code that shows how to reference the Live Connect APIs, invite a user to sign in, get the signed-in user's permission to get his or her basic profile info, and display a greeting with the signed-in user's first and last names.

default.html

HTML
<!DOCTYPE html>
<html>
    <head>
        <title>Client-Side JavaScript Code Sample</title>
        <script src="constants.js"></script>
        <script src="//js.live.net/v5.0/wl.js"></script>
    </head>
    <body>
        <div id="signin"></div>
        <label id="info"></label>
        <script>
            WL.Event.subscribe("auth.login", onLogin);
            WL.init({
                client_id: APP_CLIENT_ID,
                redirect_uri: REDIRECT_URL,
                scope: "wl.signin",
                response_type: "token"
            });
            WL.ui({
                name: "signin",
                element: "signin"
            });
            function onLogin (session) {
                if (!session.error) {
                    WL.api({
                        path: "me",
                        method: "GET"
                    }).then(
                        function (response) {
                            document.getElementById("info").innerText =
                                "Hello, " + response.first_name + " " + response.last_name + "!";
                        },
                        function (responseFailed) {
                            document.getElementById("info").innerText =
                                "Error calling API: " + responseFailed.error.message;
                        }
                    );
                }
                else {
                    document.getElementById("info").innerText =
                        "Error signing in: " + session.error_description;
                }
            }
        </script>
    </body>
</html>

callback.html

HTML
<!DOCTYPE html>

<html>
    <head>
        <title></title>
    </head>
    <body>
        <script src="//js.live.net/v5.0/wl.js"></script>
    </body>
</html>

constants.js (replace YOUR_CLIENT_ID with your app's client ID and YOUR_REDIRECT_URL with your app's redirect URL)

JavaScript
var APP_CLIENT_ID = "YOUR_CLIENT_ID";
var REDIRECT_URL = "YOUR_REDIRECT_URL";

To learn what this code does, see Core concepts and Identity (profile).

To learn how to use many of the code examples throughout this documentation in the context of a larger reference code sample, see Working with the code examples.

If you're working on a server-side website or script, or if you're working on a client-side website or script that can't use JavaScript, see the REST code samples in Server-side scenarios.

Top

Testing web apps locally

When you are developing a web app, it is convenient to test the app on a local computer before you deploy it to a web server. However, the Live Connect APIs require the redirect URL to use the same domain at which the app's client ID was configured. Your local computer's web server likely uses a default address like http://localhost, so you must map your domain to the Internet Protocol (IP) address of your local web server. To do this, you add a mapping to the hosts file on your computer. (The job of the hosts file is to map host names to IP addresses.) On Windows computers, the hosts file is located at \Windows\System32\drivers\etc\hosts. On Mac OS X and most Unix computers, it is located at /private/etc/hosts. The format is the IP address, followed by the domain to map, like this.

127.0.0.1    MyDomain.com
127.0.0.1    AnotherDomain.com

The preceding example demonstrates mapping two arbitrary domain names to the IP address for localhost. With these mappings in place, every time you navigate to MyDomain.com or AnotherDomain.com, you will be redirected to 127.0.0.1 (http://localhost). The mappings in the hosts file apply to all web navigation, including redirect URLs that are returned by the Live Connect APIs. This works because the Live Connect APIs do not check the actual IP address that is in use, the APIs only verify the domain name. If your client ID was configured with a redirect URL of http://MyTestingDomain.com/MyApp/callback.htm, you update your hosts file with the following mapping: 127.0.0.1 MyTestingDomain.com. Now if you enter "MyTestingDomain.com" into your browser, it will resolve to http://localhost, so you can use your local web server for testing.

Important

Elevated (or root) privileges are required to edit the hosts file, regardless of platform.

Tip

You can map an externally available domain to your local server IP address, but you must comment out the mapping when you want to view the actual website. This is only applicable to the computer on which the hosts file was modified. This is a handy trick because it makes it easy to switch between your externally available website and your local test website.

Top

Next steps

From here, we suggest starting with the info in Core concepts, Identity (profiles), Hotmail (contacts and calendars), SkyDrive (files and photos), and Messenger (instant messaging). If you're writing code for a server-side website or script, be sure to see Server-side scenarios, too.

Top


Working with the code examples

To make full use of the smaller code examples in the Core concepts, Identity (profiles), Hotmail (contacts and calendars), and Microsoft SkyDrive (files and photos) sections in your apps, you can use those code examples in the context of larger, reference code samples that we provide here.

  • Working with the JavaScript code examples
    • Working with the C# code examples
      • Working with the Objective-C code examples
        • Working with the Java code examples
          • Working with the REST code examples
          • Additional code examples

          Working with the JavaScript code examples

          To demonstrate the use of the smaller JavaScript code examples, we've written the following larger, reference code sample that you can use as guidance for your own apps.

          default.htm (for Windows Store apps using JavaScript only)

          HTML
          <!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title>JavaScript Code Sample</title>
    <!-- WinJS references -->
    <link href="//Microsoft.WinJS.1.0.RC/css/ui-dark.css" rel="stylesheet" />
    <script src="//Microsoft.WinJS.1.0.RC/js/base.js"></script>
    <script src="//Microsoft.WinJS.1.0.RC/js/ui.js"></script>
    <!-- JavaScript Code Sample references-->
    <link href="/css/default.css" rel="stylesheet" />
    <script src="/js/default.js"></script>
    <!-- Developer-defined references -->
    <script src="///LiveSDKHTML/js/wl.js"></script>
    <script src="/js/gather_info.js"></script>
</head>
<body>
    <h1>JavaScript Code Sample</h1>
    <div id="signin"></div>
    <br />
    <label id="infoLabel"></label>
    <script>
        WL.Event.subscribe("auth.login", onLogin);
        WL.init({
            scope: "wl.signin",
        });
        WL.ui({
            name: "signin",
            element: "signin"
        });
        function onLogin(session) {
            var session = WL.getSession();
            if (session.error) {
                document.getElementById("infoLabel").innerText =
                    "Error signing in: " + session.error;
            }
            else {
                document.getElementById("infoLabel").innerText =
                    "Signed in.";
            }
        }
    </script>
          HTML
          </body>
</html>

          For the sign-in coding patterns that are appropriate for Windows Store apps using JavaScript, see Guidelines for the Microsoft account sign-in experience.

          Note The preceding code sample prompts the user to consent to the wl.signin scope only. To write code to prompt the user to consent to additional scopes later, see the code examples in the "Requesting additional scopes" section of Obtaining user consent.

          constants.js (for client-side web pages and scripts using JavaScript only

          Client-side web-pages and scripts using JavaScript must define the app's client ID and redirect URL. In the code examples, these are defined in constants.js; however you must replace the placeholder strings: YOUR_CLIENT_ID and YOUR_REDIRECT_URL with your app's client ID and redirect URL, respectively.

          JavaScript
          var APP_CLIENT_ID = "YOUR_CLIENT_ID";
var REDIRECT_URL = "YOUR_REDIRECT_URL";

          default.htm (for client-side web pages and scripts using JavaScript only)

          The code in this sample prompts the user to consent to only the wl.signin scope. In your app, you'll probably need to add additional scopes. See Obtaining user consent for more info on how to add additional scopes.

          HTML
          <!DOCTYPE html>
<html>
    <head>
        <title>Client-Side JavaScript Dashboard</title>
        <script src="//js.live.net/v5.0/wl.js"></script>
        <script src="gather_info.js"></script>
        <script src="constants.js"></script>
    </head>
    <body>
        <div id="signin"></div>
        <br />
        <label id="infoLabel"></label>
        <script>
            WL.Event.subscribe("auth.login", onLogin);
            WL.init({
                client_id: APP_CLIENT_ID,
                redirect_uri: REDIRECT_URL,
                scope: "wl.signin",
                response_type: "token"
            });
            WL.ui({
                name: "signin",
                element: "signin"
            });
            function onLogin() {
                document.getElementById("infoLabel").innerText = "Signed in.";
            }
        </script>
          HTML
              </body>
</html>

          callback.htm (for client-side web pages and scripts using JavaScript only)

          HTML
          <!DOCTYPE html>

<html>
    <head>
        <title></title>
    </head>
    <body>
        <script src="//js.live.net/v5.0/wl.js"></script>
    </body>
</html>

          To make your app's code easier to manage, you could put code that runs when users interact with the app, such as when they click buttons, in a separate file and name it gather_info.js as in this code sample, .

          Top

          Working with the C# code examples

          To demonstrate the use of the smaller C# code examples, we've written the following larger, reference code sample that you can use as guidance for your own apps.

          MainPage.xaml (for Windows Store apps using C# only)

          XAML
          <Page
    x:Class="CSharpCodeSample.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:CSharpCodeSample"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d"
    xmlns:live="using:Microsoft.Live.Controls">

    <Grid Background="{StaticResource ApplicationPageBackgroundBrush}">
    <live:SignInButton x:Name="btnSignin" Scopes="wl.signin wl.basic" SessionChanged="btnSignin_SessionChanged" />
        <TextBlock Height="32" Foreground="White" HorizontalAlignment="Left" Margin="8,76,0,0" Name="infoTextBlock" VerticalAlignment="Top" Width="419" />
    </Grid>
</Page>

          Note The preceding code sample prompts the user to consent to the wl.signin and wl.basic scopes only. To write code to prompt the user to consent to additional scopes later, see the code examples in the "Requesting additional scopes" section of Obtaining user consent.

          MainPage.xaml (for Windows Phone apps using C# only)

          Apps that are not Windows Store apps must define the app's client ID in the app. In this example, you must replace the placeholder string: CLIENT_ID with your app's client ID.

          XAML
          <phone:PhoneApplicationPage
    x:Class="WindowsPhoneCodeSample.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">
    <Grid x:Name="LayoutRoot" Background="Transparent">
        <my:SignInButton Name="btnSignin" ClientId="CLIENT_ID" Scopes="wl.signin wl.basic" Branding="Windows" TextType="SignIn" SessionChanged="btnSignin_SessionChanged" HorizontalAlignment="Left"  VerticalAlignment="Top" />
        <TextBlock Height="32" HorizontalAlignment="Left" Margin="12,78,0,0" Name="infoTextBlock" Text="" VerticalAlignment="Top" Width="419" />
    </Grid>
</phone:PhoneApplicationPage>

          Note The preceding code sample prompts the user to consent to the wl.signin and wl.basic scopes only. To write code to prompt the user to consent to additional scopes later, see the code examples in the "Requesting additional scopes" section of Obtaining user consent.

          MainPage.xaml.cs (for Windows Store apps using C# and Windows Phone apps using C#)

          C#
          using System;
using System.IO;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Microsoft.Live;
using Microsoft.Live.Controls;

namespace CSharpCodeSample
{
    public sealed partial class MainPage : Page
    {
        private LiveAuthClient auth;
        private LiveConnectClient client;
        private LiveConnectSession session;

        public MainPage()
        {
            this.InitializeComponent();
        }

        private void btnSignin_SessionChanged(object sender, LiveConnectSessionChangedEventArgs e)
        {
            if (e.Status == LiveConnectSessionStatus.Connected)
            {
                session = e.Session;
                client = new LiveConnectClient(session);
                infoTextBlock.Text = "Signed in.";
            }
            else
            {
                infoTextBlock.Text = "Not signed in.";
                client = null;
            }
        }
    }
}

          For the sign-in coding patterns that are appropriate for Windows Store apps using JavaScript, see Guidelines for the Microsoft account sign-in experience.

          Top

          Working with the Objective-C code examples

          To demonstrate the use of the smaller Objective-C code examples, we've written the following larger, reference code sample that you can use as guidance for your own apps.

          ViewController.h

          ObjectiveC
          #import <UIKit/UIKit.h>
#import "LiveSDK/LiveConnectClient.h"

@interface ViewController : UIViewController<LiveAuthDelegate, LiveOperationDelegate, LiveDownloadOperationDelegate, LiveUploadOperationDelegate>
@property (strong, nonatomic) LiveConnectClient *liveClient;
@property (strong, nonatomic) IBOutlet UILabel *infoLabel;
@end

          ViewController.m

          Apps that are not Windows Store apps must define the app's client ID in the app. In this example, you must replace the placeholder string: APP_CLIENT_ID with your app's client ID.

          ObjectiveC
          #import "ViewController.h"

@implementation ViewController
@synthesize liveClient;
@synthesize infoLabel;

NSString* APP_CLIENT_ID=@"000000004406774C";

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.liveClient = [[LiveConnectClient alloc] initWithClientId:APP_CLIENT_ID
                                                         delegate:self
                                                        userState:@"initialize"];
}

- (void)authCompleted:(LiveConnectSessionStatus) status
              session:(LiveConnectSession *) session
            userState:(id) userState
{
    if ([userState isEqual:@"initialize"])
    {
        [self.infoLabel setText:@"Initialized."];
        [self.liveClient login:self
                        scopes:[NSArray arrayWithObjects:@"wl.signin", nil]
                      delegate:self
                     userState:@"signin"];
    }
    if ([userState isEqual:@"signin"])
    {
        if (session != nil)
        {
            [self.infoLabel setText:@"Signed in."];
        }
    }
}

- (void)authFailed:(NSError *) error
         userState:(id)userState
{
    [self.infoLabel setText:[NSString stringWithFormat:@"Error: %@", [error localizedDescription]]];
}
@end

          Working with the Java code examples

          To demonstrate the use of the smaller Java code examples, we've written the following larger, reference code sample that you can use as guidance for your own apps.

          main.xml

          none
          <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >
    <TextView
        android:id="@+id/resultTextView"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Results will display here." />
</LinearLayout>

          JavaCodeSample.java

          Java
          package com.live.dev;

import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
import java.util.Arrays;
import com.microsoft.live.LiveAuthException;
import com.microsoft.live.LiveAuthListener;
import com.microsoft.live.LiveAuthClient;
import com.microsoft.live.LiveConnectSession;
import com.microsoft.live.LiveConnectClient;
import com.microsoft.live.LiveStatus;

public class JavaCodeSample extends Activity implements LiveAuthListener {

    private LiveAuthClient auth;
    private LiveConnectClient client;
    private TextView resultTextView;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        this.resultTextView = (TextView)findViewById(R.id.resultTextView);
        this.auth = new LiveAuthClient(this, MyConstants.APP_CLIENT_ID);
    }

    @Override
    protected void onStart() {
        super.onStart();
        Iterable<String> scopes = Arrays.asList("wl.signin", "wl.basic");
        this.auth.login(scopes, this);
    }

    public void onAuthComplete(LiveStatus status, LiveConnectSession session, Object userState) {
        if(status == LiveStatus.CONNECTED) {
            this.resultTextView.setText("Signed in.");
            client = new LiveConnectClient(session);
        }
        else {
            this.resultTextView.setText("Not signed in.");
            client = null;
        }
    }

    public void onAuthError(LiveAuthException exception, Object userState) {
        this.resultTextView.setText("Error signing in: " + exception.getMessage());
        client = null;
    }
}

          MyConstants.java

          Apps that are not Windows Store apps must define the app's client ID in the app. In this example, you must replace the placeholder string: MY CLIENT ID with your app's client ID.

          java
          package com.live.dev;

final class MyConstants {
    static final String APP_CLIENT_ID = "MY CLIENT ID";
}

          Working with the REST code examples

          To use the Representational State Transfer (REST) code examples, we're following this format.

          METHOD https://apis.live.net/v5.0/REST_PATH?access_token=ACCESS_TOKEN

HEADER_FIELD: HEADER_VALUE

BODY

          In this format, the uppercase characters represent the following:

          • METHOD represents an HTTP request method (or verb) that the Live Connect REST API supports, like GET, POST, UPDATE, and DELETE.
          • REST_PATH represents a path that our REST implementation supports, like me, me/albums, and me/photos.
          • ACCESS_TOKEN represents a valid access token that Live Connect issues. This access token enables a specific client ID to work with a specific set of user info for a specific time period.
          • HEADER_FIELD represents an HTTP header field, like Content-Type, that our REST implementation supports for the corresponding HTTP verb.
          • HEADER_VALUE represents an HTTP header value, like application/json, that our REST implementation supports for the corresponding HTTP header field.
          • BODY represents a body value, like this code sample for creating an Event object, that our REST implementation supports for the associated HTTP verb.
            {
    "name": "Global Project Risk Management Meeting",
    "description": "Generate and assess risks for the project",
    "start_time": "2011-04-20T01:00:00-07:00",
    "end_time": "2011-04-20T02:00:00-07:00",
    "location": "Building 81, Room 9981, 123 Anywhere St., Redmond WA 19599",
    "is_all_day_event": false,
    "availability": "busy",
    "visibility": "public"
}

          Putting this all together, here are the input parameters for a sample REST call that creates an Event object.

          POST https://apis.live.net/v5.0/me/events?access_token=EwBQ... ...AA==

Content-Type: application/json

{
    "name": "Global Project Risk Management Meeting",
    "description": "Generate and assess risks for the project",
    "start_time": "2011-04-20T01:00:00-07:00",
    "end_time": "2011-04-20T02:00:00-07:00",
    "location": "Building 81, Room 9981, 123 Anywhere St., Redmond WA 19599",
    "is_all_day_event": false,
    "availability": "busy",
    "visibility": "public"
}

          You can apply the patterns of these REST input parameters to your app's specific code syntax for making REST calls.

          Top

          Additional code examples

          We provide lots of additional code examples outside of our documentation, including these:

          • The Live Software Development Kit (SDK) links to several code examples. In the Live SDK install folder, go to the \Samples\ folder.

            Note By default, the Live SDK is installed in the \Live\v5.0\ folder in \Program Files\Microsoft SDKs\ (on 32-bit computers) or \Program Files (x86)\Microsoft SDKs\ (on 64-bit computers).

          • MSDN Samples - SkyDrive Photo API sample for WP7
          • GitHub - liveservices—code examples for ASP.NET websites, Windows desktop apps with C#, Windows Phone apps, PHP scripts, and apps for the iOS operating system for Apple devices.

          Top


Mobile and Windows desktop apps

In this article

  • Creating a new app
  • App overview
  • Building an app

Live Connect uses industry standard protocols such as OAuth 2.0, JavaScript Object Notation (JSON), and Extensible Messaging and Presence Protocol (XMPP) to make it easy to access and integrate Microsoft SkyDrive, Hotmail, and Windows Live Messenger into your mobile or desktop app.

This walkthrough demonstrates how to create a mobile or a desktop app that can access user data by using Live Connect. These development patterns can be used for Windows desktop apps and for mobile apps. In addition, there are code samples available on GitHub that show how to use Live Connect from a variety of mobile platforms.

Note Live Connect now provides APIs for the iOS operating system for Apple devices and the Google Android mobile technology platform, to make coding these app types easier than before. For details, see iOS apps and Android apps.

To access data from Live Connect from your platform of choice requires the availability of a web browser component that can be used to authenticate the user. The app in this example is a Windows Presentation Foundation (WPF) app that is written in C# and the .NET Framework version 4. You can build and run it by using either Microsoft Visual Studio 2010 or Microsoft Visual Studio 2008.

Important Because Windows Store apps and Windows Phone apps have built-in support for user sign-in and consent, the info presented in this walkthrough is not applicable to them. For these types of apps, see Windows Store apps and Windows Phone apps.

Creating a new app

When you get a client ID from the Live Connect app management site, leave the Redirect Domain field blank, and select Yes for the Mobile client app option. By doing so, you configure your app to use a special redirect URL (https://login.live.com/oauth20_desktop.srf), which enables the app to handle redirects after the user has given authorization and facilitates refreshing the access token. For more info, see Configuring your app.

Note

Top

App overview

To implement the client-side authentication flow, desktop apps must use a web browser control. Most development languages include such a control. In this example, our app uses the System.Windows.Forms.WebBrowser class. After sign in is complete, all subsequent Live Connect API calls can be accomplished by using the System.Net.WebRequest class. Use the web browser control to start the sign-in, passing a URL similar to this one.

https://login.live.com/oauth20_authorize.srf?client_id=YOUR_CLIENT_ID&scope=YOUR_SCOPE_STRING&response_type=code&redirect_uri=https://login.live.com/oauth20_desktop.srf

Note

Mobile apps that use the client-side app flow should append &display=touch to the authorize URL.

This URL displays the standard Live Connect sign-in page. Note that the redirect_uri parameter specifies the Live Connect URL that is designed for desktop apps as described in the previous section. Use this URL whenever you need to supply a redirect Uniform Resource Identifier (URI). The response_type and scope parameters are also required. The value of the response_type parameter must be set to code.

After the user grants consent, the Live Connect APIs return a URI that contains the authorization code. It looks like the URI in the following example.

https://login.live.com/oauth20_desktop.srf#code=AUTHORIZATION_CODE

Tip If the wl.offline_access scope is specified, a refresh token is also provided.

Your app can read the authorization code from the returned URL, and use it to retrieve an access token by making a call that passes a URL similar to this one.

POST https://login.live.com/oauth20_token.srf

Content-type: application/x-www-form-urlencoded

client_id=YOUR_CLIENT_ID&client_secret=YOUR_CLIENT_SECRET&redirect_uri=https://login.live.com/oauth20_desktop.srf&code=AUTHORIZATION_CODE&grant_type=authorization_code

Finally, your app can read the token data from the returned URL and use that data to make further requests from the Live Connect APIs by using the System.Net.WebRequest class.

If the wl.offline_access scope was specified in the initial request, your app can convert the refresh token into an access token by making an HTTP POST request like the one shown here.

POST https://login.live.com/oauth20_token.srf

Content-type: application/x-www-form-urlencoded

client_id=YOUR_CLIENT_ID&client_secret=YOUR_CLIENT_SECRET&redirect_uri=https://login.live.com/oauth20_desktop.srf&grant_type=refresh_token&refresh_token=REFRESH_TOKEN

Top

Building an app

In this walkthrough, you build a simple WPF app that enables signing in to Live Connect, and then retrieves some user data after sign in is complete. The app also displays the access token. Before you start this exercise, you must visit the Live Connect app management site to get a client ID and a client secret, if you don't have them already. Be sure to leave the Redirect Domain field blank, select Yes for the Mobile client app option, and make a note of your client ID and client secret.

Create a new project

  1. Start Visual Studio 2010.
  2. Click File > New Project.
  3. In Installed Templates, click Visual C# > WPF Application.
  4. In the Name field, type DesktopDemo.
  5. Click OK to create the project.

Add the browser window

  1. In Solution Explorer, right-click the project name, select Add, then select New Item.
  2. In the Add New Item dialog box, select Window (WPF).
  3. In the Name field, enter BrowserWindow.xaml.
  4. Click Add to add the window to the project.
  5. Open BrowserWindow.xaml and replace the file's contents with the following Extensible Application Markup Language (XAML) code.
    XAML
    <Window x:Class="DesktopDemo.BrowserWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Sign In" Height="460" Width="400">
    <Grid>
        <WebBrowser Height="420" HorizontalAlignment="Left" Name="webBrowser" VerticalAlignment="Top" Width="380" LoadCompleted="webBrowser_LoadCompleted" />
    </Grid>
</Window>

    BrowserWindow.xaml contains a WebBrowser control, which is used to display the Live Connect consent page.

  6. Open BrowserWindow.xaml.cs and replace the file's contents with the following code. Be sure to substitute your own client ID for the value of client_id.
    C#
    using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Text.RegularExpressions;

namespace DesktopDemo
{
    public partial class BrowserWindow : Window
    {
        static string scope = "wl.basic";
        static string client_id = "YOUR_CLIENT_ID";
        static Uri signInUrl = new Uri(String.Format(@"https://login.live.com/oauth20_authorize.srf?client_id={0}&redirect_uri=https://login.live.com/oauth20_desktop.srf&response_type=code&scope={1}", client_id, scope));
        MainWindow mainWindow = new MainWindow();

        public BrowserWindow()
        {
            InitializeComponent();
            webBrowser.Navigate(signInUrl);
        }

        private void webBrowser_LoadCompleted(object sender, System.Windows.Navigation.NavigationEventArgs e)
        {
            if (e.Uri.AbsoluteUri.Contains("code="))
            {
                if (App.Current.Properties.Contains("auth_code"))
                {
                    App.Current.Properties.Clear();
                }
                string auth_code = Regex.Split(e.Uri.AbsoluteUri, "code=")[1];
                App.Current.Properties.Add("auth_code", auth_code);
                this.Close();
            }
        }
    }
}

    The code in BrowserWindow.xaml.cs handles two basic tasks. When the window opens, BrowserWindow.xaml.cs directs the WebBrowser control to the Live Connect sign-in page by using the URI value defined in the signInUrl variable. It then monitors the webBrowser_LoadCompleted event handler. After the user signs in, it parses the Representational State Transfer (REST) response to find the authorization code and then adds it to App.Current.Properties. Note that App.Current.Properties was used to keep this example simple. In an actual app, you would persist data by using a different mechanism, such as a database.

  7. Save the project.

Add the main window controls

  1. In Solution Explorer, right-click the project name, and then click Properties.
  2. On the Application tab, in the Target framework list, click .NET Framework 4. If you are prompted to enable Visual Studio to close and then reopen the project, click Yes.
  3. In Solution Explorer, right-click References, and then click Add Reference.
  4. In the .NET tab, click System.Web.Extensions.
  5. Click Add to add the reference.
  6. Open MainWindow.xaml to view the default form.
  7. Replace the file's contents with the following XAML code.
    XAML
    <Window x:Class="DesktopDemo.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Desktop App Demo" Height="500" Width="700" Unloaded="Window_Unloaded">
    <Grid>
        <Image Height="110" HorizontalAlignment="Left" Margin="12,12,0,0" Name="imgUser" Stretch="Fill" VerticalAlignment="Top" Width="110" />
        <TextBox Height="110" HorizontalAlignment="Left" Margin="12,128,0,0" Name="txtUserInfo" VerticalAlignment="Top" Width="654" TextWrapping="Wrap" VerticalScrollBarVisibility="Auto" />
        <Button Content="Click to Sign In" Height="23" HorizontalAlignment="Center" Margin="261,99,260,0" Name="btnSignIn" VerticalAlignment="Top" Width="157" Click="btnSignIn_Click" />
        <TextBox Height="172" HorizontalAlignment="Left" Margin="12,244,0,0" Name="txtToken" VerticalAlignment="Top" Width="654" TextWrapping="Wrap" VerticalScrollBarVisibility="Auto" />
        <Button Content="Clear App Settings" Height="23" HorizontalAlignment="Left" Margin="12,426,0,0" Name="btnClear" VerticalAlignment="Top" Width="162" Click="btnClear_Click" />
    </Grid>
</Window>
  8. Save and close MainWindow.xaml.

Add initialization and request code

  1. In Solution Explorer, open MainWindow.xaml.cs.
  2. Add the following using statements after the default using statements but before the DesktopDemo namespace declaration.
    C#
    using System.Web.Script.Serialization;
using System.Net;
using System.IO;
  3. After the MainWindow class declaration, but before the MainWindow constructor, add the following variables.
    C#
    static string client_id = "YOUR CLIENT ID";
static string client_secret = "YOUR CLIENT SECRET";
static string accessTokenUrl = String.Format(@"https://login.live.com/oauth20_token.srf?client_id={0}&client_secret={1}&redirect_uri=https://login.live.com/oauth20_desktop.srf&grant_type=authorization_code&code=", client_id, client_secret);
static string apiUrl = @"https://apis.live.net/v5.0/";
public Dictionary<string, string> tokenData = new Dictionary<string, string>();

    The client_id and client_secret variables, as their names imply, represent your client ID and client secret. (Be sure to substitute your own client ID for the value of client_id and your own client secret for the value of client_secret.) The accessTokenUrl variable represents the base call to retrieve an access token. The tokenData variable is used to retrieve the access token to be stored for use later. The apiUrl variable represents the base call to retrieve user info.

  4. Add the following functions immediately after the MainWindow constructor.
    C#
    private void getAccessToken()
{
    if (App.Current.Properties.Contains("auth_code"))
    {
        makeAccessTokenRequest(accessTokenUrl + App.Current.Properties["auth_code"]);
    }
}

private void makeAccessTokenRequest(string requestUrl)
{
    WebClient wc = new WebClient();
    wc.DownloadStringCompleted += new DownloadStringCompletedEventHandler(accessToken_DownloadStringCompleted);
    wc.DownloadStringAsync(new Uri(requestUrl));
}

void accessToken_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
    tokenData = deserializeJson(e.Result);
    if (tokenData.ContainsKey("access_token"))
    {
        App.Current.Properties.Add("access_token", tokenData["access_token"]);
        getUserInfo();
    }
}

private Dictionary<string, string> deserializeJson(string json)
{
    var jss = new JavaScriptSerializer();
    var d = jss.Deserialize<Dictionary<string, string>>(json);
    return d;
}

private void getUserInfo()
{
    if (App.Current.Properties.Contains("access_token"))
    {
        makeApiRequest(apiUrl + "me?access_token=" + App.Current.Properties["access_token"]);
    }
}

private void makeApiRequest(string requestUrl)
{
    WebClient wc = new WebClient();
    wc.DownloadStringCompleted += new DownloadStringCompletedEventHandler(client_DownloadStringCompleted);
    wc.DownloadStringAsync(new Uri(requestUrl));
}

void client_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
    changeView(e.Result);
}

    The getAccessToken function uses the authorization code that was retrieved after the user signed in, along with calls to the makeAccessTokenRequest function, the accessToken_DownloadStringCompleted event handler, and the deserializeJson function, to get an access token. After the code gets the access token, the getUserInfo function calls the makeApiRequest function and the client_DownloadStringCompleted event handler to get the user's info. After the code gets the user's info, the changeView function displays the user's info, as described in the next section.

    Note

    If you are migrating from the legacy Windows Live ID Web Authentication SDK, you can use the techniques described in Single sign-on and for apps and websites to return a uid value from the authentication_token property in the JSON tokenData variable that's referenced within the accessToken_DownloadStringCompleted event handler.

  5. Save MainWindow.xaml.cs.

Add code to update the UI

  1. Paste the following code after the client_DownloadStringCompleted event handler.
    C#
    private void changeView(string result)
{
    btnSignIn.Visibility = Visibility.Collapsed;
    txtUserInfo.Text = result;
    string imgUrl = apiUrl + "me/picture?access_token=" + App.Current.Properties["access_token"];
    imgUser.Source = new BitmapImage(new Uri(imgUrl, UriKind.RelativeOrAbsolute));
    txtToken.Text += "access_token = " + App.Current.Properties["access_token"] + "\r\n\r\n";
}

    The changeView function updates the UI to display the user data that is returned by the request.

  2. Paste the code for the following two functions after the changeView function.
    C#
    private void btnSignIn_Click(object sender, RoutedEventArgs e)
{
    BrowserWindow browser = new BrowserWindow();
    browser.Closed += new EventHandler(browser_Closed);
    browser.Show();
}

private void btnClear_Click(object sender, RoutedEventArgs e)
{
    App.Current.Properties.Clear();
    btnSignIn.Visibility = Visibility.Visible;
    txtToken.Text = "";
    imgUser.Source = null;
    txtUserInfo.Text = "";
}

    These are the event handlers for each of the buttons. The btnSignIn_Click handler launches the BrowserWindow window, and the btnClear_Click handler deletes all session data and refreshes the UI. (btnClear_Click is intended as a convenience while you are experimenting with the code).

  3. Paste the following code after btnClear_Click.
    C#
    void browser_Closed(object sender, EventArgs e)
{
    getAccessToken();
}

private void Window_Unloaded(object sender, RoutedEventArgs e)
{
    Application.Current.Shutdown();
}

    The browser_Closed event handler calls getAccessToken, which uses the authorization code to get the access token. (The Window_Unloaded event simply quits the app.)

  4. Now it's time to build and test the project. Press F5 to build and run the project. Click the Click to Sign In button. Sign in with a Microsoft account email address and password. The app displays the user's photo and other info along with the access token value.

Top


Community resources

If you have questions about calling the Live Connect APIs from your code, or if you want to learn more beyond this documentation, see the following resources:

  • Live Connect Developer Center—Provides links to helpful tools, code samples, blogs, and additional learning content.
  • Live Connect Forum—Offers opportunities to ask technical questions, get answers from subject-matter experts and enthusiasts, and read and search for questions and answers from others.


Live SDK core concepts

Before you call the Live Connect APIs, you should feel comfortable with a set of core concepts that apply to all app types. These core concepts include how to get the correct access levels to begin working with users' info; how to work with users' info by using Representational State Transfer (REST) and OAuth 2.0; how to take advantage of single sign-on scenarios; how to reference the Live Connect APIs; how to sign a user in; and how to get the signed-in user's permission for your app to work with his or her info in Hotmail, Microsoft SkyDrive, Windows Live Messenger, and other services that are compatible with Live Connect.

  • Scopes and permissions

    How to get permission from a user to access that user's info or to create new objects on behalf of that user.

  • REST reference

    How to use REST with Live Connect to access info programmatically about users, their contacts and friends, their web-based activities and personal statuses, their media stored on SkyDrive, and more.

  • Referencing the APIs

    How to begin coding with the Live Connect APIs.

  • Signing users in

    How your app can enable a user to sign in.

  • Obtaining user consent

    How your app can get a signed-in user's permission, or consent, to work with his or her info.

  • Getting user data

    How your app can begin working with a signed-in user's info.

  • Single sign-on for apps and websites

    How to design your apps and websites so that users don't have to sign in with their credentials multiple times when they access related resources.

  • Server-side scenarios

    How to use server-side scripts to interact directly with Live Connect by using REST.

  • OAuth 2.0

    How Live Connect implements the OAuth 2.0 protocol's authorization flows to authenticate users and to provide your apps with permission to access authenticated users' info.

  • Supported locales

    How client-side JavaScript websites and scripts can use localized versions of the Live Connect JavaScript API (web) and consent page for better code performance and increased user satisfaction.

These core concepts build on the info in Getting started. After you learn these concepts, we encourage you to begin working with the code examples in areas such as Identity (profiles), Hotmail (contacts and calendars), SkyDrive (files and photos), and Messenger (instant messaging). You can also go straight to the Live Connect API Reference to get info to further customize your apps.


Scopes and permissions

Before your app makes requests of the Live Connect APIs to work with Live Connect info, in most cases you must get permission from the user to access that info or to create new objects on behalf of the user. In the Live Connect APIs, this permission is called a scope. Each scope grants a different permission level. You'll find more info about each scope in this topic. For info about requesting a scope and obtaining user consent, see Obtaining user consent.

  • Scope types
  • Core scopes
  • Extended scopes
  • Developer scopes
  • Subset and superset behavior
  • Accessing a user's public info
  • Scope details

Scope types

There are three types of scopes:

  • Core scopes are central to the Live Connect APIs and involve users' core profile and contact data.
  • Extended scopes allow you to work with users' extended profile and contact data.
  • Developer scopes allow you to work with developers' client IDs.

Top

Core scopes

Scope | Enables
wl.basic | Read access to a user's basic profile info. Also enables read access to a user's list of contacts.
wl.offline_access | The ability of an app to read and update a user's info at any time. Without this scope, an app can access the user's info only while the user is signed in to Live Connect and is using your app.
wl.signin | Single sign-in behavior. With single sign-in, users who are already signed in to Live Connect are also signed in to your website.

Top

Extended scopes

Scope | Enables
wl.birthday | Read access to a user's birthday info including birth day, month, and year.
wl.calendars | Read access to a user's calendars and events.
wl.calendars_update | Read and write access to a user's calendars and events.
wl.contacts_birthday | Read access to the birth day and birth month of a user's contacts. Note that this also gives read access to the user's birth day, birth month, and birth year.
wl.contacts_create | Creation of new contacts in the user's address book.
wl.contacts_calendars | Read access to a user's calendars and events. Also enables read access to any calendars and events that other users have shared with the user.
wl.contacts_photos | Read access to a user's albums, photos, videos, and audio, and their associated comments and tags. Also enables read access to any albums, photos, videos, and audio that other users have shared with the user.
wl.contacts_skydrive | Read access to Microsoft SkyDrive files that other users have shared with the user. Note that this also gives read access to the user's files stored in SkyDrive.
wl.emails | Read access to a user's personal, preferred, and business email addresses.
wl.events_create | Creation of events on the user's default calendar.
wl.messenger | Enables signing in to the Windows Live Messenger Extensible Messaging and Presence Protocol (XMPP) service.
wl.phone_numbers | Read access to a user's personal, business, and mobile phone numbers.
wl.photos | Read access to a user's photos, videos, audio, and albums.
wl.postal_addresses | Read access to a user's postal addresses.
wl.share | Enables updating a user's status message.
wl.skydrive | Read access to a user's files stored in SkyDrive.
wl.skydrive_update | Read and write access to a user's files stored in SkyDrive.
wl.work_profile | Read access to a user's employer and work position information.

Top

Developer scopes

Scope | Enables
wl.applications | Read access to a developer's client IDs that have been created to work with the Live Connect APIs.
wl.applications_create | Creation of new client IDs on behalf of a developer.

Top

Subset and superset behavior

Certain scopes give access to a subset of the data that is addressed by other scopes. For example, wl.birthday gives access to the user's birthday, but wl.contacts_birthday gives access both to the user's birthday and to birthdays of the user's Messenger friends. In requests that specify multiple scopes, if one scope is a superset of another, the subset scope is ignored. Likewise, if an app has been granted access to a subset scope (for example, wl.birthday), and the user later grants access to a superset scope (for example, wl.contacts_birthday), the subset scope is revoked as redundant. The following table shows the scopes that share a subset/superset relationship.

Subset scope | Superset scopes
wl.birthday | wl.contacts_birthday
wl.calendars | wl.contacts_calendars wl.calendars_update
wl.photos | wl.contacts_photos
wl.skydrive | wl.contacts_skydrive wl.skydrive_update
wl.applications | wl.applications_create

Top

Accessing a user's public info

There is an exception to the rule that you must get the permission from the user before you can access his or her info: your app can access a user's publicly available info without requesting any scope. Public info includes the user's ID, first and last names, display name, gender, locale, and picture. The user's Messenger friends list is also available if the user has elected to make it public. For example, the following GET request, without any access token specified, returns the user's public profile info.

https://apis.live.net/v5.0/8c8ce076ca27823f

The info returned by Live Connect looks like the following.

{
   "id": "8c8ce076ca27823f",
   "name": "Roberto Tamburello",
   "first_name": "Roberto",
   "last_name": "Tamburello",
   "gender": null,
   "locale": "en_US"
}

As another example, a GET request for the user's picture, also without any access token specified, looks like the following.

https://apis.live.net/v5.0/8c8ce076ca27823f/picture

The request would be redirected to a URL that might look like the following.

http://blufiles.storage.msn.com/y1m9UZK4sELhooi0vvVFy0DvE0xIMPK-lZXeZQohhW9LmEXwLHZHyh9ue2c3oWnrTqx0r5q3J9N5KtFI58Rfy-u-Q

Top

Scope details

The following sections provide additional details about the available scopes.

In several of these sections, the Live Connect Representational State Transfer (REST) objects and the corresponding structures that these scopes can access are described in tables. For more info about these REST objects and structures, see REST reference.

wl.applications

The wl.applications scope enables read access to a developer's client IDs.

This scope enables read access to all of the Application object's structures.

Top

wl.applications_create

The wl.applications_create scope enables the programmatic creation of new client IDs on behalf of a developer.

Similar to the wl.applications scope, this scope enables access to all of the Application object's structures.

Note When a user consents to the wl.applications_create scope, the user also implicitly consents to the info that is accessible with the wl.applications scope. However, if the user consents to the wl.applications scope and then later consents to the wl.applications_create scope, the wl.applications scope is revoked because wl.applications is a subset of wl.applications_create and is therefore redundant.

Top

wl.basic

The wl.basic scope enables read access to a user's basic profile info and to the user's list of contacts.

The following table lists the structures that can be accessed with user consent to the wl.basic scope.

REST object | Structure
User | link
User | updated_time
Contact | id
Contact | first_name
Contact | last_name
Contact | name
Contact | gender
Contact | is_friend
Contact | is_favorite
Contact | user_id
Contact | email_hashes
Contact | birth_day (also requires the wl.contacts_birthday scope)
Contact | birth_month (also requires the wl.contacts_birthday scope)
Contact | updated_time

Top

wl.birthday

The wl.birthday scope enables read access to a user's birth-date info.

The following table lists the structures that can be accessed with user consent to the wl.birthday scope.

REST object | Structure
User | birth_day
User | birth_month
User | birth_year

Top

wl.calendars

The wl.calendars scope enables read access to a user's calendars and events.

Top

wl.calendars_update

The wl.calendars_update scope enables read and write access to a user's calendars and events.

Top

wl.contacts_birthday

The wl.contacts_birthday scope enables read access to birth-date info for a user's contacts.

The following table lists the structures that can be accessed with user consent to the wl.contacts_birthday scope.

REST object | Structure
Contact | birth_day (also requires the wl.basic scope)
Contact | birth_month (also requires the wl.basic scope)

Note When a user consents to the wl.contacts_birthday scope, the user also implicitly consents to access to the info that is covered by the wl.birthday scope. However, if the user consents to the wl.birthday scope and then later consents to the wl.contacts_birthday scope, the wl.birthday scope is revoked because it is a subset of wl.contacts_birthday and is therefore redundant.

Top

wl.contacts_create

The wl.contacts_create scope enables the creation of contacts in a user's address book.

Top

wl.contacts_calendars

The wl.contacts_calendars scope enables read access to a user's calendars and events, and read access to calendars and events that other users have shared with the user. Permissions to shared calendars and events are restricted by the permissions that have been granted to the consenting user.

Note When a user consents to the wl.contacts_calendars scope, the user also implicitly consents to access to the info that is covered by the wl.calendars scope. However, if the user consents to the wl.calendars scope and then later consents to the wl.contacts_calendars scope, the wl.calendars scope is revoked because it is a subset of wl.contacts_calendarsand is therefore redundant.

Top

wl.contacts_photos

The wl.contacts_photos scope enables read access to a user's albums, photos, videos, and audio and to their associated comments and tags. This scope also enables read access to any albums, photos, videos, and audio that other users have shared with the user.

This scope enables read access to all of the structures of the Album, Audio, Photo, and Video objects for a Messenger friend.

Note When a user consents to the wl.contacts_photos scope, the user also implicitly consents to access to the info that is covered by the wl.photos scope. However, if the user consents to the wl.photos scope and then later consents to the wl.contacts_photos scope, the wl.photos scope is revoked because it is a subset of wl.contacts_photosand is therefore redundant.

Top

wl.contacts_skydrive

The wl.contacts_skydrive scope enables read access to SkyDrive files that other users have shared with the user.

Note When a user consents to the wl.contacts_skydrive scope, the user also implicitly consents to access to the info that is covered by the wl.skydrive scope. However, if the user consents to the wl.skydrive scope and then later consents to the wl.contacts_skydrive scope, the wl.skydrive scope is revoked because it is a subset of wl.contacts_skydriveand is therefore redundant.)

Top

wl.emails

The wl.emails scope enables read access to a user's email addresses.

The following table lists the structures that can be accessed with user consent to the wl.emails scope.

REST object | Structure
User | emails
User | preferred (emails object)
User | account (emails object)
User | personal (emails object)
User | business (emails object)

Top

wl.events_create

The wl.events_create scope enables the creation of events on the user's default calendar.

This scope enables access to all of the Event object's structures.

Top

wl.messenger

The wl.messenger scope enables signing in to the Messenger XMPP service. For more information, see Getting started using Messenger with XMPP.

Top

wl.offline_access

The wl.offline_access scope enables an app to read and update a user's info at any time. Without this scope, an app can access the user's info only while the user is signed in to Live Connect and is using the app.

Top

wl.phone_numbers

The wl.phone_numbers scope enables access to a user's phone numbers.

The following table lists the structures that can be accessed with user consent to the wl.phone_numbers scope.

REST object | Structure
User | phones
User | personal (phones object)
User | business (phones object)
User | mobile (phones object)

Top

wl.photos

The wl.photos scope enables read access to a user's photos, videos, audio, and albums.

This scope enables read access to all of the structures of the Album, Audio, Photo, and Video objects for a user.

Top

wl.postal_addresses

The wl.postal_addresses scope enables read access to a user's postal addresses.

The following table lists the structures that can be accessed with user consent to the wl.postal_addresses scope.

REST object | Structure
User | addresses
User | personal (addresses object)
User | street (personal object)
User | street_2 (personal object)
User | city (personal object)
User | state (personal object)
User | postal_code (personal object)
User | region (personal object)
User | business (addresses object)
User | street (business object)
User | street_2 (business object)
User | city (business object)
User | state (business object)
User | postal_code (business object)
User | region (business object)

Top

wl.share

The wl.share scope enables the creation of activities on a user's activity feed and status message.

This scope enables access to all of the structures of the Activity object.

Top

wl.signin

The wl.signin scope enables single sign-in behavior. Users who are already signed in to Live Connect are also signed in to your app and therefore do not have to enter their credentials.

For info about the sign-in process, see Signing users in.

Top

wl.skydrive

The wl.skydrive scope enables read access to a user's files stored on SkyDrive.

Top

wl.skydrive_update

The wl.skydrive_update scope enables read and write access to a user's files stored on SkyDrive.

Top

wl.work_profile

The wl.work_profile scope enables read access to a user's employer and work position info.

The following table lists the structures that can be accessed with user consent to the wl.work_profile scope.

REST object | Structure
User | work
User | employer (work array)
User | name (employer object)
User | position (work array)
User | name (position object)

Top


REST reference

The Live Connect Representational State Transfer (REST) API enables apps that work with Live Connect to access info programmatically about users, their contacts and friends, their web-based activities and personal status, their media stored on Microsoft SkyDrive, and more.

This topic contains the following sections:

  • Supported HTTP verbs
  • Support for resumable downloads
  • Understanding the objects
  • Query parameters
    • Structure value options
    • Activity object
    • Album object
    • Application object
    • Audio object
    • Calendar object
    • Comment object
    • Contact object
    • Error object
    • Event object
    • File object
    • Folder object
    • Friend object
    • Permissions object
    • Photo object
    • Tag object
    • User object
    • Video object
    • Additional URL parameters

    Supported HTTP verbs

    The Live Connect REST API supports the standard HTTP verbs.

    • GET—Returns a representation of a resource.
    • POST—Adds a new resource to a collection.
    • PUT—Updates a resource at the location pointed by the URL or creates a new resource, if it doesn't exist.
    • DELETE—Deletes a resource.
    • MOVE—Moves the location of a resource.
    • COPY—Duplicates a resource.

    Request URLs must reference https://apis.live.net/v5.0/, followed by the path for the object you are working with, any parameters, and finally, the access token (represented here as ACCESS_TOKEN).

    https://apis.live.net/v5.0/me/albums?access_token=ACCESS_TOKEN

    Top

    Support for resumable downloads

    Live Connect provides support for resumable downloads by using the HTTP Range header. If a download is interrupted, an app can continue the download at a later time by requesting only the byte range for the remainder of the file. This is particularly useful when downloading larger files, or in situations where network reliability is less than optimal.

    Top

    Understanding the objects

    In the Live Connect REST API, each category of info is contained in an object. Objects consist of a combination of child objects, arrays, and values. To access a specific object, you need to know the unique path to, and in many cases, the unique ID of, that object.

    The following table lists the objects that are supported by Live Connect REST API requests, along with valid object paths.

    Object | Description | Valid object paths
Activity | An activity in a user's activity feed and status message. | /me/share /USER_ID/share
Album | A user's album in SkyDrive. Albums can contain combinations of photos, videos, audio, files, and folders. | /me/albums /USER_ID/albums /ALBUM_ID An Album object can be returned as part of /ALBUM_ID/files, /me/skydrive/files, /me/skydrive/shared/files, /me/skydrive/shared/albums, or /USER_ID/skydrive/files.
Application | Info about a client ID that works with Live Connect. | /me/applications /USER_ID/applications /APPLICATION_ID
Audio | A user's audio file in SkyDrive. | /AUDIO_ID An Audio object can be returned as part of /ALBUM_ID/files, /FOLDER_ID/files, /me/skydrive/files, or USER_ID/skydrive/files.
Calendar | A user's calendar. | /me/calendars /USER_ID/calendars /CALENDAR_ID
Comment | A comment that is made by a user on a photo or a video in SkyDrive. | /PHOTO_ID/comments /VIDEO_ID/comments /COMMENT_ID
Contact | A user's Hotmail contact. (If the contact's is_friend value is set to true, the contact is also the user's friend.) | /me/contacts /USER_ID/contacts /CONTACT_ID
Error | Info about an error that is returned by the Live Connect APIs. | None.
Event | An event on a user's calendar. | /me/events /USER_ID/events /CALENDAR_ID/events
File | A user's file in SkyDrive. | /FILE_ID A File object can be returned as part of /FOLDER_ID/files, /me/skydrive/files, /me/skydrive/shared, /me/skydrive/shared/files, or /USER_ID/skydrive/files.
Folder | A user's folder in SkyDrive. Folders can contain combinations of photos, videos, audio, files (such as Microsoft Office documents), and subfolders. | /FOLDER_ID A Folder object can be returned as part of /FOLDER_ID/files, /me/skydrive/files, /me/skydrive/shared/files, /USER_ID/skydrive/files, or /ALBUM_ID/files.
Friend | A user's friend. Friends are a subset of a user's contacts and reflect people that the user has a publicly visible relationship with. Explicit permission is not required to view a user's friends. Because Friend returns less data than Contact, it's more compact for scenarios where only the names and IDs of the user's friends are needed. | /me/friends /USER_ID/friends
Permissions | A list of scopes. | /me/permissions /USER_ID/permissions
Photo | A user's photo in SkyDrive. | /PHOTO_ID A Photo object can be returned as part of /ALBUM_ID/files, /ALBUM_ID/photos, /FOLDER_ID/files, /me/skydrive/files, /me/skydrive/shared/photos, or USER_ID/skydrive/files.
Tag | A tag that is associated with a photo or a video in SkyDrive. | /PHOTO_ID/tags /VIDEO_ID/tags /TAG_ID
User | A user. | /me /USER_ID
Video | A user's video in SkyDrive. | /VIDEO_ID A Video object can be returned as part of /ALBUM_ID/files, /ALBUM_ID/videos, /FOLDER_ID/files, /me/skydrive/files, /me/skydrive/shared/videos, or USER_ID/skydrive/files.

    In the preceding table, replace USER_ID, CONTACT_ID, ALBUM_ID, PHOTO_ID, VIDEO_ID, AUDIO_ID, FOLDER_ID, or APPLICATION_ID with the target user ID, Contact object ID, Album object ID, Photo object ID, Video object ID, Audio object ID, Folder object ID, or Application object ID or Live Connect client ID, respectively.

    In the preceding table, you can use /me as a shortcut for the signed-in user instead of specifying /USER_ID. However, you cannot use /me unless you also provide an access token.

    The Live Connect REST API exchanges info between apps, Live Connect, and SkyDrive in JavaScript Object Notation (JSON) format. (Because of this, the JSON terms structure, object, array, and value are used throughout this reference.)

    When your app makes a GET request for an object, the Live Connect REST API returns the requested info as a JSON-formatted structure. Similarly, when your app makes a POST or PUT request, the Live Connect REST API requires the info to be submitted to it as a JSON-formatted structure. For more info about JSON, see Introducing JSON (http://www.json.org).

    Top

    Query parameters

    Query parameters can be added to the end of the request URL to modify the information returned in the response. The parameters described in this section are used to specify a particular subset of the response. Additional URL parameters can also be added to specify how to return the results.

    Filter query parameter

    You can use the filter query parameter to specify the types of items to return when requesting SkyDrive items, as shown here.

/FOLDER_ID/files?filter=albums

    The following values are supported:

    • albums

    • audio

    • folders

    • photos

    • videos

    When specifying multiple values, use a comma-delimited list like this.

/FOLDER_ID/files?filter=videos,audio

    The filter query parameter is supported for any request that returns a list of SkyDrive items, for example, queries ending in /files, or /shared.

    Limit query parameter

    The limit parameter restricts the number of entries returned. This example uses the limit query parameter so that the command returns only the first two of the user's contacts.

me/contacts?limit=2

    You can use this parameter with the offset parameter to select specific entries within a collection.

    Note In the JSON-formatted object that's returned, you can look in the paging object for the previous and next structures to get the offset and limit parameter values of the previous and next entries.

    Offset query parameter

    The offset parameter specifies the first entry to return from a collection. This example uses the offset parameter with the limit parameter to return two of the user's calendar entries, starting with the third one. That is, it will return entries 3 and 4 from the user's calendar.

me/calendars?limit=2&offset=3

    You can use this parameter with the limit parameter to select specific entries within a collection.

    Note In the JSON-formatted object that's returned, you can look in the paging object for the previous and next structures to get the offset and limit parameter values of the previous and next entries.

    Top

    Structure value options

    In the following sections, the column labeled "R/W" indicates whether a value is read-only or read/write, and the column labeled "Required on create" indicates whether a value is required for the creation of an object.

    Top

    Activity object

    The Activity object contains info about activities in a user's activity feed and status message. The Live Connect REST API supports creating Activity objects. Use the wl.share scope to create Activity objects.

    The Activity object contains the following structures.

    Structure | Type | R/W | Required on create | Description
from | object | R |  | Info about the user who shared the activity. This structure is visible only in the Activity object that is returned if the activity was successfully shared.
name (from object) | string | R |  | The name of the user who shared the activity. This structure is visible only in the Activity object that is returned if the activity was successfully shared.
id (from object) | string | R |  | The Live ID of the user who shared the activity. This structure is visible only in the Activity object that is returned if the activity was successfully shared.
message | string | RW | Yes | The text of the message.
link | string | RW |  | The URL of the content to share.
description | string | RW |  | A description of the content to share.
picture | string | RW |  | The URL of a thumbnail image of the content to share.
name | string | RW |  | The title of the content to share.
source | string | RW |  | The URL to the video source file, if this is a video activity.

    Some activity types have required and optional structures, as described in the following table.

    Activity type | Required structures | Allowed optional structures
Text | message | None (description, picture, name, and source must not be present).
Text with a link | message, link | description, picture, name If picture is included, it refers to a preview or thumbnail view of the content.
Video | message, link, source | description, picture, name If picture is included, it refers to a preview or thumbnail view of the content.

    Sharing one of these activity types without specifying its required structures will return an error.

    Important Values for Activity object structures must not exceed 512 characters, with the exception of the source structure value, which must not exceed 487 characters. If the value for either the link or source field exceeds the respective maximum limit, the call returns an error. For all other structures, values that exceed the maximum length are truncated and sent.

    The following is an example of an Activity object.

    {
    "message": "Explore Windows Live Hotmail",
    "link": "http://explore.live.com/windows-live-hotmail",
    "description": "Give us 15 seconds...we'll show you the new Hotmail!",
    "picture": "http://res2.explore.live.com/...part of URL omitted for brevity...fd39.jpg",
    "name": "Windows Live Hotmail Home"
}

    To create an Activity object by using the Live Connect REST API, make a POST request to /me/share. Include the properties for the activity in the request body, as shown here.

    Content-Type: application/json

{
    "message": "Explore Windows Live Hotmail",
    "link": "http://explore.live.com/windows-live-hotmail",
    "description": "Give us 15 seconds...we'll show you the new Hotmail!",
    "picture": "http://res2.explore.live.com/...part of URL omitted for brevity...fd39.jpg",
    "name": "Windows Live Hotmail Home"
}

    To learn how to create other activity types, see Sharing a user's status.

    Note

    If the call is successful in this example, the Live Connect REST API returns the following JSON-formatted object.

    {
   "from": {
      "name": "Roberto Tamburello",
      "id": "8c8ce076ca27823f"
   },
   "message": ...The message value...,
   "link": ...The link value, if one was provided, otherwise null...,
   "description": ...The description value, if one was provided, otherwise null...,
   "picture": ...The picture value, if one was provided, otherwise null...,
   "name": ...The name value, if one was provided, otherwise null...,
   "source": ...The source value, if one was provided, otherwise null...
}

    Top

    Album object

    The Album object contains info about a user's albums in Microsoft SkyDrive. Albums are stored at the root level of a user's SkyDrive directory, and can contain combinations of photos, videos, audio, files, and folders. The Live Connect REST API supports reading Album objects. Use the wl.photos scope to read a user's Album objects. Use the wl.skydrive scope to read a user's files. Use the wl.contacts_photos scope to read any albums, photos, videos, and audio that other users have shared with the user.

    The Album object contains the following structures.

    Structure Type R/W Required on create Description

    data

    array

    R

    An array container for Album objects when a collection of objects is returned.

    id

    string

    R

    The Album object's ID.

    from

    object

    R

    Info about the user who authored the album.

    name (from object)

    string

    R

    The name of the user who authored the album.

    id (from object)

    string

    R

    The Live ID of the user who authored the album.

    name

    string

    RW

    Yes

    The name of the album.

    description

    string/null

    RW

    A description of the album, or null if no description is specified.

    parent_id

    string

    R

    The resource ID of the parent.

    upload_location

    string

    R

    The URL to upload items to the album, hosted in SkyDrive. Requires the wl.skydrive scope.

    is_embeddable

    true/false

    R

    A value that indicates whether this album can be embedded. If this album can be embedded, this value is true; otherwise, it is false.

    count

    number

    R

    The total number of items in the album.

    link

    string

    R

    A URL of the album, hosted in SkyDrive.

    type

    string

    R

    The type of object; in this case, "album".

    shared_with

    object

    R

    The object that contains permissions info for the album. Requires the wl.skydrive scope.

    access (shared_with object)

    string

    R

    A localized string that contains info about who can access the album. The options are:

    • People I selected
    • Just me
    • Everyone (public)
    • Friends
    • My friends and their friends
    • People with a link
    The default is Just me.

    created_time

    string

    R

    The time, in ISO 8601 format, at which the album was created.

    updated_time

    string

    R

    The time, in ISO 8601 format, at which the album was last updated.

    The following is an example of a collection of Album objects. (For brevity, only the first object is shown.)

    {
   "data": [
      {
         "id": "album.8c8ce076ca27823f.8C8CE076CA27823F!126",
         "from": {
            "name": "Roberto Tamburello",
            "id": "8c8ce076ca27823f"
         },
         "name": "My Sample Album 1",
         "description": "",
         "parent_id": "folder.de57f4126ed7e411",
         "upload_location": "https://apis.live.net/v5.0/folder.de57f4126ed7e411.DE57F4126ED7E411!126/files/",
         "is_embeddable": true
         "count": 4,
         "link": "https://cid-8c8ce076ca27823f.skydrive.live.com/redir.aspx?page\u003dself\u0026resid\u003d8C8CE076CA27823F!126\u0026type\u003d5",
         "type": "album",
         "shared_with": {
            "access": "Everyone (public)"
         },
         "created_time": "2011-04-21T23:19:47+0000",
         "updated_time": "2011-04-22T19:18:12+0000"
      }, {
         ...
      }
   ]
}

    To get a collection of Album objects by using the Live Connect REST API, make a GET request to /me/albums.

    Note To get an album's cover image, call /ALBUM_ID/picture.

    To create a new Album resource, make a POST request to /me/albums. Pass the name and description attributes in the request body, as shown here.

    {
   "name": "Vacation 2011",
   "description": "Photos from our fun vacation."
}

    To update the properties of an Album, make a PUT request to /ALBUM_ID. Pass the attributes to update in the request body, as shown here.

    {
   "name": "Maui Vacation 2011",
   "description": "Photos from our vacation on Maui."
}

    To delete an album, make a DELETE request to /ALBUM_ID.

    Top

    Application object

    The Application object contains info about a developer's client IDs that work with Live Connect. The Live Connect REST API supports reading and creating Application objects. Use the wl.applications scope to read Application objects, and use the wl.applications_create scope to create Application objects.

    The ability to create, read, update, and delete Application objects is useful for providers who build comment or sign-in widgets for use by third-party websites. Supplying an application ID for each website that uses the provider’s widget enables third-party sites to provide a redirect URL for OAuth authorization and track analytics for widget usage on https://manage.dev.live.com.

    The Application object contains the following structures.

    Structure | Type | R/W | Required on create | Description
data | array | R |  | An array of Application objects, if a collection of objects is returned.
id | string | R |  | The Application object's ID. Do not specify this structure when you create a client ID, because the system generates it automatically upon creation.
name | string | RW | Yes | The client ID's name.
client_id | string | R |  | The client ID. This structure is generated automatically upon creation.
client_secret | string | R |  | The client ID's client secret. This structure is generated automatically upon creation.
uri | string | RW | Yes | The client ID's redirect Uniform Resource Identifier (URI). This structure is required only when you create a client ID. When you read a client ID, this structure appears in the uri (uris array) structure.
uris | array | R |  | An array that contains the redirect URI info. This structure is generated automatically upon creation.
uri (uris array) | string | R |  | The redirect URI. This structure is generated automatically upon creation.
type (uris array) | string | R |  | The redirect URI type. The only valid value is "web". This structure is generated automatically upon creation.
terms_of_service_link | string | RW |  | The URL of the client ID's terms of service webpage.
privacy_link | string | RW |  | The URL of the client ID's privacy webpage.
picture | string | R |  | The URL to the picture associated with the application.
upload_location | string | R |  | The URL to upload a picture to be associated with the application.
created_time | string | R |  | The time, in ISO 8601 format, at which the client ID was created. This structure is generated automatically upon creation.
updated_time | string | R |  | The time, in ISO 8601 format, at which the client ID was last updated. This structure is generated automatically upon creation.

    The following is an example of a collection of Application objects. (For brevity, only the first object is shown.)

    {
  "data": [
      {
         "id": "application.000000004c043705",
         "name": "Pilot Live Connect App",
         "client_id": "000000004c043705",
         "client_secret": "O9L3tC4ecrCdLDaNsNC3m4mdiBm9gYi4",
         "uris": [
            {
               "uri": "http://www.contoso.com",
               "type": "web"
            }
         ],
         "terms_of_service_link": "http://www.contoso.com/terms_of_service.php",
         "privacy_link": "http://www.contoso.com/privacy.php",
         "picture": "https://public.dc1files.livefilestore.com/y1ppKKuiPyL82GBO149h-XhPxuPbD4iv0r-0IbITngBKpqEUShzTmxsj295NjLtLfmZxWZArsbYPG6FkhV7nKCPeg?psid=1",
         "upload_location": "https://apis.live.net/v5.0/application.000000004c043705/picture",
         "created_time": "2011-04-18T19:03:59+0000",
         "updated_time": "2011-04-25T18:24:26+0000"
      },  {
         ...
         }
   ]
}

    To get an Application object by using the Live Connect REST API, make a GET request to /me/applications.

    To create an Application object by using the Live Connect REST API, make a POST request to /me/applications. Include the properties for the Application object in the request body, as shown here.

    Content-Type: application/json

{
    "name": "Pilot Live Connect App",
    "uri": "http://www.contoso.com",
    "terms_of_service_link": "http://www.contoso.com/terms_of_service.php",
    "privacy_link": "http://www.contoso.com/privacy.php"
}

    Note

    If the call is successful, the Live Connect REST API returns the following JSON-formatted object.

    {
    "id": "application.000000004c043705",
    "name": "Pilot Live Connect App",
    "client_id": "000000004c043705",
    "client_secret": "O9L3tC4ecrCdLDaNsNC3m4mdiBm9gYi4",
    "uris": [
        {
            "uri": "http://www.contoso.com",
            "type": "web"
        }
    ],
    "terms_of_service_link": "http://www.contoso.com/terms_of_service.php",
    "privacy_link": "http://www.contoso.com/privacy.php",
    "picture": null
    "upload_location": "https://apis.live.net/v5.0/application.000000004c043705/picture",
    "created_time": "2011-04-18T19:03:59+0000",
    "updated_time": "2011-04-25T18:24:26+0000"
}

    To get an application’s logo, make a GET request to APPLICATION_ID/picture, where APPLICATION_ID is the value of the id structure, for example, application.000000004c043705/picture. A link to the location of the application’s logo is returned in the redirect response’s Location header. If you set the suppress_redirects query string parameter to true, as in application.000000004c043705/picture?suppress_redirects=true, a JSON object is returned in the response's body. This object has a single location structure whose value is a link that points to the location of the application’s logo.

    To upload an application's logo, make a POST or a PUT request to APPLICATION_ID/picture, or to the value of the location structure within the response to a GET call to /APPLICATION_ID/picture?suppress_redirects=true. For more info about POST and PUT operations, see the "Uploading files" section of Folders and files.

    Note When uploading an application's logo, the overwrite query-string parameter and the logo's filename, if provided, are ignored. Also, only logos in Portable Network Graphics (PNG) and Graphics Interchange Format (GIF) file formats, of size 48 × 48 pixels, can be uploaded.

    Top

    Audio object

    The Audio object contains info about a user's audio in SkyDrive. The Live Connect REST API supports creating, reading, updating, and deleting Audio objects. Use the wl.skydrive scope to read Audio objects. Use the wl.contacts_skydrive scope to read any audio that other users have shared with the user. Use the wl.skydrive_update scope to create, update, or delete Audio objects.

    The Audio object contains the following structures.

    Structure Type R/W Required on create Description

    data

    array

    R

    An array of Audio objects, if a collection of objects is returned.

    id

    string

    R

    The Audio object's ID.

    from

    object

    R

    Info about the user who uploaded the audio.

    name (from object)

    string

    R

    The name of the user who uploaded the audio.

    id (from object)

    string

    R

    The ID of the user who uploaded the audio.

    name

    string

    RW

    Yes

    The name of the audio.

    description

    string/null

    RW

    A description of the audio, or null if no description is specified.

    parent_id

    string

    R

    The id of the folder in which the audio is currently stored.

    size

    number

    R

    The size, in bytes, of the audio.

    upload_location

    string

    R

    The URL to use to upload a new audio to overwrite the existing audio.

    comments_count

    number

    R

    The number of comments associated with the audio.

    comments_enabled

    true/false

    R

    A value that indicates whether comments are enabled for the audio. If comments can be made, this value is true; otherwise, it is false.

    is_embeddable

    true/false

    R

    A value that indicates whether this audio can be embedded. If this audio can be embedded, this value is true; otherwise, it is false.

    source

    string

    R

    The URL to use to download the audio from SkyDrive.

    Warning

    This value is not persistent. Use it immediately after making the request, and avoid caching.

    link

    string

    R

    A URL to view the item on SkyDrive.

    type

    string

    R

    The type of object; in this case, "audio".

    title

    string

    RW

    The audio's title.

    artist

    string

    RW

    The audio's artist name.

    album

    string

    RW

    The audio's album name.

    album_artist

    string

    RW

    The artist name of the audio's album.

    genre

    string

    RW

    The audio's genre.

    duration

    integer

    R

    The audio's playing time, in milliseconds.

    picture

    string

    R

    A URL to view the audio's picture on SkyDrive.

    shared_with

    object

    R

    The object that contains permission info.

    access (shared_with object)

    string

    R

    Info about who can access the audio. The options are:

    • People I selected
    • Just me
    • Everyone (public)
    • Friends
    • My friends and their friends
    • People with a link
    The default is Just me.

    created_time

    string

    R

    The time, in ISO 8601 format, at which the audio was created.

    updated_time

    string

    R

    The time, in ISO 8601 format, at which the audio was last updated.

    The following is an example of a collection of Audio objects. (For brevity, only the first object is shown.)

    {
   "data": [
      {
         "id": "file.a6b2a7e8f2515e5e.A6B2A7E8F2515E5E!144",
         "from": {
            "name": "Stig Struve-Christensen",
            "id": "a6b2a7e8f2515e5e"
         },
         "name": "SampleAudio.mp3",
         "description": null,
         "parent_id": "folder.a6b2a7e8f2515e5e",
         "size": 8414449,
         "upload_location": "https://apis.live.net/v5.0/file.a6b2a7e8f2515e5e.A6B2A7E8F2515E5E!144/content/",
         "comments_count": 0,
         "comments_enabled": false,
         "is_embeddable": false,
         "source": "http://storage.live.com/s1p60U8Xs4UzIXTScrTioalE-ZaVFiDQBA15MS2BwcsuNjfG64Z2fw-DAjXnPuqC47YR40_xAoPD8aRGhtna9ZFZ9_oO4BTz4CWF973DTXMxc5U3TntcQ9qEA/SampleAudio.mp3:Binary",
         "link": "https://skydrive.live.com/redir.aspx?cid\u003d22688711f5410e6c\u0026page\u003dview\u0026resid\u003d22688711F5410E6C!582\u0026parid\u003d22688711F5410E6C!581",
         "type": "audio",
         "title": "My Sample Audio",
         "artist": "My Favorite Artist",
         "album": "My Favorite Album",
         "album_artist": "My Favorite Artist",
         "genre": "Easy Listening",
         "duration": 225000,
         "picture": "https://storage.live.com/items/A6B2A7E8F2515E5E!144:MobileReady/SampleAudio.mp3?psid=1&ck=0&ex=720"
         "shared_with": {
            "access": "Just me"
         },
         "created_time": "2012-09-23T22:00:57+0000",
         "updated_time": "2012-09-03T22:00:57+0000"
      }, {
         ...
      }
   ]
}

    To create a new Audio resource, you can make either a PUT request with the audio in the body or a POST request with the audio in a multipart form body. For POST, make a POST request to the /UPLOAD_LOCATION for the target folder, or a POST request to /FOLDER_ID/files. You must format the request as a multipart/form-data media type as described in RFC 2388. You must specify the Content-Type as multipart/form-data, and specify the boundary like this.

    Content-Type: multipart/form-data; boundary=AaB03x

    Provide the item to upload on a multipart section, and the name of the audio as the value of the filename parameter of the Content-Disposition header, as shown here.

    Content-Type: multipart/form-data; boundary=AaB03x
--AaB03x
Content-Disposition: form-data; name="file"; filename="SampleAudio.wav"
Content-Type: audio/mp3

...contents of SampleAudio.wav...
--AaB03x--

    Note

    The boundary value (shown here as "AaB03x") can be any arbitrary string value.

    Only one multipart section per request is supported. For a PUT request, leave the Content-Type blank and put the contents of the file in the request body.

    Upon successful creation, the location header points to the location for the newly created audio, and the response body contains the following properties.

    {
   "id": "ID of the new audio",
   "name": "The file's name and file extension",
   "source": "URL where the audio can be downloaded from"
}

    You can upload an audio to an existing resource in any of the following ways.

    • Make a PUT request to /UPLOAD_LOCATION/FILE_NAME for the folder you would like to upload to.

    • Make a PUT request to /FOLDER_ID/files/FILE_NAME.

    • Make a PUT request to /ALBUM_ID/files/FILE_NAME.

    • Make a PUT request to /UPLOAD_LOCATION for the file to update.

    • Make a PUT request to /AUDIO_ID/content.

    To update the properties for an Audio resource, make a PUT request to /AUDIO_ID, and specify the changes in the request body, as shown here.

    {
   "name": "SampleAudioChanged.wav"
   "description": "Holiday Concert"
}

    To delete an audio, make a DELETE request to /AUDIO_ID.

    To move an audio, make a MOVE request to /AUDIO_IF or /FOLDER_ID, and specify the ID of the destination folder in the request body, as shown here.

    {
   "destination": "FOLDER_ID"
}

    To copy an audio, make a COPY request to /AUDIO_ID or /FOLDER_ID, and specify the ID of the destination folder in the request body, as shown here.

    {
   "destination": "FOLDER_ID"
}

    For PUT and POST requests, you can use the overwrite query string parameter to indicate whether the request should fail if the resource already exists, as shown here. Optionally you can specify an overwrite query-string parameter value of ChooseNewName if you want to upload a duplicate copy of the file but let SkyDrive choose the uploaded file's new file name. Note that MOVE and COPY do not support overwriting at this time.

    overwrite=true
overwrite=false
overwrite=ChooseNewName

    If the value of the overwrite query string parameter is set to true, and the audio exists, it is overwritten. If the value is set to false, the audio is not overwritten, and a resource_already_exists error is returned. If no overwrite query string parameter is specified, the default value is true.

    Top

    Calendar object

    The Calendar object contains info about a user's Hotmail calendar. The Live Connect REST API supports creating, reading, updating, and deleting calendars. Use the wl.calendars scope to read a user's Calendar objects. Use the wl.calendars_update scope to create Calendar objects for a user. Use the wl.contacts_calendars scope to read a user's friends' Calendar objects.

    The Calendar object contains the following structures.

    Structure Type R/W Required on create Description

    id

    string

    R

    The Calendar object's ID.

    name

    string

    RW

    Yes

    Name of the calendar.

    description

    string/null

    RW

    Description of the calendar.

    created_time

    string

    R

    The time, in ISO 8601 format, at which the calendar was created.

    updated_time

    string

    R

    The time, in ISO 8601 format, that the calendar was last updated.

    from

    object

    R

    Info about the user who owns the calendar.

    name (from object)

    string

    R

    The name of the user who uploaded the file.

    id (from object)

    string

    R

    The ID of the user who owns the calendar.

    is_default

    true/false

    R

    A value that indicates whether this calendar is the default calendar. If this calendar is the default calendar, this value is true; otherwise, it is false.

    subscription_location

    string

    RW

    A public subscription URL with which Live Connect will synchronize properties and events periodically for this calendar. A NULL value indicates that this is not a subscribed calendar.

    permissions

    string

    R

    Role and permissions that are granted to the user for the calendar. The possible values are:

    • free_busy: The user can see only free/busy info.
    • limited_details: The user can see a subset of all details.
    • read: The user can only read the content of the calendar events.
    • read_write: The user can read and write calendar and events.
    • co_owner: The user is co-owner of this calendar.
    • owner: The user is the owner of this calendar.

    The following is an example of a collection of Calendar objects. (For brevity, only the first object is shown.)

    {
   "data": [
      {
         "id": "calendar.42d4dbc866f94c83849c88c6eb9985bc",
         "name": "Birthday calendar",
         "description": "If you have birthdays listed for your contacts, they'll appear on this calendar. You can add more birthdays, but you can't add other types of events.",
         "created_time": "2011-08-05T19:41:04+0000",
         "updated_time": "2011-08-05T19:41:04+0000",
         "from": {
            "name": null,
            "id": null
         },
         "is_default": false,
         "subscription_location": null,
         "permissions": "read"
      },{
         ...
      }
   ]
}

    To get a collection of Calendar objects by using the Live Connect REST API, make a GET request to either /me/calendars, or /USER_ID/calendars.

    To get the properties for a particular Calendar object, make a GET request with the ID of the calendar.

    https://apis.live.net/v5.0/calendar.b4466224b2ca42798c3d4ea90c75aa56?access_token=ACCESS_TOKEN

    To create a new Calendar, make a POST request to either /me/calendars, or /USER_ID/calendars. Pass the name (required) and summary (optional) strings as properties in the request body. The properties for the new calendar are returned in the response body, and the Location header contains the URI for the newly created calendar.

    {
   "name": "Summer Events",
   "summary": "Things we are doing this summer."
}

    Warning

    The request body must not include the subscription_location property.

    To subscribe to a public calendar, make a POST request to either /me/calendars or /USER_ID/calendars. Pass the name and subscription_location strings as properties in the request body. The value of subscription_location must be a valid online iCal calendar. Both properties are required.

    {
   "name": "Soccer League"
   "subscription_location": "ical.sharedcalendars.com/98754auv"
}

    To update a Calendar, make a PUT request to /CALENDAR_ID. Include the properties to update in the request body, as shown here.

    {
   "name": "Fall Happenings"
}

    To delete a Calendar, make a DELETE request to /CALENDAR_ID.

    In the preceding examples, replace CALENDAR_ID with the target calendar ID.

    Top

    Comment object

    The Comment object contains info about comments that are associated with a photo, audio, or video on SkyDrive. The Live Connect REST API supports reading Comment objects. Use the wl.photos scope to read Comment objects. Use the wl.contacts_photos scope to read the Comment objects that are associated with any albums, photos, and videos that other users have shared with the user.

    The Comment object contains the following structures.

    Structure | Type | R/W | Required on create | Description
data | array | R |  | An array of Comment objects, if a collection of objects is returned.
id | string | R |  | The Comment object's id.
from | object | R |  | Info about the user who created the comment.
name (from object) | string | R |  | The name of the user who created the comment.
id (from object) | string | R |  | The ID of the user who created the comment.
message | string | RW | Yes | The text of the comment. The maximum length of a comment is 10,000 characters.
created_time | string | R |  | The time, in ISO 8601 format, at which the comment was created.

    The following is an example of a collection of Comment objects. (For brevity, only the first object is shown.)

    {
   "data": [
      {
         "id": "comment.22688711f5410e6c.22688711f0410e6c!818.22688711F5410E6C!979",
         "from": {
            "name": "Roberto Tamburello",
            "id": "8c8ce076ca27823f"
         },
         "message": "A lighthouse built on some rocks.",
         "created_time": "2011-04-21T23:21:28+0000"
      }, {
         ...
      }
   ]
}

    To get a collection of Comment objects by using the Live Connect REST API, make a GET request to /RESOURCE_ID/comments.

    Top

    Contact object

    The Contact object contains info about a user's Hotmail contacts. The Live Connect REST API supports reading Contact objects.

    The Contact object contains the following structures.

    Structure | Required scopes | Type | R/W | Required on create | Description
id | wl.basic | string | R |  | The Contact object's ID.
first_name | wl.basic | string/null | RW | Optional | The contact's first name, or null if no first name is specified.
last_name | wl.basic | string/null | RW | Optional | The contact's last name, or null if no last name is specified.
name | wl.basic | string | R |  | The contact's full name, formatted for location.
gender | wl.basic | string/null | RW |  | The contact's gender. Valid values are "male", "female", or null if the contact's gender is not specified.
is_friend | wl.basic | true/false | R |  | A value that indicates whether the contact is set as a friend. If the contact is a friend, this value is true; otherwise, it is false.
is_favorite | wl.basic | true/false | RW |  | A value that indicates whether the contact is set as a favorite contact. If the contact is a favorite, this value is true; otherwise, it is false.
user_id | wl.basic | string/null | R |  | The contact's ID, if the contact has one. If not, this value is null.
email_hashes | wl.basic | array | R |  | An array containing a SHA-256 hash for each of the contact's email addresses. For more info, see Friend finder.
updated_time | wl.basic | string | R |  | The time, in ISO 8601 format, at which the user last updated the data.
birth_day | wl.basic and wl.contacts_birthday | number/null | R |  | The day of the contact's birth date, or null if no birth date is specified.
birth_month | wl.basic and wl.contacts_birthday | number/null | R |  | The month of the contact's birth date, or null if no birth date is specified.

    When creating a new Contact object, at least one of the following attributes must be provided. These are marked as Optional in the preceding structures table.

    • first_name
    • last_name
    • preferred (User object, emails structure)
    • personal (User object, emails structure)
    • business (User object, emails structure)
    • other (User object, emails structure)
    • name (User object, work array, employer structure)

    The preferred, personal, business, other, and name structures belong to the User object. These attributes are not returned when getting a Contact object instance. However, it is possible to add these attributes when creating a new Contact object. Although the value cannot be directly returned, this behavior is handy in situations when you add a new contact by email address only, or if you want to create a contact that is a company. To ensure that the company name or email address appear in place of the contact name, omit the first_name and last_name fields. The email address or company name that you specify appears in place of the name in the returned Contact object instance.

    Use the following JSON as a guide for defining the attributes in your request.

    {
   "first_name": "",
   "last_name": "",
   "emails": {
      "preferred": "",
      "personal": "",
      "business": "",
      "other": ""
   },
   "work": [
      {
         "employer": {
            "name": ""
         }
      }
   ]
}

    The following is an example of a collection of Contact objects. (For brevity, only the first object is shown.)

    {
   "data": [
      {
         "id": "contact.b4466224b2ca42798c3d4ea90c75aa56",
         "first_name": "Henrik",
         "last_name": "Jensen",
         "name": "Henrik Jensen",
         "gender": null,
         "is_friend": false,
         "is_favorite": false,
         "user_id": null,
         "email_hashes": [
            "9ecdb19f4eb8e04304c5d1280368c42e85b6e4fe39f08b0c837ec592b905a620",
            "fc05492f50da6488aa14dcf221d395bcb29a4e43b43b250d60c68df4f831cad3"
         ],
         "updated_time": "2011-04-22T00:11:13+0000",
         "birth_day": 29,
         "birth_month": 3

      }, {
         ...
      }
   ]
}

    To get a collection of Contact objects by using the Live Connect REST API, make a GET request to /me/contacts.

    Note

    If a Contact references a user, you can return a User object by making a GET request using the user_id value for the Contact.

    To redirect a GET call to the URL of the picture of a contact who is a user, call /USER_ID/picture. (A User object's ID is not the same as a contact ID.)

    Top

    Error object

    The Error object contains info about an error that is returned by the Live Connect APIs.

    The Error object contains the following structures.

    Structure | Type | Description
error | object | Info about the error.
code (error object) | string | The error code.
message (error object) | string | The error message.

    The following is an example of an Error object.

    {
   "error": {
      "code": "request_token_expired",
      "message": "The provided access token has expired."
   }
}

    Top

    Event object

    The Event object contains info about events on a user's Hotmail calendars. The Live Connect REST API supports creating Event objects. Use the wl.events_create scope to create Event objects on the user's default calendar only. Use the wl.calendars scope to read Event objects on the user's calendars. Use wl.calendars_update to create Event objects on any of the user's calendars. Use the wl.contacts_calendars scope to read Event objects from the user's friend's calendars.

    The Event object contains the following structures.

    Structure Type R/W Required on create Description

    id

    string

    R

    The ID of the event.

    name

    string

    RW

    Yes

    The name of the event, with a maximum length of 255 characters. This structure is required.

    created_time

    string

    R

    The time, in ISO 8601 format, at which the event was created.

    updated_time

    string

    R

    The time, in ISO 8601 format, at which the event was updated. This structure is visible only in the Event object that is returned if the event was successfully created.

    description

    string

    RW

    Yes

    A description of the event, with a maximum length of 32,768 characters. This structure is required.

    calendar_id

    object

    R

    The ID of the calendar that contains the event.

    from

    object

    R

    The object that contains the name and ID of the organizer.

    name (from object)

    string

    R

    The name of the organizer.

    id (from object)

    string

    R

    The ID of the organizer.

    start_time

    string

    RW

    Yes

    The start time, in ISO 8601 format, of the event. When the event is being read, the time will be the user's local time, in ISO 8601 format.

    end_time

    string

    RW

    The end time, in ISO 8601 format, of the event. If no end time is specified, the default value is 30 minutes after start_time. This structure is optional when creating an event. When the event is being read, the time will be the user's local time, in ISO 8601 format.

    location

    string

    RW

    The name of the location at which the event will take place. The maximum length is 1,000 characters.

    is_all_day_event

    true/false

    RW

    A value that specifies whether the event is an all-day event. If the event is an all-day event, this value is true; otherwise, it is false. If this structure is missing, the default value is false.

    is_recurrent

    true/false

    R

    A value that specifies whether the event is recurring. If the event is recurring, this value is true; otherwise, it is false.

    recurrence

    string

    R

    The text description of the recurrence pattern, for example, "Occurs every week on Tuesday". The value is Null if this is not a recurrent event.

    reminder_time

    number

    RW

    The time, in minutes, before the event for the reminder alarm.

    availability

    string

    RW

    The user's availability status for the event. Valid values are:

    • free
    • busy
    • tentative
    • out_of_office
    The default value is free.

    visibility

    string

    RW

    A value that specifies whether the event is publicly visible. Valid values are:

    • public—the event is visible to anyone who can view the calendar.
    • private"—the event is visible only to the event owner.
    The default value is public.

    The following is an example of an Event object.

    {
   "id": "event.611afb17fa9448f28cdb8277e8ffeb77.e9f015000d0249ce847c5306a25d7d75",
   "name": "Global Project Risk Management Meeting",
   "description": "Generate and assess risks for the project",
   "calendar_id": "calendar.611afb17fa9448f28cdb8277e8ffeb77",
   "from": {
      "name": "William Flash",
      "id": "de57f4126ed7e411"
   },
   "start_time": "2011-04-20T01:00:00+0000",
   "end_time": "2011-04-20T02:00:00+0000",
   "location": "Building 81, Room 9981, 123 Anywhere St., Redmond WA 19599",
   "is_all_day_event": false,
   "is_recurrent": false,
   "recurrence": null,
   "reminder_time": null,
   "availability": "busy",
   "visibility": "public",
   "created_time": "2011-03-14T23:01:31+0000",
   "updated_time": "2011-04-19T20:23:03+0000"
}

    To return a list of events for a calendar by using the Live Connect REST API, make a GET request to /CALENDAR_ID/events. This will return all events between now and the next 30 days by default.

    To return a list of events for a user, make a GET request to either /me/events, or /USER_ID/events.

    To retrieve the properties for an Event, make a GET request to /EVENT_ID.

    To create an Event object on the user's default calendar by using the Live Connect REST API, make a POST request to /me/events. Pass the properties for the event in the request body, as shown here.

    Content-Type: application/json

{
    "name": "Global Project Risk Management Meeting",
    "description": "Generate and assess risks for the project",
    "start_time": "2011-04-20T01:00:00-07:00",
    "end_time": "2011-04-20T02:00:00-07:00",
    "location": "Building 81, Room 9981, 123 Anywhere St., Redmond WA 19599",
    "is_all_day_event": false,
    "availability": "busy",
    "visibility": "public"
}

    Note

    If the call is successful, the Live Connect REST API returns the following JSON-formatted object.

    {
   "name": "Global Project Risk Management Meeting",
   "description": "Generate and assess risks for the project",
   "start_time": "2011-04-20T01:00:00+0000",
   "end_time": "2011-04-20T02:00:00+0000",
   "location": "Building 81, Room 9981, 123 Anywhere St., Redmond WA 19599",
   "is_all_day_event": false,
   "is_recurrent": false,
   "recurrence": null,
   "reminder_time": null,
   "availability": "busy",
   "visibility": "public",
   "updated_time": "2011-04-19T20:23:03+0000"
}

    To delete an Event, make a DELETE request to /EVENT_ID.

    Tip

    The Live Connect REST API does not support creating or updating recurring events; however, you can delete recurring events the same way you would delete a nonrecurring event. Deleting a recurring event deletes all of its occurrences.

    Top

    File object

    The File object contains info about a user's files in SkyDrive. The Live Connect REST API supports creating, reading, updating, and deleting File objects. Use the wl.skydrive scope to read File objects. Use the wl.contacts_skydrive scope to read any files that other users have shared with the user. Use the wl.skydrive_update scope to create, update, or delete File objects.

    The File object contains the following structures.

    Structure Type R/W Required on create Description

    data

    array

    R

    An array of File objects, if a collection of objects is returned.

    id

    string

    R

    The File object's ID.

    from

    object

    R

    Info about the user who uploaded the file.

    name (from object)

    string

    R

    The name of the user who uploaded the file.

    id (from object)

    string

    R

    The ID of the user who uploaded the file.

    name

    string

    RW

    Yes

    The name of the file.

    description

    string/null

    RW

    A description of the file, or null if no description is specified.

    parent_id

    string

    R

    The ID of the folder the file is currently stored in.

    size

    number

    R

    The size, in bytes, of the file.

    upload_location

    string

    R

    The URL to upload file content hosted in SkyDrive.

    Note This structure is not available if the file is a Microsoft Office OneNote notebook.

    comments_count

    number

    R

    The number of comments that are associated with the file.

    comments_enabled

    true/false

    R

    A value that indicates whether comments are enabled for the file. If comments can be made, this value is true; otherwise, it is false.

    is_embeddable

    true/false

    R

    A value that indicates whether this file can be embedded. If this file can be embedded, this value is true; otherwise, it is false.

    source

    string

    R

    The URL to use to download the file from SkyDrive.

    Warning

    This value is not persistent. Use it immediately after making the request, and avoid caching.

    Note This structure is not available if the file is a Office OneNote notebook.

    link

    string

    R

    A URL to view the item on SkyDrive.

    type

    string

    R

    The type of object; in this case, "file".

    Note If the file is a Office OneNote notebook, the type structure is set to "notebook".

    shared_with

    object

    R

    Object that contains permission info.

    access (shared_with object)

    string

    R

    Info about who can access the folder. The options are:

    • People I selected
    • Just me
    • Everyone (public)
    • Friends
    • My friends and their friends
    • People with a link
    The default is Just me.

    created_time

    string

    R

    The time, in ISO 8601 format, at which the file was created.

    updated_time

    string

    R

    The time, in ISO 8601 format, at which the file was last updated.

    The following is an example of a File object.

    {
   "data": [
      {
         "id": "file.22688711f5410e6c.22688711F5410E6C!942",
         "from": {
            "name": "William Flash",
            "id": "22688711f5410e6c"
         },
         "name": "Processing.docx",
         "description": null,
         "parent_id": "folder.22688711f5410e6c.22688711F5410E6C!479",
         "size": 12692,
         "upload_location": "https://apis.live.net/v5.0/file.22688711f5410e6c.22688711F5410E6C!942/content/",
         "comments_count": 0,
         "comments_enabled": true,
         "is_embeddable": false,
         "source": "http://storage.live.com/s1pEwo9qzyT4_BJZqMNm-aVzgLo-WRsQGzjzFsXjyREuQG5pDYr237vKz3i2pmqFuniYPzsuIZAOCUMB_gdfKCUpLpVcaAMXGrk4T7jOWenRniCv9vex7GWfSvy-XCVBVnU/Processing.docx:Binary",
         "link": "https://skydrive-df.live.com/redir.aspx?cid\u003d22688711f5410e6c\u0026page\u003dview\u0026resid\u003d22688711F5410E6C!942\u0026parid\u003d22688711F5410E6C!479",
         "type": "file",
         "shared_with": {
            "access": "Everyone (public)"
         },
         "created_time": "2011-10-12T23:18:23+0000",
         "updated_time": "2011-10-12T23:18:23+0000"
      },{
         ...
      }
   ]
}

    To get properties for a File resource, make a GET request to /FILE_ID (the target file ID).

    To download the content of a File resource, make a GET request to/FILE_ID/content. The file content is returned in the response body.

    Tip You can instruct the user's web browser to prompt the user to save the file that's being downloaded instead of having the web browser try to download and display the file directly in the browser. To do this, add the download=true query parameter after /content (for example, FILE_ID/content?download=true). The download=true query parameter works for all calls related to SkyDrive that redirect to content or to returning URLs that point to content. For example, FOLDER_ID/files?download=true causes all source and thumbnail URLs in the response to be treated also as download links when they are used.

    To return a download link for a File resource, make a GET request to /FILE_ID/content with the suppress_redirects=true parameter. The URL is returned in the response body in the following format.

    {
   "location": "..."
}

    Tip If the client has already requested the properties for a file, the download link will be in the source field.

    To create a new File resource, you can either make a PUT request with the file in the body, or you can make a POST request with the file in a multipart form body. You can make a POST request to the /UPLOAD_LOCATION for the target folder, a POST request to /FOLDER_ID/files, or a PUT request to /FOLDER_ID/files/<file name>. For a POST request, you must also format the request as a multipart/form-data media type as described in RFC 2388. You must specify the Content-Type as multipart/form-data, and specify the boundary like this.

    Important On platforms that support the PUT request, use PUT whenever possible to upload files to SkyDriveto avoid errors that can occur when POST is used.

    Content-Type: multipart/form-data; boundary=AaB03x

    Provide the item to upload on a multipart section, and the name of the file as the value of the filename parameter of the Content-Disposition header, as shown here.

    --AaB03x
Content-Disposition: form-data; name="file"; filename="file1.txt"
Content-Type: text/plain

...contents of file1.txt...
--AaB03x--

    Note

    The boundary value (shown here as "AaB03x") can be any arbitrary string value.

    We support only one multipart section per request. For a PUT request, leave the Content-Type blank and put the contents of the file in the request body.

    Upon successful creation, the location header points to the location for the newly created file, and the response body contains the following properties.

    {
   "id": "ID of the new file",
   "name": "The file's name and file extension",
   "source": "URL where the file can be downloaded from"
}

    You can instruct SkyDrive to return an HTML response that can be used inside a web browser after the file is created. You can also attach a unique identifier to each upload request so that you can identify a particular upload if you are uploading multiple files in quick succession, which is especially useful for <form> multipart posts. To do this, use a POST multipart/form-data request, like this.

    POST https://apis.live.net/v5.0/folder.a6b2a7e8f2515e5e.A6B2A7E8F2515E5E!110/files?state=MyNewFileState&redirect_uri=http%3A%2F%2Fwww.contoso.com%2Fcallback.htm&access_token=ACCESS_TOKEN

Content-Type: multipart/form-data; boundary=AaB03x

--AaB03x
Content-Disposition: form-data; name="file"; filename="MyNewFile.txt"
Content-Type: text/plain

These are the contents of my new file.
--AaB03x--

    In this example, replace the folder ID with your target folder ID; replace the state query-string parameter value with your unique identifier; and replace the redirect_uri query-string parameter with the path to your callback page. Note that the domain portion of the path must match the redirect domain that you specified in the Live Connect app management site for the corresponding client ID.

    SkyDrive returns HTML-formatted code similar to the following.

    <html>
    <head>
        <script type="text/javascript">
            window.location = "http://www.contoso.com/callback.htm#state=MyNewFileState&result=%7B%22id%22%3A%22file.a6b2a7e8f2515e5e.A6B2A7E8F2515E5E!184%22%2C%22source%22%3A%22http%3A%2F%2Fstorage.live.com%2Fs1pasGKzgXFvuEQCbxGtOyIpboUVH1OCHoRzUJNDDwL0zVoidb0RRrNVk88hUrOEve5OMT7eCkuxPbop7dV9tMJQ-eE8SCQ28vFv9ZgPnDGwQMRm-0FeG3-KEY4HL9dQSw9%2FMyNewFile.txt%3ABinary%2CDefault%2FMyNewFile.txt%22%7D";
        </script>
    </head>
</html>

    When decoded, the result response parameter is similar to this.

    {
    "id": "file.a6b2a7e8f2515e5e.A6B2A7E8F2515E5E!184",
    "name: "MyNewFile.txt",
    "source": "http://storage.live.com/s1pasGKzgXFvuEQCbxGtOyIpboUVH1OCHoRzUJNDDwL0zVoidb0RRrNVk88hUrOEve5OMT7eCkuxPbop7dV9tMJQ-eE8SCQ28vFv9ZgPnDGwQMRm-0FeG3-KEY4HL9dQSw9/MyNewFile.txt:Binary,Default/MyNewFile.txt"
}

    You can upload a file to an existing resource in any of the following ways.

    • Make a PUT request to /UPLOAD_LOCATION/FILE_NAME of the parent folder's ID.

    • Make a PUT request to /FOLDER_ID/files/FILE_NAME.

    • Make a PUT request to /UPLOAD_LOCATION for the file to update.

    • Make a PUT request to /FILE_ID/content.

    To update the properties for a File resource, make a PUT request to /FILE_ID, and specify the changes in the request body, as shown here. In this example, both the file name and the description are updated. Note that the filename extension is required when updating the file name.

    {
   "name": "UFO_Sightings_1979.docx"
   "description": "The detailed accounts of all UFO sightings in 1979."
}

    To delete a file, make a DELETE request to /FILE_ID.

    To move a file, make a MOVE request to /FILE_ID or /FOLDER_ID, and specify the ID of the destination folder in the request body, as shown here.

    {
   "destination": "FOLDER_ID"
}

    To copy a file, make a COPY request to /FILE_ID or /FOLDER_ID, and specify the ID of the destination folder in the request body, as shown here.

    {
   "destination": "FOLDER_ID"
}

    For PUT and POST requests, you can use the overwrite query string parameter to indicate whether the request should fail if the resource already exists, as shown here. Optionally you can specify an overwrite query-string parameter value of ChooseNewName if you want to upload a duplicate copy of the file but let SkyDrive choose the uploaded file's new file name.

    overwrite=true
overwrite=false
overwrite=ChooseNewName

    If the value of the overwrite query string parameter is set to true, and the file exists, it is overwritten. If the value is set to false, the file is not overwritten and an resource_already_exists error is returned. If no overwrite query string parameter is specified, the default value is true.

    In all of the preceding cases, you can replace FILE_ID with either me/skydrive/FRIENDLY_FOLDER_NAME or USER_ID/skydrive/FRIENDLY_FOLDER_NAME, where me represents the current consenting user, USER_ID represents the consenting user's ID, and FRIENDLY_FOLDER_NAME represents an allowed friendly folder name like my_documents to represent the Documents folder. For more info, see the SkyDrive core concepts topic's "Use friendly names to access certain SkyDrive folders" section.

    Tip Before uploading a file, have your app check to make sure that there is enough available SkyDrive storage space by making a GET call to USER_ID/skydrive/quota. For example, your app could get the size of the file in bytes and then compare it to the number of available storage bytes returned in the SkyDrive quota call. For more info, see SkyDrive core concepts, in the "Get a user's total and remaining SkyDrive storage quota" section.

    Top

    Folder object

    The Folder object contains info about a user's folders in SkyDrive. Folders can contain combinations of photos, videos, audio, and subfolders. The Live Connect REST API supports reading Folder objects. Use the wl.photos scope to read Folder objects. Use the wl.contacts_photos scope to read any albums, photos, videos, and audio that other users have shared with the user.

    The Folder object contains the following structures.

    Structure Type R/W Required on create Description

    data

    array

    R

    An array container for Folder objects, if a collection of objects is returned.

    id

    string

    R

    The Folder object's ID.

    from

    object

    R

    Info about the user who created the folder.

    name (from object)

    string

    R

    The name of the user who created the folder.

    id (from object)

    string

    R

    The ID of the user who created the folder.

    name

    string

    RW

    Yes

    The name of the folder.

    description

    string/null

    RW

    A description of the folder, or null if no description is specified.

    count

    number

    R

    The total number of items in the folder.

    link

    string

    R

    The URL of the folder, hosted in SkyDrive.

    parent_id

    string

    R

    The resource ID of the parent.

    upload_location

    string

    R

    The URL to upload items to the folder hosted in SkyDrive. Requires the wl.skydrive scope.

    is_embeddable

    true/false

    R

    A value that indicates whether this folder can be embedded. If this folder can be embedded, this value is true; otherwise, it is false.

    type

    string

    R

    The type of object; in this case, "folder".

    created_time

    string

    R

    The time, in ISO 8601 format, at which the folder was created.

    updated_time

    string

    R

    The time, in ISO 8601 format, at which the contents of the folder were last updated.

    shared_with

    object

    R

    Permissions info for the folder. Requires the wl.skydrive scope.

    access (shared_with object)

    string

    R

    Info about who can access the folder. The options are:

    • People I selected
    • Just me
    • Everyone (public)
    • Friends
    • My friends and their friends
    • People with a link
    The default is Just me.

    The following is an example of a collection of Folder objects. (For brevity, only the first object is shown.)

    {
   "data": [
      {
         "id": "folder.8c8ce076ca27823f.8C8CE076CA27823F!142",
         "from": {
            "name": "Roberto Tamburello",
            "id": "8c8ce076ca27823f"
         },
         "name": "My Sample Folder in Album 1",
         "description": "",
         "parent_id": "folder.de57f4126ed7e411",
         "upload_location": "https://apis.live.net/v5.0/folder.de57f4126ed7e411.DE57F4126ED7E411!126/files/",
         "is_embeddable": true,
         "count": 3,
         "link": "https://cid-8c8ce076ca27823f.skydrive.live.com/redir.aspx?page\u003dself\u0026resid\u003d8C8CE076CA27823F!142\u0026parid\u003d8C8CE076CA27823F!126\u0026type\u003d5",
         "type": "folder",
         "shared_with": {
             "access": "Just me"
         },
         "created_time": "2011-04-22T00:36:30+0000",
         "updated_time": "2011-04-22T19:18:12+0000"
      }, {
         ...
      }
   ]
}

    To get the root Folder resource by using the Live Connect REST API, make a GET request to either /me/skydrive or /USER_ID/skydrive.

    To get a subfolder resource, make a GET request to /FOLDER_ID.

    To enumerate the contents of a folder, make a GET request to /FOLDER_ID/files.

    A folder may contain the following objects.

    • Folder object
    • File object
    • Album object
    • Photo object
    • Video object
    • Audio object

    To create a new Folder resource, make a POST request to /FOLDER_ID. Pass the name and description attributes in the request body, as shown here.

    {
   "name": "Informative Spreadsheets",
   "description": "A folder full of useful data visualizations."
}

    The folder is created as a child of the folder that is specified in the request URL. The location header points to the newly created folder location, and the response body contains properties for the newly created folder.

    To update the properties of a Folder, make a PUT request to /FOLDER_ID. Pass the attributes to update in the request body, as shown here.

    {
   "name": "Very Informative Spreadsheets",
   "description": "A folder full of even more useful data visualizations."
}

    To delete a folder, make a DELETE request to /FOLDER_ID.

    In the preceding examples, replace FOLDER_ID with the target folder ID.

    Top

    Friend object

    The Friend object contains info about a user's friends. A Friend object represents a user's contact whose is_friend value is set to true. The Live Connect REST API supports reading Friend objects.

    The Friend object contains the following structures.

    Structure | Required scopes | Type | Description
data | wl.basic | array | An array container for Friend objects when a collection of objects is returned.
id | wl.basic | string | The friend's ID.
name | wl.basic | string | The friend's full name, formatted for locale.

    The following is an example of a collection of Friend objects. (For brevity, only the first object is shown.)

    {
   "data": [
      {
         "id": "d09ea18fafc39a0c",
         "name": "Henrik Jensen"
      }, {
         ...
      }
   ]
}

    To get a collection of Friend objects by using the Live Connect REST API, make a GET request to /me/friends.

    Top

    Permissions object

    The Permissions object contains a list of scopes, showing those scopes to which the user has consented. The response body contains a JSON object that lists all consented scopes as a name/value pair. Each scope to which the user consented is present as a key.

    The following is an example of a Permissions object. (For brevity, not all scopes are shown.)

    {
   "data": [
        {
            "wl.basic": 1,
            "wl.offline_access": 1,
            "wl.signin": 1,
            ...
        }
    ]
}

    To get a Permissions object by using the Live Connect REST API, make a GET request to /me/permissions.

    Top

    Photo object

    The Photo object contains info about a user's photos on SkyDrive. The Live Connect REST API supports creating, reading, updating, and deleting Photo objects. Use the wl.photos scope to read Photo objects. Use the wl.contacts_photos scope to read any albums, photos, videos, and audio that other users have shared with the user. Use the wl.skydrive_update scope to create, update, or delete Photo objects.

    Note

    Photos that are uploaded to SkyDrive through the API are limited to a maximum resolution of 2048 x 2048 pixels. Any photo over that resolution is scaled proportionally to fit within a maximum size of 2048 x 2048 pixels.

    The Photo object contains the following structures.

    Structure Type R/W Required on create Description

    data

    array

    R

    An array of Photo objects, when a collection of objects is returned.

    id

    string

    R

    The Photo object's ID.

    from

    object

    R

    Info about the user who uploaded the photo.

    name (from object)

    string

    R

    The name of the user who uploaded the photo. Part of the from object.

    id (from object)

    string

    R

    The ID of the user who uploaded the photo. Part of the from object.

    name

    string

    RW

    Yes

    The file name of the photo.

    description

    string/null

    RW

    A description of the photo, or null if no description is specified.

    parent_id

    string

    R

    The ID of the folder where the item is stored.

    size

    number

    R

    The size, in bytes, of the photo.

    comments_count

    number

    R

    The number of comments associated with the photo.

    comments_enabled

    true/false

    R

    A value that indicates whether comments are enabled for the photo. If comments can be made, this value is true; otherwise, it is false.

    tags_count

    number

    R

    The number of tags on the photo.

    tags_enabled

    true/false

    R

    A value that indicates whether tags are enabled for the photo. If users can tag the photo, this value is true; otherwise, it is false.

    is_embeddable

    true/false

    R

    A value that indicates whether this photo can be embedded. If this photo can be embedded, this value is true; otherwise, it is false.

    picture

    string

    R

    A URL of the photo's picture.

    source

    string

    R

    The download URL for the photo.

    Warning

    This value is not persistent. Use it immediately after making the request, and avoid caching.

    upload_location

    string

    R

    The URL to upload photo content hosted in SkyDrive. This value is returned only if the wl.skydrive scope is present.

    images

    array

    R

    Info about various sizes of the photo.

    height (images array)

    number

    R

    The height, in pixels, of this image of this particular size.

    width (images array)

    number

    R

    The width, in pixels, of this image of this particular size.

    source (images array)

    string

    R

    A URL of the source file of this image of this particular size.

    type (images array)

    string

    R

    The type of this image of this particular size. Valid values are:

    • full (maximum size: 2048 × 2048 pixels)

    • normal (maximum size 800 × 800 pixels)

    • album (maximum size 176 × 176 pixels)

    • small (maximum size 96 × 96 pixels)

    link

    string

    R

    A URL of the photo, hosted in SkyDrive.

    when_taken

    string/null

    R

    The date, in ISO 8601 format, on which the photo was taken, or null if no date is specified.

    height

    number

    R

    The height, in pixels, of the photo.

    width

    number

    R

    The width, in pixels, of the photo.

    type

    string

    R

    The type of object; in this case, "photo".

    location

    object

    R

    The location where the photo was taken.

    Note The location object is not available for shared photos.

    latitude (location object)

    double

    R

    The latitude portion of the location where the photo was taken, expressed as positive (north) or negative (south) degrees relative to the equator.

    longitude (location object)

    double

    R

    The longitude portion of the location where the photo was taken, expressed as positive (east) or negative (west) degrees relative to the Prime Meridian.

    altitude (location object)

    double

    R

    The altitude portion of the location where the photo was taken, expressed as positive (above) or negative (below) values relative to sea level, in units of measurement as determined by the camera.

    camera_make

    string

    R

    The manufacturer of the camera that took the photo.

    camera_model

    string

    R

    The brand and model number of the camera that took the photo.

    focal_ratio

    double

    R

    The f-number that the photo was taken at.

    focal_length

    double

    R

    The focal length that the photo was taken at, typically expressed in millimeters for newer lenses.

    exposure_numerator

    double

    R

    The numerator of the shutter speed (for example, the "1" in "1/15 s") that the photo was taken at.

    exposure_denominator

    double

    R

    The denominator of the shutter speed (for example, the "15" in "1/15 s") that the photo was taken at.

    shared_with

    object

    R

    The object that contains permissions info for the photo.

    access (shared_with object)

             string

    R

    Info about who can access the photo. The options are:

    • People I selected
    • Just me
    • Everyone (public)
    • Friends
    • My friends and their friends
    • People with a link
    The default is Just me.

    created_time

    string

    R

    The time, in ISO 8601 format, at which the photo was created.

    updated_time

    string

    R

    The time, in ISO 8601 format, at which the photo was last updated.

    The following is an example of a collection of Photo objects. (For brevity, only the first object is shown.)

    {
   "data": [
      {
         "id": "file.de57f4126ed7e411.DE57F4126ED7E411!128",
         "from": {
            "name": "Nuno Bento",
            "id": "de57f4126ed7e411"
         },
         "name": "Maui-2012_0034.JPG",
         "description": null,
         "parent_id": "folder.de57f4126ed7e411.DE57F4126ED7E411!126",
         "size": 561683,
         "comments_count": 1,
         "comments_enabled": true,
         "tags_count": 0,
         "tags_enabled": true,
         "is_embeddable": true,
         "picture": "http://storage.live.com/s1pKk5vzd-gdPanbzKYhB0nQGn8wGq5DSgqvrgIHU1NTXA4e2-spGkAhQjW1d9pcgKAGLB4NsEsSvDoREmdx5w-JiFrinEJJuEoz08Ws_IFupkX2bPSvy5qmths9ijwvDrXi1OBCWk9GW9Kt-qNNOAA9g/Maui09_0034.JPG:Thumbnail",
         "source": "http://storage.live.com/s1pKk5vzd-gdPanbzKYhB0nQGn8wGq5DSgqvrgIHU1NTXA4e2-spGkAhQjW1d9pcgKAGLB4NsEsSvDoREmdx5w-JiFrinEJJuEoz08Ws_IFupkX2bPSvy5qmths9ijwvDrXi1OBCWk9GW9Kt-qNNOAA9g/Maui09_0034.JPG:HighRes",
         "upload_location": "https://apis.live.net/v5.0/file.de57f4126ed7e411.DE57F4126ED7E411!128/content/",
         "images": [
            {
               "height": 450,
               "width": 600,
               "source": "http://storage.live.com/s1pKk5vzd-gdPanbzKYhB0nQGn8wGq5DSgqvrgIHU1NTXA4e2-spGkAhQjW1d9pcgKAGLB4NsEsSvDoREmdx5w-JiFrinEJJuEoz08Ws_IFupkX2bPSvy5qmths9ijwvDrXi1OBCWk9GW9Kt-qNNOAA9g/Maui09_0034.JPG:WebReady",
               "type": "normal"
            }, {
               "height": 132,
               "width": 176,
               "source": "http://storage.live.com/s1pKk5vzd-gdPanbzKYhB0nQGn8wGq5DSgqvrgIHU1NTXA4e2-spGkAhQjW1d9pcgKAGLB4NsEsSvDoREmdx5w-JiFrinEJJuEoz08Ws_IFupkX2bPSvy5qmths9ijwvDrXi1OBCWk9GW9Kt-qNNOAA9g/Maui09_0034.JPG:MobileReady",
               "type": "album"
            }, {
               "height": 72,
               "width": 96,
               "source": "http://storage.live.com/s1pKk5vzd-gdPanbzKYhB0nQGn8wGq5DSgqvrgIHU1NTXA4e2-spGkAhQjW1d9pcgKAGLB4NsEsSvDoREmdx5w-JiFrinEJJuEoz08Ws_IFupkX2bPSvy5qmths9ijwvDrXi1OBCWk9GW9Kt-qNNOAA9g/Maui09_0034.JPG:Thumbnail",
               "type": "thumbnail"
            }, {
               "height": 1200,
               "width": 1600,
               "source": "http://storage.live.com/s1pKk5vzd-gdPanbzKYhB0nQGn8wGq5DSgqvrgIHU1NTXA4e2-spGkAhQjW1d9pcgKAGLB4NsEsSvDoREmdx5w-JiFrinEJJuEoz08Ws_IFupkX2bPSvy5qmths9ijwvDrXi1OBCWk9GW9Kt-qNNOAA9g/Maui09_0034.JPG:HighRes",
               "type": "full"
            }
         ],
         "link": "https://skydrive.live.com/redir.aspx?cid\u003dde57f4126ed7e411\u0026page\u003dview\u0026resid\u003dDE57F4126ED7E411!128\u0026parid\u003dDE57F4126ED7E411!126",
         "when_taken": "2008-03-24T23:41:53+0000",
         "height": 1200,
         "width": 1600,
         "type": "photo",
         "location": {
             "latitude": 47.65316,
             "longitude": -122.135911,
             "altitude": 43
         },
         "camera_make": "MyManufacturer",
         "camera_model": "MyModel",
         "focal_ratio": 2.8,
         "focal_length": 3.85,
         "exposure_numerator": 1,
         "exposure_denominator": 15,
         "shared_with": {
            "access": "Everyone (public)"
         },
         "created_time": "2012-12-03T18:14:03+0000",
         "updated_time": "2012-12-03T18:31:01+0000"
      }, {
         ...
      }
   ]
}

    To get a collection of Photo objects by using the Live Connect REST API, make a GET request to /ALBUM_ID/files.

    Note You can also get a collection of Photo objects by calling either /ALBUM_ID/photos, or /FOLDER_ID/photos.

    Note To display a photo, call /PHOTO_ID/picture. To display a photo of a specific image size, follow /PHOTO_ID/picture with ?type= and one of the following: thumbnail, small, album, normal, or full. The default is normal. The following is an example of a call that displays a thumbnail image.

    https://apis.live.net/v5.0/PHOTO_ID/picture?type=thumbnail&access_token=ACCESS_TOKEN

    In the preceding examples, replace ALBUM_ID and PHOTO_ID with the target album or photo ID.

    To create a new Photo resource, you can make either a PUT request with the photo in the body or a POST request with the photo in a multipart form body. For POST, make a POST request to the /UPLOAD_LOCATION for the target folder or a POST request to /FOLDER_ID. You must format the request as a multipart/form-data media type as described in RFC 2388. You must specify the Content-Type as multipart/form-data, and specify the boundary like this.

    Content-Type: multipart/form-data; boundary=AaB03x

    Provide the item to upload on a multipart section, and the name of the photo as the value of the filename parameter of the Content-Disposition header, as shown here.

    Content-Type: multipart/form-data; boundary=AaB03x
--AaB03x
Content-Disposition: form-data; name="file"; filename="hovering_orbs.jpg"
Content-Type: image/jpeg

...contents of hovering_orbs.jpg...
--AaB03x--

    Note

    The boundary value (shown here as "AaB03x") can be any arbitrary string value.

    Only one multipart section per request is supported. For a PUT request, leave the Content-Type blank and put the contents of the file in the request body.

    Upon successful creation, the location header points to the location for the newly created photo, and the response body contains the following properties.

    {
   "id": "ID of the new photo",
   "name": "The file's name and file extension",
   "source": "URL where the photo can be downloaded from"
}

    You can upload a photo to an existing resource in any of the following ways.

    • Make a PUT request to /UPLOAD_LOCATION/FILE_NAME for the folder you would like to upload to.

    • Make a PUT request to /FOLDER_ID/files/FILE_NAME.

    • Make a PUT request to /ALBUM_ID/files/FILE_NAME.

    • Make a PUT request to /UPLOAD_LOCATION for the file to update.

    • Make a PUT request to /PHOTO_ID/content.

    By default, if an uploaded photo is larger than 2048 × 2048 pixels in size, SkyDrive automatically attempts to shrink it to fit within this 2048 × 2048-pixel size constraint. To override this behavior, set the downsize_photo_uploads query-string parameter to false—for example, /FOLDER_ID/files?downsize_photo_uploads=false for POST or /FOLDER_ID/files/FILENAME?downsize_photo_uploads=false for PUT.

    To update the properties for a Photo resource, make a PUT request to /PHOTO_ID, and specify the changes in the request body, as shown here.

    {
   "name": "fast-moving_orbs.jpg"
   "description": "Fast moving objects."
}

    To delete a photo, make a DELETE request to /PHOTO_ID.

    To move a photo, make a MOVE request to /PHOTO_ID or /FOLDER_ID, and specify the ID of the destination folder in the request body, as shown here.

    {
   "destination": "FOLDER_ID"
}

    To copy a photo, make a COPY request to /PHOTO_ID or /FOLDER_ID, and specify the ID of the destination folder in the request body, as shown here.

    {
   "destination": "FOLDER_ID"
}

    For PUT and POST requests, you can use the overwrite query string parameter to indicate whether the request should fail if the resource already exists, as shown here. Optionally you can specify an overwrite query-string parameter value of ChooseNewName if you want to upload a duplicate copy of the file but let SkyDrive choose the uploaded file's new file name. Note that MOVE and COPY do not support overwriting at this time.

    overwrite=true
overwrite=false
overwrite=ChooseNewName

    If the value of the overwrite query string parameter is set to true, and the file exists, it is overwritten. If the value is set to false, the file is not overwritten, and a resource_already_exists error is returned. If no overwrite query string parameter is specified, the default value is true.

    Top

    Tag object

    The Tag object contains info about tags that are associated with a photo or a video on SkyDrive. The Live Connect REST API supports reading Tag objects. Use the wl.photos, and wl.skydrive scopes to read Tag objects. Use the wl.contacts_photos and wl.contacts_skydrive scopes to read the Tag objects that are associated with any photos that other users have shared with the user.

    The Tag object contains the following structures.

    Structure | Type | R/W | Required on create | Description
data | array | R |  | An array of Tag objects, if a collection of objects is returned.
id | string | R |  | The Tag object's ID.
user | object | RW |  | The user object for the tagged person.
name (user object) | string | RW |  | The name of the tagged person.
id (user object) | string | RW |  | The user ID of the tagged user if they have one; otherwise, null.
x | number | RW |  | The center of the tag's horizontal position, measured as a floating-point percentage from 0 to 100, from the left edge of the photo. This value is not returned for Video objects.
y | number | RW |  | The center of the tag's vertical position, measured as a floating-point percentage from 0 to 100, from the top edge of the photo. This value is not returned for Video objects.
created_time | string | R |  | The time, in ISO 8601 format, at which the tag was created.

    The following is an example of a collection of Tag objects. (For brevity, only the first object is shown.)

    {
    "id": "tag.22688711f5410e6c.22688711f5410e6c!767.PRaXZrdHI1uYGQYi9CU0StrzHak",
    "user": {
        "name": "Roberto Tamburello",
        "id": "8c8ce076ca27823f"
    },
    "x": 43.8986,
    "y": 54.4138,
    "created_time": "2011-04-22T01:17:00+0000"
}

    Note

    Information about the tagged user is stored in the user attribute.

    The x and y members are not present on tags that are returned from a video object.

    To get a collection of Tag objects by using the Live Connect REST API, make a GET request to /RESOURCE_ID/tags.

    Top

    User object

    The User object contains info about a user. The Live Connect REST API supports reading User objects.

    The User object contains the following structures.

    Structure | Required scopes | Type | Description
id | None | string | The user's ID.
name | None | string | The user's full name.
first_name | None | string/null | The user's first name.
last_name | None | string/null | The user's last name.
link | wl.basic | string | The URL of the user's profile page.
birth_day | wl.birthday | number/null | The day of the user's birth date, or null if no birth date is specified.
birth_month | wl.birthday | number/null | The month of the user's birth date, or null if no birth date is specified.
birth_year | wl.birthday | number/null | The year of the user's birth date, or null if no birth date is specified.
work | wl.work_profile | array | An array that contains the user's work info.
employer (work array) | wl.work_profile | object | Info about the user's employer.
name (employer object) | wl.work_profile | string/null | The name of the user's employer, or null if the employer's name is not specified.
position (work array) | wl.work_profile | object | Info about the user's work position.
name (position object) | wl.work_profile | string/null | The name of the user's work position, or null if the name of the work position is not specified.
gender | None | string/null | The user's gender. Valid values are "male", "female", or null if the user's gender is not specified.
emails | wl.emails | object | The user's email addresses.
preferred (emails object) | wl.emails | string/null | The user's preferred email address, or null if one is not specified.
account (emails object) | wl.emails | string | The email address that is associated with the account.
personal (emails object) | wl.emails | string/null | The user's personal email address, or null if one is not specified.
business (emails object) | wl.emails | string/null | The user's business email address, or null if one is not specified.
other (emails object) | wl.emails | string/null | The user's "alternate" email address, or null if one is not specified.
addresses | wl.postal_addresses | object | The user's postal addresses.
personal (addresses object) | wl.postal_addresses | object | The user's personal postal address.
street (personal object) | wl.postal_addresses | string/null | The user's personal street address, or null if one is not specified.
street_2 (personal object) | wl.postal_addresses | string/null | The second line of the user's personal street address, or null if one is not specified.
city (personal object) | wl.postal_addresses | string/null | The city of the user's personal address, or null if one is not specified.
state (personal object) | wl.postal_addresses | string/null | The state of the user's personal address, or null if one is not specified.
postal_code (personal object) | wl.postal_addresses | string/null | The postal code of the user's personal address, or null if one is not specified.
region (personal object) | wl.postal_addresses | string/null | The region of the user's personal address, or null if one is not specified.
business(addresses object) | wl.postal_addresses | object | The user's business postal address.
street (business object) | wl.postal_addresses | string/null | The user's business street address, or null if one is not specified.
street_2 (business object) | wl.postal_addresses | string/null | The second line of the user's business street address, or null if one is not specified.
city (business object) | wl.postal_addresses | string/null | The city of the user's business address, or null if one is not specified.
state (business object) | wl.postal_addresses | string/null | The state of the user's business address, or null if one is not specified.
postal_code (business object) | wl.postal_addresses | string/null | The postal code of the user's business address, or null if one is not specified.
region (business object) | wl.postal_addresses | string/null | The region of the user's business address, or null if one is not specified.
phones | wl.phone_numbers | object | The user's phone numbers.
personal (phones object) | wl.phone_numbers | string/null | The user's personal phone number, or null if one is not specified.
business (phones object) | wl.phone_numbers | string/null | The user's business phone number, or null if one is not specified.
mobile (phones object) | wl.phone_numbers | string/null | The user's mobile phone number, or null if one is not specified.
locale | None | string | The user's locale code.
updated_time | wl.basic | string | The time, in ISO 8601 format, at which the user last updated the object.

    The following is an example of a User object.

    {
   "id": "8c8ce076ca27823f",
   "name": "Roberto Tamburello",
   "first_name": "Roberto",
   "last_name": "Tamburello",
   "link": "http://cid-8c8ce076ca27823f.profile.live.com/",
   "birth_day": 20,
   "birth_month": 4,
   "birth_year": 2010,
   "work": [
      {
         "employer": {
            "name": "Microsoft Corporation"
         },
         "position": {
            "name": "Software Development Engineer"
         }
      }
   ],
   "gender": "male",
   "emails": {
      "preferred": "Roberto@contoso.com",
      "account": "Roberto@contoso.com",
      "personal": "Roberto@fabrikam.com",
      "business": "Robert@adatum.com",
      "other": "Roberto@adventure-works.com"
   },
   "addresses": {
      "personal": {
         "street": "123 Main St.",
         "street_2": "Apt. A",
         "city": "Redmond",
         "state": "WA",
         "postal_code": "12990",
         "region": "United States"
      },
      "business": {
         "street": "456 Anywhere St.",
         "street_2": "Suite 1",
         "city": "Redmond",
         "state": "WA",
         "postal_code": "12399",
         "region": "United States"
      }
   },
   "phones": {
      "personal": "(555) 555-1212",
      "business": "(555) 111-1212",
      "mobile": null
   },
   "locale": "en_US",
   "updated_time": "2011-04-21T23:55:34+0000"
}

    To get a User object by using the Live Connect REST API, make a GET request to either /me, or /USER_ID.

    Note To redirect a GET call to the URL of a user's picture, you can call /me/picture or /USER_ID/picture. You can get different sizes of a user's picture, if they exist, by calling /me/picture?type=SIZE or /USER_ID/picture?type=SIZE, where SIZE is one of the following: small (to get a 96 × 96-pixel picture), medium (180 × 180), or large (360 × 360). If a particular size picture doesn't exist, the next-largest size picture that's available is returned. In any event, a 96 × 96-pixel picture is returned (unless no picture is associated with the user, in which case a default user picture is returned).

    Top

    Video object

    The Video object contains info about a user's videos on SkyDrive. The Live Connect REST API supports creating, reading, updating, and deleting Video objects. Use the wl.photos scope to read Video objects. Use the wl.contacts_photos scope to read albums, photos, and videos that other users have shared with the user. Use the wl.skydrive_update scope to create, update, or delete Video objects.

    The Video object contains the following structures.

    Structure Type R/W Required on create Description

    data

    array

    R

    An array of Video objects, if a collection of objects is returned.

    id

    string

    R

    The Video object's ID.

    from

    object

    R

    Info about the user who uploaded the video.

    name (from object)

    string

    R

    The name of the user who uploaded the video.

    id (from object)

    string

    R

    The ID of the user who uploaded the video.

    name

    string

    RW

    Yes

    The file name of the video.

    description

    string/null

    RW

    A description of the video, or null if no description is specified.

    parent_id

    string

    R

    The id of the folder where the item is stored.

    size

    number

    R

    The size, in bytes, of the video.

    comments_count

    number

    R

    The number of comments that are associated with the video.

    comments_enabled

    true/false

    R

    A value that indicates whether comments are enabled for the video. If comments can be made, this value is true; otherwise, it is false.

    tags_count

    number

    R

    The number of tags on the video.

    tags_enabled

    true/false

    R

    A value that indicates whether tags are enabled for the video. If tags can be set, this value is true; otherwise, it is false.

    is_embeddable

    true/false

    R

    A value that indicates whether this video can be embedded. If this video can be embedded, this value is true; otherwise, it is false.

    picture

    string

    R

    A URL of a picture that represents the video.

    source

    string

    R

    The download URL for the video.

    Warning

    This value is not persistent. Use it immediately after making the request, and avoid caching.

    upload_location

    string

    R

    The URL to upload video content, hosted in SkyDrive. This value is returned only if the wl.skydrive scope is present.

    link

    string

    R

    A URL of the video, hosted in SkyDrive.

    height

    number

    R

    The height, in pixels, of the video.

    width

    number

    R

    The width, in pixels, of the video.

    duration

    number

    R

    The duration, in milliseconds, of the video run time.

    bitrate

    number

    R

    The bit rate, in bits per second, of the video.

    type

    string

    R

    The type of object; in this case, "video".

    shared_with

    object

    R

    The object that contains permission info.

    access (shared_with object)

    string

    R

    Info about who can access the file. The options are:

    • People I selected
    • Just me
    • Everyone (public)
    • Friends
    • My friends and their friends
    • People with a link
    The default is Just me.

    created_time

    string

    R

    The time, in ISO 8601 format, at which the video was created.

    updated_time

    string

    R

    The time, in ISO 8601 format, at which the video was last updated.

    The following is an example of a collection of Video objects. (For brevity, only the first object is shown.)

    {
    "data": [
      {
         "id": "file.de57f4126ed7e411.DE57F4126ED7E411!135",
         "from": {
            "name": "Nuno Bento",
            "id": "de57f4126ed7e411"
         },
         "name": "Wildlife.wmv",
         "description": null,
         "parent_id": "folder.de57f4126ed7e411.DE57F4126ED7E411!126",
         "size": 26246026,
         "comments_count": 0,
         "comments_enabled": true,
         "tags_count": 0,
         "tags_enabled": true,
         "is_embeddable": true,
         "picture": "http://storage.live.com/s1pKk5vzd-gdPaJ5Q1MKN34itsyRlUkAYzD_zsr0Dg-5r4bH8Qo8XRgsunA0M-V4G-XPpu1spowx4xwfjCuDcWQVa7aWld2WCdfeWjBK_coPqaQqzoE26BJP3OZAITB5i_DRPK8jK3ZLilSbNJd-onrOA/Wildlife.wmv:Thumbnail",
         "source": "http://storage.live.com/s1pKk5vzd-gdPaJ5Q1MKN34itsyRlUkAYzD_zsr0Dg-5r4bH8Qo8XRgsunA0M-V4G-XPpu1spowx4xwfjCuDcWQVa7aWld2WCdfeWjBK_coPqaQqzoE26BJP3OZAITB5i_DRPK8jK3ZLilSbNJd-onrOA/Wildlife.wmv:VideoMain",
         "upload_location": "https://apis.live.net/v5.0/file.de57f4126ed7e411.DE57F4126ED7E411!135/content/",
         "link": "https://skydrive.live.com/redir.aspx?cid\u003dde57f4126ed7e411\u0026page\u003dview\u0026resid\u003dDE57F4126ED7E411!135\u0026parid\u003dDE57F4126ED7E411!126",
         "height": 720,
         "width": 1280,
         "duration": 30093,
         "bitrate": 5942130,
         "type": "video",
         "shared_with": {
            "access": "Everyone (public)"
         },
         "created_time": "2011-08-23T23:41:18+0000",
         "updated_time": "2011-08-23T23:41:32+0000"
      }, {
         ...
      }
   ]
}

    To get a collection of Video objects by using the Live Connect REST API, make a GET request to /ALBUM_ID/files.

    Note You can also get a collection of Video objects by calling either /ALBUM_ID/videos, or /FOLDER_ID/videos.

    In the preceding examples, replace ALBUM_ID with the target Live Connect album ID.

    To create a new Video resource, you can make either a PUT request with the video in the body or a POST request with the video in a multipart form body. For POST, make a POST request to the /UPLOAD_LOCATION for the target folder or a POST request to /FOLDER_ID. You must format the request as a multipart/form-data media type as described in RFC 2388. You must specify the Content-Type as multipart/form-data and specify the boundary, as shown here.

    Content-Type: multipart/form-data; boundary=AaB03x

    Provide the item to upload on a multipart section, and the name of the photo as the value of the filename parameter of the Content-Disposition header, as shown here.

    Content-Type: multipart/form-data; boundary=AaB03x
--AaB03x
Content-Disposition: form-data; name="file"; filename="strange_lights.avi"
Content-Type: video/x-msvideo

...contents of strange_lights.avi...
--AaB03x--

    Note

    The boundary value (shown here as "AaB03x") can be any arbitrary string value.

    Only one multipart section per request is supported. For a PUT request, leave the Content-Type blank and put the contents of the file in the request body.

    Upon successful creation, the location header points to the location for the newly created video, and the response body contains the following properties.

    {
   "id": "ID of the new video",
   "name": "The file's name and file extension",
   "source": "URL where the video can be downloaded from"
}

    You can upload a video to an existing resource in any of the following ways.

    • Make a PUT request to /UPLOAD_LOCATION/FILE_NAME of the parent folder's ID.

    • Make a PUT request to /FOLDER_ID/files/FILE_NAME.

    • Make a PUT request to /ALBUM_ID/files/FILE_NAME.

    • Make a PUT request to /UPLOAD_LOCATION for the file to update.

    • Make a PUT request to /VIDEO_ID/content.

    To update the properties for a Video resource, make a PUT request to /VIDEO_ID, and specify the changes in the request body, as shown here.

    {
   "name": "triangle_formation.avi"
   "description": "Sightings of UFOs in triangle formation."
}

    To delete a video, make a DELETE request to /VIDEO_ID.

    To move a video, make a MOVE request to /VIDEO_ID or /FOLDER_ID, and specify the ID of the destination folder in the request body, as shown here.

    {
   "destination": "FOLDER_ID"
}

    To copy a video, make a COPY request to /VIDEO_ID or /FOLDER_ID, and specify the ID of the destination folder in the request body, as shown here.

    {
   "destination": "FOLDER_ID"
}

    For PUT and POST requests, you can use the overwrite query string parameter to indicate whether the request should fail if the resource already exists, as shown here. Optionally you can specify an overwrite query-string parameter value of ChooseNewName if you want to upload a duplicate copy of the file but let SkyDrive choose the uploaded file's new file name.

    overwrite=true
overwrite=false
overwrite=ChooseNewName

    If the value of the overwrite query string parameter is set to true, and the file exists, it is overwritten. If the value is set to false, the file is not overwritten and a resource_already_exists error is returned. If no overwrite query string parameter is specified, the default value is true.

    Top

    Additional URL parameters

    You can specify additional parameters, as part of the URL of a GET request to the Live Connect REST API, to instruct the Live Connect APIs how to return its results. The following table explains these parameters.

    Parameter Description Valid values Default value Examples

    pretty

    When this value is set to true, Live Connect returns the response in a more human-readable format. When this value is set to false, white space and new lines are not included, which improves performance but makes the response less readable.

    true/false

    true

    pretty=false

    callback

    The name of the function that handles the JSON with padding (JSONP) function call. When this parameter is specified, all error responses use the HTTP status code 200 to help ensure proper handling in the web browser.

    A string that represents the name of the callback function.

    None

    callback=onResponse

    suppress_response_codes

    When this value is set to true, Live Connect returns the HTTP status code 200 for all error responses. This option is useful with web-browser plug-ins like Microsoft Silverlight or Adobe Flash Player.

    true/false

    false

    suppress_response_code=true

    method

    The name of the HTTP method that is used for request processing instead of GET.

    A string that represents the HTTP request method, such as POST.

    None

    method=POST

    locale

    The locale that determines the format in which Live Connectreturnsvalues. In particular:

    • Canonical folder names are translated to the language specified by the locale.
    • Profile data is returned in the format that is appropriate to the locale.
    • Contact data is returned in the format that is appropriate to the locale.

    A culture name string from the table in Supported locales.

    None

    locale=es

    return_ssl_resources

    By default, Live Connect uses Secure Hypertext Transfer Protocol (HTTPS) to refer to the resources it returns, such as the source URLs for SkyDrive items. This helps prevent web-browser warnings when an originating website also uses HTTPS.

    Set this parameter to false if you don't want the returned resource to use HTTPS. When set to false, the returned resources will use HTTP.

    true/false

    true

    return_ssl_resources=false

    For example, the following URL makes a GET request for the user's contacts list, with the pretty parameter set to false.

    https://apis.live.net/v5.0/me/contacts?pretty=false&access_token=ACCESS_TOKEN

    Top


Referencing the APIs

The Live Connect APIs include the JavaScript API (Windows 8 and web), the Managed API (Windows 8 and Windows Phone), the iOS API, the Android API, and the Representational State Transfer (REST) API. The following sections guide you to info about how to reference these APIs:

  • Referencing the JavaScript API (Windows 8 and web)
  • Referencing the Managed API (Windows 8 and Windows Phone)
  • Referencing the iOS APIs
  • Referencing the Android APIs
  • Referencing the REST APIs

Referencing the JavaScript API (Windows 8 and web)

Instructions for Windows Store apps using JavaScript

To reference the APIs in a project in Microsoft Visual Studio 11 for Windows 8, see the "Referencing the APIs with JavaScript" section in Windows Store apps.

Instructions for client-side websites and scripts that use JavaScript

To reference the API, for client-side websites and scripts that use JavaScript, set a reference to a web-based version of the wl.js file from your code, like this.

<script src="//js.live.net/v5.0/wl.js"></script>

A web-based debugging version of wl.js, called wl.debug.js, is also available. It is an uncompressed version of wl.js. To call it, substitute wl.debug.js for wl.js, like this.

<script src="//js.live.net/v5.0/wl.debug.js"></script>

Web-based localized versions of the APIs are available for JavaScript. You add a URL segment that specifies the culture-name string for the localized version that you want to use. For example, to load the web-based Japanese version, your app uses a URL, like this.

<script src="//js.live.net/v5.0/ja/wl.js"></script>

For a complete list of supported localized versions, see Supported locales.

Top

Referencing the Managed API (Windows 8 and Windows Phone)

To reference the API for Windows Store apps with C#, see the "Referencing the APIs with C#" section in Windows Store apps. To reference the API for Windows Phone apps with C#, see the "Referencing the APIs with C#" section in Windows Phone apps.

Top

Referencing the iOS APIs

To reference the APIs for Objective-C, see the "Referencing the APIs with Objective-C" section in iOS apps.

Top

Referencing the Android APIs

To reference the APIs for Java, see the "Referencing the APIs with Java" section in Android apps.

Top

Referencing the REST APIs

Use the info in Server-side scenarios to learn about available REST calls and their syntax. To learn how to make REST calls for your specific platform and programming language combination, see your documentation.

Top


Signing users in

Before your app can work with a user's info, the user must be signed in to their Microsoft account. Typically, you do this is by adding sign-in functionality to your app in the form of a button or a hyperlink. After the user's Microsoft account has been verified, the app receives an access token. This access token confirms that the user successfully signed in and it specifies which parts of the user's info your app can work with and for how long.

The Live Connect APIs support several different ways to help you add sign-in functionality to your app. Windows Store apps use the sign-in features provided by Windows 8 and other types of apps can use the sign-in UI provided by the Live Connect APIs.

The sign-in process consists of the following steps:

  • Initialize the Live Connect APIs
  • Allow the user to sign-in to their Microsoft account, if they haven't already signed in
  • Get the session info after the user sign's in

Implementing the sign-in functionality is described for the following programming languages.

  • Signing a user in with JavaScript for Windows Store apps and HTML
    • Signing a user in with C# for Windows Store apps and Windows Phone apps
      • Signing a user in with Objective-C for iOS
      • Signing a user in with Java for Android
      • Signing a user in with REST
      • Next steps

      To get the most benefit from the code examples in this topic, refer to the context of the larger code samples in Working with the code examples.

      Design tip

      When you implement the sign-in functionality for your app, we strongly recommend that you use the Live Connect APIs to manage session state. For example, use the Live Connect APIs to determine when to change the Live Connect sign-in control's text between "sign in" and "sign out", maintain custom user states, and manage access and refresh tokens. If you write custom code to manage session-state logic, that code could cause problems by creating inconsistencies with the session state that is managed by the Live Connect APIs.

      Signing a user in with JavaScript for Windows Store apps and HTML

      The Live Connect APIs provide two functions that you can use to sign-in users from your app in JavaScript.

      • WL.login

        Adds sign-in functionality to any HTML element.

      • WL.ui

        Displays a sign-in button in your app.

      Initialize the Live Connect APIs

      Initialize the Live Connect APIs by subscribing to the auth.login event and calling WL.init when the page loads. Calling WL.init with the wl.signin scope enables single sign-in and the sign-in UI.

      To use this example in your app, replace APP_CLIENT_ID with your app's client ID, and REDIRECT_URL with your app's redirect URL.

      Note Windows Store apps using JavaScript don't need to specify the client_id, redirect_uri, and response_type parameters in the call to WL.init.

      HTML
      WL.Event.subscribe("auth.login", onLogin);
      HTML
      WL.init({
    client_id: APP_CLIENT_ID,
    redirect_uri: REDIRECT_URL,
    scope: "wl.signin",
    response_type: "token"
});

      Sign-in using WL.login

      In Windows 8, your Windows Store apps using JavaScript, should use the WL.login function to use the sign-in UI provided by Windows.

      For all other types of apps, WL.login is ideal for situations where you need to provide a richer sign-in experience than the default UI provides, such as when the user must provide additional confirmation or consent for your app to work with the user's info.

      When you use WL.login, you must provide the specific scopes and permissions that your app requires. In this example, the custom signInUser function calls WL.login to sign in the user with the wl.signin scope . The custom signInUser function is called when the user clicks the accompanying HTML button control.

      (In this case, the results of the sign in are handled by a custom onLoginComplete function, which is provided later in this topic.)

      HTML
      function signInUser() {
    WL.login({
        scope: "wl.signin"
    }, onLoginComplete);
}

document.write("<button onclick='signInUser()'>" +
    "Sign In</button>");

      Sign-in using WL.ui

      If you want to follow a controls-based approach to signing users in and you're not writing a Windows Store app, we recommend that you use the WL.ui function to create a Live Connect sign-in control. With this control, you define the type of UI element you want to create.

      To add a sign-in control to your app, create a container element, such as a <div> tag with the signin ID, like this.

      HTML
      <div id="signin"></div>

      Now you can call WL.ui to create the sign-in control. When this code runs, it adds a sign-in button to the <div> tag with the signin ID.

      After the user clicks the sign-in button and successfully signs in, Live Connect asks the user to okay, or consent to, the wl.signin scope .

      HTML
      WL.ui({
    name: "signin",
    element: "signin"
});

      In general, we recommend that you include the sign-in control as part of your initialization code.

      For the sign-in coding patterns that are appropriate for Windows Store apps using JavaScript, see Guidelines for the Microsoft account sign-in experience.

      Getting session info and handling events

      Many of the functions in the Live Connect APIs support an optional callback parameter that your JavaScriptapp can use to control what happens after a call finishes.

      You can also use an event handler to detect changes in user status. To handle events from the Live Connect APIs, call WL.Event.subscribe. In this example, the code subscribes to the auth.login event, which is fired after the user signs in. After calling the code in this example, the onLogin function will be called after the user signs in.

      HTML
      WL.Event.subscribe("auth.login", onLogin);

      The onLogin function in this example displays the "Signed in" message.

      HTML
      function onLogin() {
    document.getElementById("infoLabel").innerText = "Signed in.";
}

      Another common event that an app might track is auth.sessionChange. This event is fired when an aspect of the sign-in session changes, such as when the user consents to a new scope.

      This code subscribes to the auth.sessionChange event so that the onSessionChange function will be called when an aspect of the user's session changes.

      HTML
      WL.Event.subscribe("auth.sessionChange", onSessionChange);

      The onSessionChange function calls WL.getSessionto get a session object for the user. The session object contains information such as the user ID, access token, and the scopes to which the user has consented.

      HTML
      function onSessionChange() {
    var session = WL.getSession();
    if (session) {
    document.getElementById("infoLabel").innerText =
        "Something about the session changed.";
    }
    else {
        document.getElementById("infoLabel").innerText =
            "Signed out or session error.";
    }
}

      Top

      Signing a user in with C# for Windows Store apps and Windows Phone apps

      Windows Store apps should use the sign-in controls provided by Windows 8. For more info about the Windows 8 sign-in experience, see Guidelines for the Microsoft account sign-in experience.

      Windows Phone apps using C# can use the sign-in control provided by the Live Connect APIs.

      You can use the Live Connect sign-in control in C#.

      Initialize the Live Connect APIs

      Windows Store apps using C# and Windows Phone apps using C# initialize the Live Connect APIs when the app starts.

      Sign in with the sign-in control

      Windows Store apps should use the sign-in controls provided by Windows 8. For more info about the Windows 8 sign-in experience, see Guidelines for the Microsoft account sign-in experience.

      Your Windows Phone app using C# can add the sign-in control provided by the Live Connect APIs by adding the control to the app's Extensible Application Markup Language (XAML). The following code shows an example of this.

      The Scopes property must be set for Windows Phone apps to indicate the scopes and permissions required.

      For Windows Phone apps, you must also set the SessionChanged property to the method that handles that event. You must also set the ClientId property to the app's client ID.

      The sign-in control has other properties that you can set to customize your app's appearance.

      • Branding

        Specifies the logo to display on the sign-in button. BrandingType describes the possible values for this property.

      • TextType

        Specifies the text to display on the sign-in button. ButtonTextType describes the possible values for this property.

      If you don't define these properties, the sign-in button will display the Windows brand logo with the text "Sign in".

      Here's what the XAML code might look like for a Windows Phone app. The default page-level attributes are omitted from this example for clarity. If you use this code in your own app, replace CLIENT_ID with your app's client ID.

      <phone:PhoneApplicationPage
    ...
    xmlns:my="clr-namespace:Microsoft.Live.Controls;assembly=Microsoft.Live.Controls">
    <Grid x:Name="LayoutRoot" Background="Transparent">
        <my:SignInButton Name="btnLogin" ClientId="CLIENT_ID" Scopes="wl.signin wl.basic" Branding="Windows" TextType="SignIn" SessionChanged="btnLogin_SessionChanged" HorizontalAlignment="Left" VerticalAlignment="Top" />
        <TextBlock Height="32" HorizontalAlignment="Left" Margin="12,78,0,0" Name="infoTextBlock" Text="" VerticalAlignment="Top" Width="419" />
    </Grid>
</phone:PhoneApplicationPage>

      Building a custom sign-in experience

      If your app needs a customized sign-in experience, your app can prompt the user to sign in without using the Live Connect sign-in control. Likewise, after the user has signed-in, you can prompt user to grant access to additional scopes when your app needs them.

      One way to do this is to create a button control, and then call this code in the button control's click event handler, like this.

      [C# for Windows Store apps and Windows Phone apps]

      C#
      private async void btnMoreScopes_Click(object sender, RoutedEventArgs e)
{
    try
    {
        LiveAuthClient auth = new LiveAuthClient();
        LiveLoginResult loginResult = await auth.LoginAsync(new string[] { "wl.basic" });
        if (loginResult.Status == LiveConnectSessionStatus.Connected)
        {
            this.infoTextBlock.Text = "Signed in.";
        }
    }
    catch (LiveAuthException exception)
    {
        this.infoTextBlock.Text = "Error signing in: " + exception.Message;
    }
}

      Here's what the code does:

      1. Initializes an instance of the LiveAuthClient.
      2. Calls the LoginAsync method for the instance of LiveAuthClient, specifying the requested scopes.
      3. Verifies whether the result of the LoginAsync method call is established and connected. If so, sets the instance of a LiveConnectSession variable. Also, initializes an instance of the LiveConnectClient class for the connected client's session.

      Get session info

      This example shows the custom method that handles the sign-in control's SessionChanged event.

      C#
      private void btnLogin_SessionChanged(object sender, LiveConnectSessionChangedEventArgs e)
{
    if (e.Status == LiveConnectSessionStatus.Connected)
    {
        session = e.Session;
        client = new LiveConnectClient(session);
        infoTextBlock.Text = "Signed in.";
    }
    else
    {
        infoTextBlock.Text = "Not signed in.";
        client = null;
    }
}

      Here's what the code does:

      1. Checks to see if the instance of the LiveConnectSessionChangedEventArgs (represented here by the variable e) session exists and is connected successfully.
      2. If so, sets the instance of LiveConnectSession (represented here by the global variable session, which was declared earlier) to the connect client's session, so that it can be reused later in code. It also initializes an instance of the LiveConnectClient class, which represents the connected client's session (represented here by the global variable client, which was declared earlier), so that it also can be reused later in code.
      3. If the session can't be established and connected successfully, display an error message and set an instance of the LiveConnectClient class to null.

      Localizing the sign-in control for Windows Phone apps

      To display a localized version of the sign-in control and the consent page, follow these steps.

      1. Add the list of all target culture IDs to the <SupportedCultures> tag in your project file.

        This example shows what the <SupportedCultures> tag would look like if your Windows Phone app targeted French.

        XML
            <SupportedCultures>fr<SupportedCultures>

        For more info about using the <SupportedCultures> tag, see How to: Add Resources to a Silverlight-based Application.

        For the list of cultures that Windows Phone apps support, see Culture and Language Support.

      2. Next, call this code before calling the Live Connect APIs, where CULTURE_ID is a supported culture ID, like fr-FR for French:

        C#
            System.Threading.Thread.CurrentThread.CurrentUICulture =
        new System.Globalization.CultureInfo("CULTURE_ID");

      Top

      Signing a user in with Objective-C for iOS

      One of the ways to sign a user in with Objective-C is when the app starts. Here's how.

      ObjectiveC
      - (void)viewDidLoad
{
    [super viewDidLoad];
    self.liveClient = [[LiveConnectClient alloc] initWithClientId:APP_CLIENT_ID
                                                         delegate:self
                                                        userState:@"genesis"];
}

- (void) authCompleted:(LiveConnectSessionStatus)status
               session:(LiveConnectSession *)session
             userState:(id)userState
{
    if (session != nil) {
        self.statusLabel.text = @"You are signed in.";
    }
}

- (void) authFailed:(NSError *)error
          userState:(id)userState
{
    // Failed.
}

      Here's what this code does:

      1. In the viewDidLoad method, initializes an instance of the LiveConnectClient interface, named liveClient, specifying the app's client ID, indicating that the current instance will be handling the initialization success and failure messages, and specifying an optional, unique user-state argument (@"genesis", in this case) for easier method handling later.
      2. If the LiveConnectClient instance is successfully initialized, the authCompleted:session:userState method is called. Otherwise, the authFailed:userState method is called.
      3. If the user successfully signs in and consents, the authCompleted:session:userState method is called once again. Otherwise, the authFailed:userState method is called.

      You can also prompt the user to sign in after the app starts. One way to do this is to create a button control and then call the sign-in code in the button control's click-event handler, like this.

      ObjectiveC
      - (IBAction)onClickSignInButton:(id)sender {
    if (self.liveClient.session == nil)
    {
        [self.liveClient login:self
                        scopes:[NSArray arrayWithObjects:@"wl.signin", nil ]
                      delegate:self
                     userState:@"signin"];
    }
    else
    {
        [self.liveClient logoutWithDelegate:self
                                  userState:@"signout"];
    }
}

- (void) authCompleted:(LiveConnectSessionStatus)status
               session:(LiveConnectSession *)session
             userState:(id)userState
{
    [self updateButtons];
    if (session != nil) {
        self.statusLabel.text = @"You are signed in.";
    }
}

- (void) authFailed:(NSError *)error userState:(id)userState
{
    // Failed.
}

- (void) updateButtons {
    LiveConnectSession *session = self.liveClient.session;
    NSString *signInButtonText = (session == nil)? @"Sign in": @"Sign out";
    [self.signInButton setTitle:signInButtonText
                       forState:UIControlStateNormal];
}

      Here's what the code does:

      1. Uses the login:scopes:delegate:userState method of the LiveConnectClient instance, specifying the scopes to use, indicating that the current instance will be handling the authorization success and failure messages, and specifying a unique user-state argument (@"signin", in this case) for easier method handling later.
      2. If the user successfully signs in and consents, the authCompleted:session:userState method is called. Otherwise, the authFailed:userState method is called.

      Note This code's parent interface must implement the LiveAuthDelegate interface before calling the authCompleted and authFailed methods.

      Signing a user in with Java for Android

      One of the ways to sign a user in with Java is when the app starts. Here's how.

      Java
      @Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    this.resultTextView = (TextView)findViewById(R.id.resultTextView);
    this.auth = new LiveAuthClient(this, MyConstants.APP_CLIENT_ID);
}

@Override
protected void onStart() {
    super.onStart();
    Iterable<String> scopes = Arrays.asList("wl.signin", "wl.basic");
    this.auth.login(scopes, this);
}

public void onAuthComplete(LiveStatus status, LiveConnectSession session, Object userState) {
    if(status == LiveStatus.CONNECTED) {
        this.resultTextView.setText("Signed in.");
        client = new LiveConnectClient(session);
    }
    else {
        this.resultTextView.setText("Not signed in.");
        client = null;
    }
}

public void onAuthError(LiveAuthException exception, Object userState) {
    this.resultTextView.setText("Error signing in: " + exception.getMessage());
    client = null;
}

      Here's what this code does:

      1. In the app's main Activity class, in the onCreate method, initializes an instance of the LiveAuthClient class, specifying the app's client ID.
      2. In the app's main Activity class, in the onStart method, calls the login method for the instance of LiveAuthClient, specifying the requested scopes.
      3. If the connected client's session is established and connected, calls the onAuthComplete method, which initializes an instance of the LiveConnectClient class for the connected client's session (represented here by the global variable client, which was declared earlier), so that it also can be reused later in code.
      4. If, however, the connected client's session cannot be established and connected, calls the onAuthError method and displays an error message.

      After an initial sign-in, you can prompt the signed-in user to okay additional scopes that your app needs. One way to do this is to create a button control and then call the sign-in code in the button control's click-event handler, like this.

      Java
      public void moreScopes() {
    auth.login(this, Arrays.asList(new String[] { "wl.basic" }), new LiveAuthListener() {
        public void onAuthComplete(LiveStatus status, LiveConnectSession session, Object userState) {
            if (status == LiveStatus.CONNECTED) {
                resultTextView.setText("Signed in.");
                client = new LiveConnectClient(session);
            } else {
                resultTextView.setText("Not signed in.");
                client = null;
            }
        }
        public void onAuthError(LiveAuthException exception, Object userState) {
            resultTextView.setText("Error signing in: " + exception.getMessage());
            client = null;
        }
    });
}

      Here's what the code does:

      1. Defines a list of additional scopes.
      2. Calls the instance of the initialize method of the LiveAuthClient class (represented here by the global variable auth, which was declared earlier) with the list of additional scopes and a new instance of a LiveAuthListener class.
      3. If the connected client's session is established and connected, calls the onAuthComplete method, which initializes an instance of the LiveConnectClient class for the connected client's session (represented here by the global variable client, which was declared earlier), so that it also can be reused later in code.
      4. If, however, the connected client's session cannot be established and connected, calls the onAuthError method and displays an error message.

      Signing a user in with REST

      If your app can't use any of the approaches previously described in this topic, we provide a Representational State Transfer (REST) implementation. To use it, your app must initiate the sign-in process by contacting the Live Connect authorization web service. To do this, make the following call from a web browser or a web-browser control.

      HTML
      GET https://login.live.com/oauth20_authorize.srf?client_id=CLIENT_ID&scope=SCOPES&response_type=RESPONSE_TYPE&redirect_uri=REDIRECT_URL

      Note

      Mobile apps should append &display=touch to the authorize URL.

      In this code, replace the following values:

      • Replace CLIENT_ID with your app's client ID.
      • Replace SCOPES with the list of scopes to be requested. To specify more than one scope, separate each scope with the escape code for a space, for example, wl.signin%20wl.basic. (For more info about scopes, see Obtaining user consent).
      • Replace RESPONSE_TYPE with the specific type of response. If you're using the implicit grant flow, use token to specify an access token to be returned. If you're using the authorization code grant flow, use code to specify an authorization code to be returned.
      • If you're using the implicit grant flow, replace REDIRECT_URL with https://login.live.com/oauth20_desktop.srf. If you're using the authorization code grant flow, replace REDIRECT_URL with the URL to your callback webpage. If you specified a redirect domain when you created your client ID (like http://www.contoso.com), the redirect domain portion of the URL must be the same as the one that you specified when your client ID was created. In any case, the URL must use URL escape codes in this REST call, such as %20 for spaces, %3A for colons, and %2F for forward slashes.

        Note For details about the implicit grant flow and the authorization code grant flow, see OAuth 2.0.

      When Live Connect receives this call, it checks to see if the user is already signed in. If not, the user is prompted to provide his or her Microsoft account credentials.

      After the user successfully signs in and consents to the requested scopes, the Live Connect authorization web service uses the redirect domain to return the user to your app. If you're using the implicit grant flow, you'll see this.

      https://login.live.com/oauth20_desktop.srf#access_token=ACCESS_TOKEN&token_type=bearer&authentication_token=AUTHENTICATION_TOKEN&expires_in=3600&scope=SCOPES

      You use this access token (represented here as ACCESS_TOKEN) to work with a user's info. To see how, skip to the end of this section.

      However, if you're using the authorization code grant flow, different info is returned, and you'll need to make one more call. Here's what's returned.

      http://www.contoso.com/Callback.htm?code=AUTHORIZATION_CODE

      If you're using the authorization code grant flow, you use this authorization code (represented here as AUTHORIZATION_CODE) to make another call to obtain an access token.

      POST https://login.live.com/oauth20_token.srf

Content-Type: application/x-www.form-urlencoded

client_id=CLIENT_ID&redirect_uri=REDIRECT_URL&client_secret=CLIENT_SECRET&code=AUTHORIZATION_CODE&grant_type=authorization_code

      In the body, replace these:

      • Replace CLIENT_ID with your app's client ID.
      • Replace REDIRECT_URL with the URL to your callback webpage. This URL must be the same as the URL that you specified when you requested an authorization code. The URL must use URL escape codes, such as %20 for spaces, %3A for colons, and %2F for forward slashes.
      • Replace CLIENT_SECRET with the client secret that you received when your client ID was created.
      • Replace AUTHORIZATION_CODE with the authorization code that was returned on the initial call.

      If this second call is successful, the response from the Live Connect authorization web service contains a JavaScript Object Notation (JSON)-formatted object that includes the access token. The access token is contained in a JSON-formatted object that looks like this, where ACCESS_TOKEN represents the actual access token, and SCOPES represents the actual scopes.

      {
    "access_token": "ACCESS_TOKEN",
    "expires_in": 3600,
    "scope":"SCOPES",
    "token_type":"bearer"
}

      At this point, you can use REST calls to work with the signed-in user's info. For each request, you must append an access_token parameter that contains the access token. Note that the access token is valid for only the number of seconds that are specified in the expires_in value. Here, REST_PATH represents the actual target REST path (like me), and ACCESS_TOKEN represents the actual access token.

      https://apis.live.net/v5.0/REST_PATH?access_token=ACCESS_TOKEN

      For info about using this implementation in a server-side website or script, see Server-side scenarios.

      Top

      Next steps

      Now that you understand how to sign users in by using the Live Connect APIs, learn more about:

      • Scopes and permissions
      • Obtaining user consent
      • Getting user data

      Top


Obtaining user consent

This topic describes how an app requests permission from the user to access data the user has stored in Hotmail, Microsoft SkyDrive, Windows Live Messenger, and other services that are compatible with Live Connect.

Before your app can access a user's data, the signed-in user must consent to letting the app access their data. The Live Connect APIs divide this consent into categories, called scopes.

The common tasks that your app might do to do work with the user's data include:

  • Request the initial scopes for the app
  • Request additional scopes from the user
  • List the scopes to which the app has already been given permission

How to implement these common tasks are described for the languages that the Live Connect APIs support.

  • Overview of obtaining user consent
    • Obtaining user consent in Windows Store apps
    • Obtaining user consent in JavaScript for HTML
      • Obtaining user consent in C# for Windows Phone apps
        • Obtaining user consent in Objective C for iOS
          • Obtaining user consent in Java for Android
            • Obtaining user consent using REST
              • Next steps

              To fully understand the code examples in this topic, you can use them in the context of larger code reference samples that we describe in Working with the code examples.

              Overview of obtaining user consent

              Common scopes

              Some common scopes that your app might want to request are:

              • wl.basic—Allows access to a user's basic info, such as his or her Hotmail contact list.
              • wl.emails—Allows access to a user's email addresses.
              • wl.photos—Allows access to a SkyDrive user's photos.

              For a complete list of scopes, see Scopes and permissions.

              Requesting initial scopes

              In most cases, you request a user's consent to access his or her info by adding one or more scopes to the sign-in functionality on your site.

              Important

              We recommend that you limit the number of scopes you request at any given time to the smallest number necessary to perform a task. This helps your users better understand what they are sharing with your app.

              If a user chooses to use a feature of your app that requires a scope that it doesn't currently have permission to access, your app must get consent for the new scope from the user. This code example shows how to do that in JavaScript.

              User experience

              The Live Connect APIs use OAuth 2.0 to sign in users and provide consent to your app. When a user signs in to your app, he or she is redirected to a window that is hosted by the Live Connect authorization web service.

              Note The UI that your users see might differ from these examples depending on your app type and the user's locale.

              Windows Live sign-in dialog box

              The user types his or her Microsoft account credentials in this window. If the user signs in successfully, he or she is directed to the consent page, which explains what info your app wants to work with.

              Important The data elements for which permission is being requested in this dialog box are determined by the scope values that you set in the call to instantiate the sign-in UI.

              Windows Live consent dialog box

              If the user clicks Yes, one of these events fires:

              • For JavaScript, the auth.login event fires.
              • For C#, the SessionChanged or LoginCompleted event fires.
              • For Objective-C, the authCompleted or authFailed event fires.
              • For Java, the onAuthComplete or onAuthError event fires.

              Your app subscribes to these events so that when one of them fires, the app can obtain the session object from the event handler method specified by one of the following:

              • For JavaScript, use the WL.Event.subscribe method.
              • For C#, use the SessionChanged or LoginCompleted event handler.
              • For Objective-C, use the authCompleted or authFailed event.
              • For Java, use the onAuthComplete or onAuthError event.

              After the user grants permission to access his or her data, your app can begin working with the user's information.

              After a user provides consent, Live Connect gives your app a special code, or access token, that lets your app work with the portion of the user's data to which he or she consented. By default, this access token is good for about one hour. After this hour is up, your app won't be able to work with the user's data anymore—it must ask the user to sign-in and give consent again. To request permission to access the data for a longer period of time, you can ask the user to consent to the wl.offline_access scope. The wl.offline_access scope gives your app an additional code, called a refresh token, which it can use to get a new access token whenever it needs one—even after the user signs out—typically, for up to a year. The user can, however, revoke your app's access at any time. If a user chooses to revoke consent to your app, no corresponding access tokens or refresh tokens will work—your app must ask the user to sign-in and give consent again.

              Customizing and localizing the sign-in experience

              You can customize the consent page, such as by adding an app logo or provide links to the terms-of-service and privacy statement for your app. For more info about these settings, see Configuring your app.

              You can also display a localized version of the consent page. For JavaScript details, see Signing a user in with JavaScript for Windows Store apps and HTML. For C# details, see Signing a user in with C# for Windows Store apps and Windows Phone apps.

              Top

              Obtaining user consent in Windows Store apps

              Windows Store apps should use the sign-in controls provided by Windows 8. For more info about the Windows 8 sign-in experience, see Guidelines for the Microsoft account sign-in experience.

              Obtaining user consent in JavaScript for HTML

              Requesting initial scopes in JavaScript for HTML

              If you're using JavaScript with the Live Connect sign-in control, you add a scope property to WL.init, and then you instantiate the sign-in control by calling WL.ui, like this example for client-side JavaScript.

              HTML
              WL.init({
    client_id: APP_CLIENT_ID,
    redirect_uri: REDIRECT_URL,
    scope: "wl.signin",
    response_type: "token"
});
              HTML
              WL.ui({
    name: "signin",
    element: "signin"
});

              Requesting additional scopes in JavaScript for HTML

              HTML
              function moreScopes_onClick() {
    WL.login({
        scope: ["wl.signin", "wl.basic"]
    }).then(
        function (session) {
            document.getElementById("infoLabel").innerText = "Signed in.";
        },
        function (sessionError) {
            document.getElementById("infoLabel").innerText =
                "Error signing in: " + sessionError.error_description;
        }
    );
}

              If you're not sure whether the user has consented to the scope required to perform an operation, you can wrap an API call in a call to WL.login by using an anonymous function like this.

              HTML
              WL.login({
    scope: "wl.share"
}, function() {
    WL.api({
        method: "POST",
        path: "/me/share",
        body: { message: "Hey everyone, it's my birthday!" }
    });
});

              If you use this pattern, the user will be prompted for credentials only if he or she has not consented to the required scope.

              Getting a list of current permissions in JavaScript for HTML

              HTML
              function checkPermissions_onClick() {
    WL.login({
        scope: "wl.basic"
    }).then(
        function (response) {
            WL.api({
                path: "me/permissions",
                method: "GET"
            }).then(
                function (response) {
                    var message = "";
                    for (property in response.data[0]) {
                        if (response.data[0].hasOwnProperty(property))
                            message += "<br />" + property;
                    }
                    document.getElementById("infoLabel").innerHTML = result;
                },
                function (responseFailed) {
                    document.getElementById("infoLabel").innerText =
                        "Error calling API: " + responseFailed.error.message;
                }
            );
        },
        function (responseFailed) {
            document.getElementById("infoLabel").innerText =
                "Error signing in: " + responseFailed.error_description;
        }
    );
}

              Top

              Obtaining user consent in C# for Windows Phone apps

              Requesting initial scopes in C# for Windows Phone apps

              If you're using the Live Connect sign-in control in a C# app, you set the initial scopes in the app's Extensible Application Markup Language (XAML) code. To learn how to do this, see Signing a user in with C# for Windows Phone apps.

              Requesting additional scopes in C# for Windows Store apps and Windows Phone apps

              C#
              private async void btnMoreScopes_Click(object sender, RoutedEventArgs e)
{
    try
    {
        LiveAuthClient auth = new LiveAuthClient();
        LiveLoginResult loginResult = await auth.LoginAsync(new string[] { "wl.basic" });
        if (loginResult.Status == LiveConnectSessionStatus.Connected)
        {
            this.infoTextBlock.Text = "Signed in.";
        }
    }
    catch (LiveAuthException exception)
    {
        this.infoTextBlock.Text = "Error signing in: " + exception.Message;
    }
}

              Getting a list of current permissions in C# for Windows Phone apps

              C#
              private async void btnGetPermissions_Click(object sender, RoutedEventArgs e)
{
    try
    {
        LiveConnectClient liveClient = new LiveConnectClient(this.session);
        LiveOperationResult operationResult = await liveClient.GetAsync("me/permissions");
        this.infoTextBlock.Text = operationResult.RawResult;
    }
    catch (LiveConnectException exception)
    {
        this.infoTextBlock.Text = "Error getting permissions: " + exception.Message;
    }
}

              Top

              Obtaining user consent in Objective C for iOS

              Requesting initial scopes in Objective C for iOS

              If you're using Objective-C, you can set the initial scopes in an instance of the login:scopes:delegate:UserState method of the LiveConnectClient interface, like this.

              ObjectiveC
              if ([userState isEqual:@"viewDidLoad"])
{
    [self.infoLabel setText:@"Initialized."];
    [self.liveClient login:self
                    scopes:[NSArray arrayWithObjects:@"wl.signin", nil]
                  delegate:self
                 userState:@"signin"];
}

              Requesting additional scopes in Objective-C for iOS

              ObjectiveC
              - (IBAction)onClickSignInButton:(id)sender {
    if (self.liveClient.session == nil)
    {
        [self.liveClient login:self
                        scopes:[NSArray arrayWithObjects:@"wl.signin", nil ]
                      delegate:self
                     userState:@"signin"];
    }
    else
    {
        [self.liveClient logoutWithDelegate:self
                                  userState:@"signout"];
    }
}

- (void) authCompleted:(LiveConnectSessionStatus)status
               session:(LiveConnectSession *)session
             userState:(id)userState
{
    [self updateButtons];
    if (session != nil) {
        self.statusLabel.text = @"You are signed in.";
    }
}

- (void) authFailed:(NSError *)error userState:(id)userState
{
    // Failed.
}

- (void) updateButtons {
    LiveConnectSession *session = self.liveClient.session;
    NSString *signInButtonText = (session == nil)? @"Sign in": @"Sign out";
    [self.signInButton setTitle:signInButtonText
                       forState:UIControlStateNormal];
}

              Getting a list of current permissions in Objective-C for iOS

              ObjectiveC
              - (void) displayScopes: (LiveConnectSession *) session
{
    self.displayLabel.text = [session.scopes componentsJoinedByString:@","];
}

              Top

              Obtaining user consent in Java for Android

              Requesting initial scopes in Java for Android

              If you're using Java, you can set the initial scopes in an instance of the login method of the LiveAuthClient class, like this.

              Java
              Iterable<String> scopes = Arrays.asList("wl.signin", "wl.basic");
this.auth.login(scopes, this);

              Requesting additional scopes in Java for Android

              Java
              public void moreScopes() {
    auth.login(this, Arrays.asList(new String[] { "wl.basic" }), new LiveAuthListener() {
        public void onAuthComplete(LiveStatus status, LiveConnectSession session, Object userState) {
            if (status == LiveStatus.CONNECTED) {
                resultTextView.setText("Signed in.");
                client = new LiveConnectClient(session);
            } else {
                resultTextView.setText("Not signed in.");
                client = null;
            }
        }
        public void onAuthError(LiveAuthException exception, Object userState) {
            resultTextView.setText("Error signing in: " + exception.getMessage());
            client = null;
        }
    });
}

              Getting a list of current permissions in Java for Android

              Java
              public void checkPermissions() {
    auth.login(this, Arrays.asList(new String[] { "wl.basic" }), new LiveAuthListener() {
        public void onAuthComplete(LiveStatus status, LiveConnectSession session, Object userState) {
            if (status == LiveStatus.CONNECTED) {
                resultTextView.setText("Signed in.");
                client = new LiveConnectClient(session);
                String scopes = TextUtils.join(" ", session.getScopes());
                resultTextView.setText("Signed in. Current scopes = " +  scopes );
            } else {
                resultTextView.setText("Not signed in.");
                client = null;
            }
        }
        public void onAuthError(LiveAuthException exception, Object userState) {
            resultTextView.setText("Error signing in: " + exception.getMessage());
            client = null;
        }
    });
}

              Top

              Obtaining user consent using REST

              Requesting initial scopes in REST

              For Representational State Transfer (REST), you specify scopes in the initial call to the Live Connect authorization web service, where CLIENT_ID is the actual client ID, and REDIRECT_URL is either a custom redirect URL or https://login.live.com/oauth20_desktop.srf, depending on your target OAuth grant flow. If you don't specify REDIRECT_URL, the value that was set in the redirect domain is used. For example, if the redirect domain is set to http://www.contoso.com in the app configuration and you don't specify REDIRECT_URL, then consent redirects to http://www.contoso.com#access_token=ACCESS_TOKEN.

              https://login.live.com/oauth20_authorize.srf?client_id=CLIENT_ID&scope=wl.signin&response_type=RESPONSE_TYPE&redirect_uri=REDIRECT_URL

              Note

              Mobile apps should append &display=touch to the authorize URL.

              You can request multiple scopes at a time. Each scope must be separated by a space, for example: wl.signin wl.basic. For REST, separate each scope with the escape character %20.

              To learn more about scopes, see Scopes and permissions, which explains all the scopes that you can use with your app.

              Requesting additional scopes in REST

              For REST, you must get a new access token that covers the additional scopes and any scopes that were consented to previously. You do this by specifying the list of scopes in a new call to the Live Connect authorization web service, like this.

              https://login.live.com/oauth20_authorize.srf?client_id=CLIENT_ID&scope=wl.signin%20wl.basic&response_type=RESPONSE_TYPE&redirect_uri=REDIRECT_URL

              Getting a list of current permissions in REST

              GET https://apis.live.net/v5.0/me/permissions?access_token=ACCESS_TOKEN

              The returned list of permissions will look similar to this. A "1" here represents a scope that the user has already consented to. (If a scope is not listed, the user hasn't consented to it for the app.)

              {
    "data": [
        {
            "wl.basic": 1,
            "wl.signin": 1
        }
    ]
}

              Top

              Next steps

              At this point, you understand how to sign in users by using the Live Connect APIs, and how scopes and the consent process work. From here, these topics might be interesting.

              • Getting user data to learn how to work with the info that the APIs return
              • Identity (profiles)

              Top


Getting user data

To access a user's info from Hotmail, Microsoft SkyDrive, Windows Live Messenger, and other services that are compatible with Live Connect, your app must check for two things. First, it must confirm that the user has signed in successfully. Second, it must request and receive the user's consent, to work with his or her info. For details about these steps, see Signing users in and Obtaining user consent.

This topic assumes that your app has initialized the Live Connect APIs successfully, the user has signed in successfully, and the user has consented to the wl.basic scope, which grants access to basic info about the user and his or her contacts.

  • Requesting info
    • Requesting info in JavaScript for Windows Store apps and HTML
    • Requesting info in C# for Windows Store apps] and Windows Phone apps
    • Requesting info in Objective-C for iOS
    • Requesting info in Java for Android
    • Requesting info using REST
  • Working with info
  • Next steps

To fully understand the code examples in this topic, you can use them in the context of larger code reference samples that we provide in Working with the code examples.

Requesting info

There are two different ways to work with a user's info.

  • The user ID of a person or contact
  • The me shortcut that provides access to the signed-in user.

These code examples show how to use these different methods in the languages and platforms the Live Connect APIs supports.

  • Requesting info in JavaScript for Windows Store apps and HTML
  • Requesting info in C# for Windows Store apps] and Windows Phone apps
  • Requesting info in Objective-C for iOS
  • Requesting info in Java for Android
  • Requesting info using REST

Requesting info in JavaScript for Windows Store apps and HTML

This code example shows how to request info about a specific person identified by the user ID, which is represented in this code example as USER_ID. In your code, replace USER_ID with the actual ID string of the user or contact for which you want to get info.

function readContact() {
    WL.api({
        path: "USER_ID",
        method: "GET"
    }, onReadContactCallback);
}

function onReadContactCallback(response) {
    if (!response.error) {
        var name = response.first_name;
        // Display user's first name.
    }
}

This code example shows how to use the me shortcut to request info about the signed in user.

...
WL.api({
    path: "me",
    method: "GET"
}, onApiCalled);
...

This code example shows how to use the me shortcut to get a list of the signed-in user's friends.

...
WL.api({
    path: "me/friends",
    method: "GET"
}, onApiCalled);
...

Assuming that your app has permission to access data about the user's friends, you can get that info by using the user ID of a particular friend, like this. In this example, the string value shown for the path parameter was in the collection returned by the preceding example. In your code, you would use a value returned by the preceding call and not a string constant as shown in this example.

...
WL.api({
    path: "contact.c1678ab4000000000000000000000000",
    method: "GET"
}, onApiCalled);
...

To work with info, use the WL.api method. For example, here's how to make a GET call to get the first name of a user's friend.

JavaScript
function getFriendName_onClick() {
    WL.login({
        scope: "wl.basic"
    }).then(
        function (response)
        {
            WL.api({
                path: "contact.09fb5b27000000000000000000000000",
                method: "GET"
            }).then(
                function (response) {
                    document.getElementById("infoArea").innerText =
                        "Friend's name is: " + response.first_name;
                },
                function (responseFailed) {
                    document.getElementById("infoArea").innerText =
                        "Error calling API: " + responseFailed.error.message;
                }
            );
        },
        function (responseFailed) {
            document.getElementById("infoArea").innerText =
                "Error signing in: " + responseFailed.error_description;
        }
    );
}

Requesting info in C# for Windows Store apps] and Windows Phone apps

This code example shows how to request info about a specific person identified by the user ID, which is represented in this code example as USER_ID. In your code, replace USER_ID with the actual ID string of the user or contact for which you want to get info.

private async void readContact(object sender, RoutedEventArgs e)
{
    try
    {
        LiveOperationResult operationResult = await client.GetAsync("USER_ID");
        dynamic result = operationResult.Result;
        string name = result.first_name;
        // Display user's first name.
    }
    catch (LiveConnectException exception)
    {
        // Display error if operation is unsuccessful.
    }
}

This code example shows how to use the me shortcut to request info about the signed in user.

...
LiveOperationResult operationResult = await client.GetAsync("me");
...

This code example shows how to use the me shortcut to get a list of the signed-in user's friends.

...
LiveOperationResult operationResult = await client.GetAsync("me/friends");
...

Assuming that your app has permission to access data about the user's friends, you can get that info by using the user ID of a particular friend, like this. In this example, the string value shown as the parameter to GetAsync was in the collection returned by the preceding example. In your code, you would use a value returned by the preceding call and not a string constant as shown in this example.

...
LiveOperationResult operationResult = await client.GetAsync("contact.c1678ab4000000000000000000000000");
...

To work with info, use methods of the LiveConnectClient class, such as GetAsync, PostAsync, PutAsync, and DeleteAsync for GET, POST, PUT, and DELETE calls, respectively. For example, here's how to get the first name of a user's friend.

C#
private async void btnFriendName_Click(object sender, RoutedEventArgs e)
{
    try
    {
        LiveAuthClient auth = new LiveAuthClient();
        LiveLoginResult loginResult = await auth.LoginAsync(new string[] { "wl.basic" });
        if (loginResult.Status == LiveConnectSessionStatus.Connected)
        {
            this.infoTextBlock.Text = "Signed in.";
        }
        LiveConnectClient connect = new LiveConnectClient(auth.Session);
        LiveOperationResult operationResult = await connect.GetAsync("me/friends");
        dynamic resultList = operationResult.Result;
        StringBuilder friendsNames = new StringBuilder();
        foreach (dynamic result in resultList.data)
        {
            friendsNames.Append(result.name);
            friendsNames.Append("\n");
        }
        this.infoTextBlock.Text = friendsNames.ToString();
    }
    catch (LiveAuthException exception)
    {
        this.infoTextBlock.Text = "Error signing in: " + exception.Message;
    }
    catch (LiveConnectException exception)
    {
        this.infoTextBlock.Text = "Error getting friend(s) name(s): " + exception.Message;
    }
}

Requesting info in Objective-C for iOS

This code example shows how to request info about a specific person identified by the user ID, which is represented in this code example as USER_ID. In your code, replace USER_ID with the actual ID string of the user or contact for which you want to get info.

- (IBAction)getMe:(id)sender
{
    [self.liveClient getWithPath:@"USER_ID"
                        delegate:self
                       userState:@"getUserID"];
}

- (void) liveOperationSucceeded:(LiveOperation *)operation
{
    if ([operation.UserState isEqual:@"getUserID"]) {
        [self.infoLabel setText:[NSString stringWithFormat:@"@", [operation.result objectForKey:@"first_name"]]];
    }
}

- (void) liveOperationFailed:(NSError *)error operation:(LiveOperation *)operation
{
    if ([operation.userState isEqual:@"getUserID"]) {
        [self.infoLabel setText:[NSString stringWithFormat:@"%@: %@", @"Error getting name", [error localizedDescription]]];
    }
}

This code example shows how to use the me shortcut to request info about the signed in user.

...
[self.liveClient getWithPath:@"me"
                    delegate:self
                   userState:@"getMe"];
...

This code example shows how to use the me shortcut to get a list of the signed-in user's friends.

...
[self.liveClient getWithPath:@"me/friends"
                    delegate:self
                   userState:@"getFriends"];
...

Assuming that your app has permission to access data about the user's friends, you can get that info by using the user ID of a particular friend, like this. In this example, the string value shown as the parameter to getWithPath was in the collection returned by the preceding example. In your code, you would use a value returned by the preceding call and not a string constant as shown in this example.

...
[self.liveClient getWithPath:@"contact.c1678ab4000000000000000000000000"
                    delegate:self
                   userState:@"getContact"];
...

To work with info, use methods of the LiveConnectClient interface, such as getWithPath, postWithPath, putWithPath, and deleteWithPath for GET, POST, PUT, and DELETE calls, respectively. For example, here's how to get the first name of a user's friend.

ObjectiveC
- (void) getContact
{
    [self.liveClient getWithPath:@"me/contacts"
                        delegate:self];
}

- (void) liveOperationSucceeded:(LiveOperation *)operation
{
    NSArray *contacts = [operation.result objectForKey:@"data"];
    NSDictionary *firstContact = [contacts objectAtIndex:0];
    self.displayLabel.text = [firstContact objectForKey:@"first_name"];
}

Requesting info in Java for Android

This code example shows how to request info about a specific person identified by the user ID, which is represented in this code example as USER_ID. In your code, replace USER_ID with the actual ID string of the user or contact for which you want to get info.

...
this.greetUserButton.setOnClickListener(new OnClickListener() {
    public void onClick(View v) {
        client.getAsync("USER ID", new LiveOperationListener() {
            public void onComplete(LiveOperation operation) {
                try {
                    JSONObject result = operation.getResult();
                    String name = result.getString("first_name");
                    // Display user's first name.
                } catch (JSONException e) {
                    // Display error if first name is unavailable.
                    return;
                }
            }
            public void onError(LiveOperationException exception, LiveOperation operation) {
                // Display error if operation is unsuccessful.
            }
        });
    }
});
...

This code example shows how to use the me shortcut to request info about the signed in user.

...
client.getAsync("me", new LiveOperationListener() {
    ...
});
...

This code example shows how to use the me shortcut to get a list of the signed-in user's friends.

...
client.getAsync("me/friends", new LiveOperationListener() {
    ...
});
...

Assuming that your app has permission to access data about the user's friends, you can get that info by using the user ID of a particular friend, like this. In this example, the string value shown as the parameter to getAsync was in the collection returned by the preceding example. In your code, you would use a value returned by the preceding call and not a string constant as shown in this example.

...
client.getAsync("contact.c1678ab4000000000000000000000000", new LiveOperationListener() {
    ...
});
...

To work with info, use methods of the LiveConnectClient class, such as getAsync, postAsync, putAsync, and deleteAsync for GET, POST, PUT, and DELETE calls, respectively. For example, here's how to get the first name of a user's friend.

Java
public void getFriendName() {
    client.getAsync("contact.c1678ab4000000000000000000000000", new LiveOperationListener() {
        public void onComplete(LiveOperation operation) {
            JSONObject result = operation.getResult();
            resultTextView.setText("Friend's name = " + result.optString("first_name"));
        }
        public void onError(LiveOperationException exception, LiveOperation operation) {
            resultTextView.setText("Error getting friend's name: " + exception.getMessage());
        }
    });
}

Requesting info using REST

This code example shows how to request info about a specific person identified by the user ID, which is represented in this code example as USER_ID. In your code, replace USER_ID with the actual ID string of the user or contact for which you want to get info and ACCESS_TOKEN with the access token provided when the user signed in.

GET https://apis.live.netv5.0/USER_ID?access_token=ACCESS_TOKEN

This code example shows how to use the me shortcut to request info about the signed in user. In your code, replace ACCESS_TOKEN with the access token provided when the user signed in.

GET https://apis.live.netv5.0/me?access_token=ACCESS_TOKEN

This code example shows how to use the me shortcut to get a list of the signed-in user's friends. In your code, replace ACCESS_TOKEN with the access token provided when the user signed in.

GET https://apis.live.netv5.0/me/friends?access_token=ACCESS_TOKEN

Assuming that your app has permission to access data about the user's friends, you can get that info by using the user ID of a particular friend, like this. In this example, the contact string shown was in the response returned by the preceding example. In your code, you would use a value returned by the preceding call and not the contact string shown in this example. Also, in your code, replace ACCESS_TOKEN with the access token provided when the user signed in.

GET https://apis.live.netv5.0/contact.c1678ab4000000000000000000000000?access_token=ACCESS_TOKEN

In REST, after you make the appropriate GET call, the first name of the user's friend's is in the response. Here's how to make a call by using the friend's ID. In this example, the contact string shown was in the response returned by the example above. In your code, you would use a value returned in your app and not the contact string shown in this example. Also, in your code, replace ACCESS_TOKEN with the access token provided when the user signed in.

GET https://apis.live.net/v5.0/contact.c1678ab4000000000000000000000000?access_token=ACCESS_TOKEN

Top

Working with info

The Live Connect APIs return the response as info formatted in JavaScript Object Notation (JSON). Here's a JSON-formatted object that contains a user's publicly available info.

{
  "id" : "contact.c1678ab4000000000000000000000000",
  "first_name" : "Roberto",
  "last_name" : "Tamburello",
  "name" : "Roberto Tamburello",
  "gender" : "male",
  "locale" : "en_US"
}

The REST reference topic describes the JSON-formatted object that is returned in response to each type of request.

Top

Next steps

Now you know how to get info about a user by using the Live Connect APIs. Learn more about:

  • Identity (profiles)
  • Hotmail (contacts and calendars)
  • SkyDrive (files and photos)

Top


Single sign-on for apps and websites

As apps and websites become more personalized, it becomes more important to simplify the authentication process. You can design your app or website to provide a single sign-on experience for your users. For example, if a user is signed into an app that supports Microsoft accounts, he or she doesn't have to sign in again to use a companion website.

Because Windows 8 enables users to sign in to their devices by using a Microsoft account, app developers can provide a single sign-on experience across Windows Store apps and companion websites. For example, a website can integrate the Live Connect APIs so that after a user signs in, he or she can also access Microsoft cloud services that are compatible with Live Connect—services like Hotmail and Microsoft SkyDrive. Or, if a user is signed in to a device running Windows 8, that user will already be signed in to the app's companion website.

Note

If you are migrating from the legacy Windows Live ID Web Authentication software development kit (SDK), you can use the procedures described in this topic to return a uid value from the authentication token.

  • Enable single sign-on in your app or website
  • Authenticate the signed-in user
  • Get the authentication token
  • Get authentication token data
  • Restrict JWT Issuing option for Windows 8 apps

Enable single sign-on in your app or website

To enable single sign-on functionality, request the wl.signin scope when the user signs in using Live Connect. For more information on how to sign in the user, see the topic Signing users in. When the user consents to the wl.signin scope, the user is treated as signed in to the app or website when he or she is signed in to any website that supports Microsoft accounts or signed in to a Windows 8 computer using Microsoft accounts.

Top

Authenticate the signed-in user

After the user is signed into your app or website, you may want to validate the user’s identity. This is useful when the user is signed in to a client app and the app wants to retrieve that user's info from a companion web service. In this case, the web service may want to confirm the identity of the user in a cryptographically secure manner.

The key to validating the user’s identity is an authentication token, which contains an app-specific user ID and is encoded as a JavaScript Object Notation (JSON) Web Token (JWT). The basic process for working with the authentication token is this:

  1. After the user successfully signs in and consents, the app or website gets the authentication token and saves it to a location that's recognized by the companion web service—for example, in a secure database.
  2. The companion web service gets the saved authentication token, verifies the authentication token's signature by using the app's or website's client secret, and then decodes the authentication token to get the authentication token data.
  3. The companion web service gets the user identifier value—and optionally also the package SID value or the audience value, or both—from the authentication token data. The companion web service then compares these values to any values that it's able to get for the user independently. If the values match, the user's identity is confirmed. Then, for example, the companion web service could call the previously mentioned secure database along with the matching values to get any settings that were previously stored for the user—settings such as the user's high game scores, subscription details, or shopping-cart status. How the companion web services does all of this is up to the developer and is outside the scope of this topic.

Top

Get the authentication token

To get the authentication token, use one of the following API calls.

  • For Representational State Transfer (REST), the authentication token is one of the values returned after the hash fragment as part of the response to a successful REST authorization request. It is represented in the following example as AUTHENTICATION_TOKEN. Note that you must first specify a redirect domain for your app. (To specify a redirect domain, see Configuring your app, in the "Specify a redirect domain" section.)
    http://www.contoso.com/callback.htm#access_token=ACCESS_TOKEN&authentication_token=AUTHENTICATION_TOKEN

    For more info, see Server-side scenarios.

  • For web apps using JavaScript, use the session object's authentication_token property. You can get the session object by calling the methods WL.Event.subscribe, WL.getLoginStatus, WL.getSession, and WL.login.
  • For Windows Phone apps using C#, use the Microsoft.Live.LiveConnectSession object's AuthenticationToken property.
  • For Windows Store apps using JavaScript or C#, you must first specify a redirect domain for your app. (To specify a redirect domain, see Configuring your app in the "Specify a redirect domain" section for Windows Store apps.) After you specify a redirect domain, use the session object's authentication_token property (for JavaScript) or the Microsoft.Live.LiveConnectSession object's AuthenticationToken property (for C#).
  • For iOS apps, use the LiveAuthDelegate.authCompleted:session:userState method's session parameter's authenticationToken property.
  • For Android apps, use the LiveAuthListener.onAuthComplete method's session parameter's getAuthenticationToken method.

Top

Get authentication token data

The authentication token contains two sets of data: the header that contains metadata about the token, and the body of the token that contains the actual token data. The following table describes the properties of the authentication token.

Property | Name | Info
Algorithm | alg | The cryptographic algorithm that is used to sign the token. Only HMAC SHA-256 is supported.
Type | typ | The type of token. Only a JSON web token is supported.
KID | kid | The key version field of the app.
Version | ver | The version identifier for the token.
Issuer | iss | Identifies the principal that issued the token.
Expiration | exp | Identifies the exact time when the token expires. This time is expressed in the number of seconds since 1 January 1970.
Audience | aud | Identifies the audience for which the JSON web token is intended. In this case, it is the domain name for the app.
User Identifier | uid | An identifier for the user, which is unique to the app. This is equivalent to the pairwise ID from the legacy Windows Live ID Web Authentication SDK.
Package SID | urn:microsoft:appurl | The Windows client identifier for the app, if there is one.

The following example shows an authentication token and the JSON objects that can be obtained by decoding it.

eyJhbGciOiJIUzI1NiIsICJ0eXAiOiJKV1QiLCAia2lkIjoiMCJ9.
eyJ2ZXIiOjEsICJpc3MiOiJ1cm46d2luZG93czpsaXZlaWQiLCAiZ
XhwIjoxMzA2Mjk2ODY2LCAiYXVkIjoib2F1dGgudW5pdHRlc3QuY2
9tIiwgInVpZCI6IjcxNmEyZGY5OWE2MWQ4NzlhMGQ2ZmMyNWM4YzM
3MzNmIiwgInVybjp3aW5kb3dzOnBhY2thZ2VzaWQiOiIifQ.gg5I3
8qJILse6-ELZ3p3cu4qJotcbx6aJ-Cs8TxvM5s

Header: {"alg":"HS256", "typ":"JWT", "kid":"0"}
Token: {"ver":1, "iss":"urn:windows:liveid", "exp":1306296866, "aud":"http://www.contoso.org",
"uid":"716a2df99a61d879a0d6fc25c8c3733f",
"urn:microsoft:appurl":"ms-app://s-1-15-2-355948911-3179402394-1368051653-2073632810-3145016855-291163204A-157622137B"}

To verify the authentication token's signature by using the app's or website's client secret, and to decode the authentication token, use code similar to that in the GitHub - liveservices website's /LiveSDK/Samples/Asp.net/AuthenticationToken/ sample folder.

Top

Restrict JWT Issuing option for Windows 8 apps

By default, for a Windows Store app using JavaScript or C#, Live Connect is restricted to issuing authentication tokens for that app only. This behavior is designed to prevent other Windows Store apps from getting authentication tokens that use the originating app's info. This behavior is specified in the Live Connect app management site for the originating app, in the API Settings page's Restrict JWT Issuing option, which is set to Yes by default.

To override this behavior, allowing other apps to get authentication tokens that use the originating app's info, set the Restrict JWT Issuing option to No.

For example, consider two apps that both use the same back-end web service: Contoso Sports and Contoso News. If Restrict JWT Issuing is set to Yes (the default) for Contoso Sports, Live Connect allows only Contoso Sports to get authentication tokens for its users; Contoso News can't get authentication tokens for users of Contoso Sports. However, if Restrict JWT Issuing is set to No, Live Connect allows Contoso News to get authentication tokens for users of Contoso Sports. This can be accomplished by having the back-end web services for Contoso News and Contoso Sports share user settings. However, the back-end web service won't also be able to easily distinguish, if it needs to, which authentication tokens are coming from Contoso News and which from Contoso Sports.

Top


Server-side scenarios

While client-side code works in many scenarios, there might be scenarios in which you don't want to use, or can't use client-side code or the Live Connect JavaScript API to access Live Connect services. Some examples of when you might prefer to access Live Connect services from your Web server include:

  • when you want to keep track of user sessions that use Live Connect.
  • when you want to connect the user's Microsoft account to your own Web site's credential system.
  • when you want your Web server to be able to access the user's info on their behalf when they are not online.

To access Live Connect services from your Web server, you can use the Representational State Transfer (REST) API or the Live Connect SDK for ASP.NET in server-side scripts.

To write scripts that exercise the Live Connect server-side scenario, you typically do the following:

  1. Prompt the user to sign in to Live Connect and to consent to the scopes that you have requested.
  2. If the user successfully signs in and consents, capture the authorization code that the Live Connect authorization web service returns to you.
  3. Use the authorization code to call the Live Connect authorization web service to obtain an access token—and a refresh token, if the user consented to the wl.offline_access scope. (You also get an authentication token, which is useful for single sign-on scenarios. For more info, see Single sign-on for apps and websites.)
  4. Use the access token to call the Live Connect REST API to work with the user's info, depending on the scopes for which consent has been granted. Repeat this step as needed until the Live Connect REST API indicates that the access token has expired.
    1. If the access token has expired, use the refresh token (if you have one) to obtain a new access token, and then go back to the beginning of step 4.
    2. If the refresh token has also expired, go back to step 1.

These topics describe this process in more detail.

  • Getting an authorization code
    • Using the REST API to get an authorization code
    • Using the Live Connect SDK for ASP.NET to get an authorization code
  • Getting tokens
    • Using the REST API to get tokens
    • Using the Live Connect SDK for ASP.NET to get tokens
  • Using an access token to work with a user's info
    • Using the REST API to work with a user's info
    • Using the Live Connect SDK for ASP.NET to work with a user's info
  • Using a refresh token to get a new access token and a new refresh token
    • Using the REST API to get a new access token and a new refresh token
    • Using the Live Connect SDK for ASP.NET to get a new access token and a new refresh token
  • Signing a user out
    • Using the REST API to sign a user out
    • Using the Live Connect SDK for ASP.NET to sign a user out
  • ASP.NET and PHP code samples

Getting an authorization code

The first step to obtain an access token and an authorization token—and a refresh token, if the user consented to a wl.offline_access scope request—is to obtain an authorization code. In a later step, you exchange this authorization code for an access token and an authorization token—and, optionally, a refresh token.

Retain the authorization code from this section for use in the next section.

  • Using the REST API to get an authorization code
  • Using the Live Connect SDK for ASP.NET to get an authorization code

Using the REST API to get an authorization code

To obtain an authorization code, direct the user to the Live Connect OAuth 2.0 endpoint by using the following URL and replace the following elements:

  • Replace CLIENT_ID with your app's client ID.
  • Replace SCOPES with the scopes that you want the user to give you permission to access. Separate each requested scope with the URL escape code %20.

    Note If you want to obtain a refresh token in addition to an access token, you must also include the wl.offline_access scope in the scope query parameter. (A refresh token enables you to obtain a replacement access token to interact directly with the Live Connect REST API on behalf of a user, after the user ends his or her web browsing session.)

  • Replace REDIRECT_URI with the Uniform Resource Identifier (URI) of your callback webpage. The callback URI must use URL escape codes, such as %20 for spaces, %3A for colons, and %2F for forward slashes.
https://login.live.com/oauth20_authorize.srf?client_id=CLIENT_ID&scope=SCOPES&response_type=code&redirect_uri=REDIRECT_URI

For example, the following URL uses a client ID of 0000000603DB0F, the wl.signin and wl.basic scopes, and a redirect URI of http://www.contoso.com/callback.php.

https://login.live.com/oauth20_authorize.srf?client_id=0000000603DB0F&scope=wl.signin%20wl.basic&response_type=code&redirect_uri=http%3A%2F%2Fwww.contoso.com%2Fcallback.php

Note Optionally, you can also append the following query parameters to the preceding URL:

  • A display query parameter, which represents a request for the display mode of the consent page, can be set to popup, touch, or none.
  • A locale query parameter, which is used by the request for consent page to display localized UI text in the user's preferred language. This query parameter can be set to a market value, such as en. For details, see Supported locales.
  • A state query parameter, which represents any arbitrary text string that you may want to pass to the redirect URL for your own use.

When the URL is called from a web page, the Live Connect authorization web service checks to determine whether there is a signed-in user. If the user is not signed in, he or she is prompted to sign in to Live Connect. After the user signs in, the Live Connect authorization web service checks to see whether the user previously consented to the requested scopes. If the user has not consented previously, he or she is prompted to consent to the requested scopes. If the user consents, the Live Connect authorization web service sends the authorization code to the redirect URI, with the authorization code appended as a query parameter named code, as shown in the following example.

http://www.contoso.com/callback.php?code=2bd12503-7e88-bfe7-c5c7-82274a740ff

Using the Live Connect SDK for ASP.NET to get an authorization code

This example shows how you can construct the URL if you are using the Live Connect SDK for ASP.NET.

C#
LiveAuthClient liveAuthClient = new LiveAuthClient(ClientId, ClientSecret, null);
string[] scopes = new string[] { "wl.signin", "wl.basic"};
string loginUrl = liveAuthClient.GetLoginUrl(scopes, "http://www.contoso.com/callback");

Top

Getting tokens

After you have obtained an authorization code, you exchange it for an access token and an authorization token—and a refresh token, if the user consented to a wl.offline_access scope request.

The following sections show how to use the Live Connect APIs to obtain the tokens. If you add wl.offline_access to the list of requested scopes in the following examples, and the user consents to your request, the Live Connect authorization web service sends to the callback URI an access token, an authentication token, and a refresh token. These tokens are represented as strings of characters, in the access_token, authentication_token, and refresh_token key/value pairs, inside a JavaScript Object Notation (JSON)-formatted object, as shown in the following example.

{
    "token_type":"bearer",
    "expires_in":3600,
    "scope":"wl.offline_access wl.signin wl.basic",
    "access_token":"EwCo...//access token string shortened for brevity//...AA==",
    "refresh_token":"*LA9...//refresh token string shorted for brevity//...k%65",
    "authentication_token":"eyJh...//authentication token string shortened for brevity//...93G4"
}

Note A typical refresh token string consists of well over 200 characters, so part of the refresh token string is omitted for brevity in the preceding example.

Retain this access token (and the refresh token, if you obtained one) for use in the following sections.

Note To use an authentication token, which is useful for single sign-on scenarios, see Single sign-on for apps and websites.

  • Using the REST API to get tokens
  • Using the Live Connect SDK for ASP.NET to get tokens

Using the REST API to get tokens

To obtain an access token and an authorization token (and, optionally, a refresh token), make an HTTP POST call to the Live Connect authorization web service by using the following URL.

https://login.live.com/oauth20_token.srf

The Content-Type header should have the value "application/x-www-form-urlencoded". Construct the request body as follows and replace the following elements:

  • Replace CLIENT_ID with your app's client ID.
  • Replace REDIRECT_URI with the URI to your callback webpage. This URI must be the same as the URI that you specified when you requested an authorization code. The URI must use URL escape codes, such as %20 for spaces, %3A for colons, and %2F for forward slashes.
  • Replace CLIENT_SECRET with your app's client secret. The client secret must use URL escape codes, such as %2B for the plus sign.
  • Replace AUTHORIZATION_CODE with the authorization code that you obtained earlier.
client_id=CLIENT_ID&redirect_uri=REDIRECT_URI&client_secret=CLIENT_SECRET&code=AUTHORIZATION_CODE&grant_type=authorization_code

For example, the following request body uses a client ID of 0000000603DB0F, a redirect URI of http://www.contoso.com/callback.php, a client secret of LWILlT555GicSrIATma5qgyBXebRI, and an authorization code of 2bd12503-7e88-bfe7-c5c7-82274a740ff.

client_id=0000000603DB0F&redirect_uri=http://www.contoso.com/callback.php&client_secret=LWILlT555GicSrIATma5qgyBXebRI&code=2bd12503-7e88-bfe7-c5c7-82274a740ff&grant_type=authorization_code

If the call is successful, the response for the HTTP POST request contains an access token and an authentication token. These tokens are each represented as a string of characters, in an access_token and an authentication_token key/value pair inside a JSON-formatted object, as shown in the following example.

{
    "token_type":"bearer"
    "expires_in":3600,
    "scope":"wl.signin wl.basic",
    "access_token":"EwCo...//access token string shortened for brevity//...AA==",
    "authentication_token":"eyJh...//authentication token string shortened for brevity//...93G4"
}

Note A typical token string consists of well over 550 characters, so part of each token string is omitted for brevity in the preceding example.

Using the Live Connect SDK for ASP.NET to get tokens

This example shows how to get the tokens if you are using the Live Connect SDK for ASP.NET.

C#
private LiveAuthClient liveAuthClient = new LiveAuthClient(ClientId, ClientSecret, null);
private LiveConnectSession session = null;

private async Task HandleAuthorizationAsync()
{
    try
    {
        LiveLoginResult result = await liveClient.ExchangeAuthCodeAsync(this.HttpContext);
        session = result.Session;
    }
    catch (LiveAuthException)
    {
    }
}

Task HandleAuthorizationAsync invokes LiveAuthClient.ExchangeAuthCodeAsync, which reads the authorization server’s response from the Http request. The server’s response can be either an authorization code or an error message. If the response is an authorization code, it retrieves the access token, authentication token, and refresh token from the authorization server. LiveAuthClient.ExchangeAuthCodeAsync returns an instance of LiveLoginResult, which has a Session property of the LiveConnectSession type. If the session is available, the Session property contains all the server response detail described in the earlier REST example.

Top

Using an access token to work with a user's info

After you have obtained an access token, you can use it to work with the consenting user's info.

  • Using the REST API to work with a user's info
  • Using the Live Connect SDK for ASP.NET to work with a user's info

Using the REST API to work with a user's info

To make an HTTP GET call to the Live Connect REST API to get user info, use the following URL and replace the following:

  • Replace REST_PATH with the REST path to the portion of the user's info that you want; for example, me.
  • Replace ACCESS_TOKEN with your access token.
https://apis.live.net/v5.0/REST_PATH?access_token=ACCESS_TOKEN

For example, the following URL uses a REST path of me, and an access token that starts with the characters "EwCo" and ends with the characters "AA==".

https://apis.live.net/v5.0/me?access_token=EwCo...//access token string shortened for brevity//...AA==

If the HTTP GET call is successful, the Live Connect REST API sends the requested info as a JSON-formatted object or collection, depending on the shape of the info, as shown in the following example.

{
   "id": "b6b2a7e8f2515e5",
   "name": "Apurva Dalia",
   "first_name": "Apurva",
   "last_name": "Dalia",
   "gender": null,
   "link": "http://cid-b6b2a7e8f2515e5.profile.live.com/",
   "locale": "en_US",
   "updated_time": "2011-10-26T21:13:05+0000"
}

Using the Live Connect SDK for ASP.NET to work with a user's info

This example shows how to work with a user's info if you are using the Live Connect SDK for ASP.NET.

C#
public async Task<ActionResult> Index()
{
    try
    {
        LiveAuthClient liveAuthClient = new LiveAuthClient(ClientId, ClientSecret, RedirectURL);
        LiveLoginResult result = await liveAuthClient.ExchangeAuthCodeAsync(this.HttpContext);
        if (result.Status == LiveConnectSessionStatus.Connected)
        {
            LiveConnectClient client = new LiveConnectClient(this.MSAuthClient.Session);
            LiveOperationResult meResult = await client.GetAsync("me");
            if (meResult != null)
            {
                dynamic meInfo = meResult.Result;
                this.SetNameField(meInfo.name);
            }
        }
    }
    catch (LiveAuthException authEx)
    {
        // Handle auth errors.
    }
    catch (LiveConnectException connectEx)
    {
        // Handle connect errors.
    }

    ...

    return View();
}

Top

Using a refresh token to get a new access token and a new refresh token

If you have obtained a refresh token, and the access token has expired, you can obtain a replacement access token and a replacement refresh token.

  • Using the REST API to get a new access token and a new refresh token
  • Using the Live Connect SDK for ASP.NET to get a new access token and a new refresh token

Using the REST API to get a new access token and a new refresh token

To obtain replacement tokens, make an HTTP POST call to the Live Connect authorization web service at the following URL.

https://login.live.com/oauth20_token.srf

The Content-Type header should have the value "application/x-www-form-urlencoded". Construct the request body using this template and replace the following elements:

  • Replace CLIENT_ID with your app's client ID.
  • Replace REDIRECT_URI with the URI to your callback webpage. This URI must be the same as the URI that you specified when you requested an authorization code. The URI must use URL escape codes, such as %20 for spaces, %3A for colons, and %2F for forward slashes.
  • Replace CLIENT_SECRET with your app's client secret. The client secret must use URL escape codes, such as %2B for the plus sign.
  • Replace REFRESH_TOKEN with the refresh token that you obtained earlier.
client_id=CLIENT_ID&redirect_uri=REDIRECT_URI&client_secret=CLIENT_SECRET&refresh_token=REFRESH_TOKEN&grant_type=refresh_token

For example, the following request body uses a client ID of 0000000603DB0F, a redirect URI of http://www.contoso.com/callback.php, a client secret of LWILlT555GicSrIATma5qgyBXebRI, and a refresh token that starts with "*LA9" and that ends with "xRoX".

client_id=0000000603DB0F&redirect_uri=http%3A%2F%2Fwww.contoso.com%2Fcallback.php&client_secret=LWILlT555GicSrIATma5qgyBXebRI&refresh_token=*LA9...//refresh token string shortened for brevity//...xRoX&grant_type=refresh_token

If the call is successful, the Live Connect authorization web service sends to the callback URI a replacement access token and a replacement refresh token. These tokens are represented as strings of characters, in the access_token and refresh_token key/value pairs, inside a JSON-formatted object, as shown in the following example.

{
    "token_type":"bearer",
    "expires_in": 3600,
    "scope": "wl.offline_access wl.signin wl.basic",
    "access_token":"FxDp...//access token string shortened for brevity//...BB==",
    "refresh_token":"Cla*...//refresh token string shorted for brevity//...pdeA",
    "authentication_token":"eyJh...//authentication token string shortened for brevity//...UWJE"
}

Using the Live Connect SDK for ASP.NET to get a new access token and a new refresh token

This example shows how to get a new access token and a new refresh token if you are using the Live Connect SDK for ASP.NET.

C#
public class AccountController : Controller, IRefreshTokenHandler
{
    Task IRefreshTokenHandler.SaveRefreshTokenAsync(RefreshTokenInfo tokenInfo)
    {
        await SaveRefreshTokenToDBForCurrentUserAsync(tokenInfo);
    }

    Task<RefreshTokenInfo> IRefreshTokenHandler.RetrieveRefreshTokenAsync()
    {
        return await RetrieveRefreshTokenFromDBForCurrentUserAsync();
    }

    public async Task<ActionResult> Refresh()
    {
        try
        {
             LiveAuthClient liveAuthClient = new LiveAuthClient(ClientId, ClientSecret, RedirectURL, this);
             LiveLoginResult result = await liveAuthClient.InitializeSessionAsync(this.HttpContext);
             session = result.Session;
        }
        catch (LiveAuthException)
        {
        }

        return View();
    }
}

Note

  • Refresh token is available if the login URL includes the scope wl.offline_access.
  • The AccountController class implements the IRefreshHandler in order to handle refresh token persistency.
  • The refresh token should be associated with the user ID in your app credential system.
  • IntializeSessionAsync retrieves a new access token using an available refresh token if the current session does not have a valid access token. The method will invoke the IRefreshTokenHandler.RetrieveRefreshTokenAsync() before it tries to retrieve a new access token, and it will invoke the IRefreshTokenHandler.SaveRefreshTokenAsync(), when it receives a new refresh token from the authorization server.

Top

Signing a user out

To sign a user out, make a call to the Live Connect authorization web service at the following URL.

  • Using the REST API to sign a user out
  • Using the Live Connect SDK for ASP.NET to sign a user out

Using the REST API to sign a user out

Within the larger URL, CLIENT_ID is the corresponding client ID, and REDIRECT_URL is the URL to redirect to after the Live Connect authorization web service successfully signs the user out. The domain portion of this redirect URL must match the one that is specified in the Live Connect app management site for the corresponding client ID.

https://login.live.com/oauth20_logout.srf?client_id=CLIENT_ID&redirect_uri=REDIRECT_URL

Using the Live Connect SDK for ASP.NET to sign a user out

This example shows how to sign a user out if you are using the Live Connect SDK for ASP.NET.

C#
LiveAuthClient liveAuthClient = new LiveAuthClient(ClientId, ClientSecret, null);
string loginUrl = liveAuthClient.GetLogoutUrl("http://www.contoso.com/logout");

// Clears the session in the cookie.
liveAuthClient.ClearSession(this.HttpContext);

Top

ASP.NET and PHP code samples

To see examples of calling these code patterns by using ASP.NET and PHP, see the ASP.NET and PHP code samples in the GitHub - LiveSDK collection.

Top


OAuth 2.0

Live Connect implements the OAuth 2.0 protocol to authenticate users. This topic describes both the authorization flows that Live Connect uses and the supported extension parameters.

In this topic, we assume that you are familiar with OAuth 2.0 and OAuth terminology. If you're new to OAuth, we recommend that you check out the OAuth 2.0 spec first, or refer to it when you come across a term or idea that's unfamiliar to you.

  • Supported OAuth flows
    • Implicit grant flow
    • Authorization code grant flow
  • Sign-in control flow
  • OAuth authorization request parameters
  • OAuth request and response parameters
  • Moving from OAuth WRAP to OAuth 2.0

Supported OAuth flows

Live Connect supports the following authorization flows:

  • Implicit grant flow
  • Authorization code grant flow
  • Sign-in control flow

Implicit grant flow

The implicit grant flow can be used by both web-based and desktop apps. In this flow, the client makes an authorization request to https://login.live.com/oauth20_authorize.srf with request_type=token. This is a standard OAuth 2.0 flow and is defined in detail in the Implicit Grant section of the OAuth 2.0 spec.

The following diagram illustrates how the implicit grant flow works.

OAuth 2.0 sign-in control flow diagram.

  1. The client starts the flow by directing the resource owner's user agent to the Live Connect authorization endpoint, by using a URL in the following format.

    https://login.live.com/oauth20_authorize.srf?client_id=CLIENT_ID&scope=SCOPES&response_type=token&redirect_uri=REDIRECT_URI

    This URL contains the client ID, requested scopes, and a redirection Uniform Resource Identifier (URI) to which the authorization web service sends the user agent after access is granted or denied.

    Note Do not include the wl.offline_access scope if you're using the implicit grant flow (response_type=token).

  2. The user is prompted for his or her sign-in credentials, and grants or denies the client's access request.

  3. Assuming that the user has granted access, the Live Connect authorization server redirects the user agent to the client by using the redirection URI that was provided in the initial request. The redirection URI includes an access token in the URI fragment. For example: http://contoso.com/Callback.htm#access_token=ACCESS_TOKEN.

  4. The user agent follows the redirection instructions by making a request to the Contoso web server. The user agent retains the URI fragment locally, but does not include it in the request to the server.

  5. The Contoso server returns a webpage (typically an HTML document that contains an embedded script) that is capable of accessing the full redirection URI, including the fragment that was retained by the user agent. The script can also extract the access token and other parameters that are contained in the fragment.

    The user-agent locally executes the script that was provided by the web server, to extract the access token and pass it to the client.

Top

Authorization code grant flow

In the authorization code grant flow, the client makes authorization requests by using request_type=code. It is a standard OAuth 2.0 flow, and is defined in full detail in the Authorization Code Grant section of the OAuth 2.0 spec. For further details, see Server-side scenarios.

The following diagram illustrates how the authorization code grant flow works.

OAuth 2.0 web server flow diagram.

  1. The client starts the flow by directing the resource owner's user agent to the Live Connect authorization endpoint, by using a URL in the following format.

    https://login.live.com/oauth20_authorize.srf?client_id=CLIENT_ID&scope=SCOPES&response_type=code&redirect_uri=REDIRECT_URI

    This URL contains the client ID, requested scopes, and a redirection URI to which the authorization web service sends the user agent after access is granted or denied.

  2. The authorization server authenticates the resource owner via the user agent, and establishes whether the resource owner grants or denies the client's access request.

  3. Assuming that the resource owner has granted access, the Live Connect authorization server redirects the user agent to the client by using the redirection URI that was provided in the initial request.

  4. The user agent calls the client with the redirection URI, which includes an authorization code and any local state that was provided by the client. For example: http://contoso.com/Callback.htm?code=AUTHORIZATION_CODE.

  5. The client requests an access token from the authorization server's token endpoint by using its client credentials for authentication, and includes the authorization code that was received in the previous step. The client includes the redirection URI that was used to obtain the authorization code for verification. The request URL has the following format:

    POST https://login.live.com/oauth20_token.srf

Content-type: application/x-www-form-urlencoded

client_id=CLIENT_ID&redirect_uri=REDIRECT_URI&client_secret=CLIENT_SECRET&code=AUTHORIZATION_CODE&grant_type=authorization_code

    The Live Connect authorization server validates the client credentials and the authorization code, and ensures that the redirection URI that was received matches the URI that was used to redirect the client in step 3.

  6. If the credentials are valid, the authorization server responds by returning an access token. If the wl.offline_access scope was requested, then a refresh token is also returned. To refresh the access token, the client must make a request to the following URL.

    POST https://login.live.com/oauth20_token.srf

Content-type: application/x-www-form-urlencoded

client_id=CLIENT_ID&client_secret=CLIENT_SECRET&redirect_uri=REDIRECT_URI&grant_type=refresh_token&refresh_token=REFRESH_TOKEN

    To make things easier for developers of desktop and mobile apps, the Live Connect OAuth 2.0 implementation provides the following special redirect URL: https://login.live.com/oauth20_desktop.srf. This enables apps that can host a web browser control (such as a Java app, Cocoa app, or .NET app) to handle redirects after the user has provided consent, by listening for when the user is redirected to https://login.live.com/oauth20_desktop.srf#access_token=ACCESS_TOKEN, and then retrieving the access token from the end of the URL using whatever mechanisms are available in the chosen client platform. Because apps must also refresh access tokens, the Live Connect app management site allows apps to be marked as mobile client apps. When this marker is specified and the special redirect URL (https://login.live.com/oauth20_desktop.srf) is used, the client secret is not required to refresh the access token. In that case, the URL for refreshing the access token looks like this.

    POST https://login.live.com/oauth20_token.srf

Content-type: application/x-www-form-urlencoded

client_id=CLIENT_ID&redirect_uri=https://login.live.com/oauth20_desktop.srf&grant_type=refresh_token&refresh_token=REFRESH_TOKEN

Top

Sign-in control flow

The sign-in control flow is unique to Live Connect. It uses the Live Connect sign-in control to simplify sign-in and consent for apps. Intended for use by browser-based apps, it does not require the app to use any server-side logic. You start the flow by using the JavaScript API (the WL.login method) or by embedding an HTML control (by calling the WL.ui method), rather than by calling the consent service directly by using an HTTP request. The sign-in control flow is the only web flow that supports seamless, single sign-in across Live Connect and non-Microsoft web apps. Single sign-in is the mechanism by which a user who is already signed in to Live Connect can go to a different website and be automatically signed in to that site, based on the Live Connect account. The user has control over this sign-in behavior on each website, on an opt-in basis.

The sign-in control flow is a variation of the implicit grant flow. The key difference between the two is that the sign-in control flow is implemented by using an invisible HTML iframe element that is embedded in the client webpage, and the implicit grant flow must be implemented by the client app.

Important Because the sign-in control flow requires no server-side processing, apps can access user info only after the page has loaded.

The sign-in control flow works as follows:

  1. The client starts the flow by directing the resource owner's user agent to the Live Connect authorization endpoint, by using a URL with the following format: https://login.live.com/oauth20_authorize.srf?client_id=CLIENT_ID&  scope=SCOPES&response_type=code&redirect_uri=REDIRECT_URI.

    This URL contains the client ID, requested scopes, local state, and a redirection URI to which the authorization web service sends the user agent after access is granted or denied.

  2. The user is prompted for his or her credentials, and grants or denies the client's access request.

Top

OAuth authorization request parameters

The following table lists the OAuth authorization request parameters that are used by Live Connect.

Parameter | Notes
client_id | The app's client ID.
display | The display type to be used for the authorization page. Valid values are "popup", "touch", "page", or "none".
locale | Optional. A market string that determines how the consent UI is localized. If the value of this parameter is missing or is not valid, a market value is determined by using an internal algorithm.
redirect_uri | Equivalent to the endpoint that is described in the OAuth 2.0 spec.
response_type | The type of data to be returned in the response from the authorization server. Valid values are "code" or "token".
scope | Equivalent to the scope parameter that is described in the OAuth 2.0 spec.
state | Equivalent to the state parameter that is described in the OAuth 2.0 spec.

Top

OAuth request and response parameters

The following table lists the OAuth request and response parameters that are used by Live Connect.

Parameter | Notes
client_id | The app's client ID.
client secret | The app's client secret.
grant_type | The authorization type that the server returns. Valid values are "authorization_code" or "refresh_token".
locale | Optional. A market string that determines how the consent UI is localized. If the value of this parameter is missing or is not valid, a market value is determined by using an internal algorithm.
redirect_uri | Equivalent to the endpoint that is described in the OAuth 2.0 spec.
response_type | The type of data to be returned in the response from the authorization server. Valid values are "code" or "token".
scope | Equivalent to the scope parameter that is described in the OAuth 2.0 spec.
state | Equivalent to the state parameter that is described in the OAuth 2.0 spec.
display | The display type to be used for the authorization page. Valid values are "popup", "touch", "page", or "none".

The following table lists the OAuth response parameters that are used by Live Connect.

Parameter | Notes
access_token | Equivalent to the access_token parameter that is described in the OAuth 2.0 spec.
authentication_token | The app's authentication token.
code | Equivalent to the code parameter that is described in the OAuth 2.0 spec.
expires_in | Equivalent to the expires_in parameter that is described in the OAuth 2.0 spec.
refresh_token | Equivalent to the refresh_token parameter that is described in the OAuth 2.0 spec.
scope | Equivalent to the scope parameter that is described in the OAuth 2.0 spec.
state | Equivalent to the state parameter that is described in the OAuth 2.0 spec.
token_type | The type of data to be returned in the response from the authorization server.

Top

Moving from OAuth WRAP to OAuth 2.0

Live Connect version 4.1 uses our implementation of OAuth Web Resource Authorization Protocol (WRAP) for user authentication and consent and for managing access tokens and refresh tokens. Live Connect version 5 deprecates OAuth WRAP in favor of our implementation of OAuth 2.0. Also, we plan to turn off access to Live Connect version 4.1 services on 25 June 2012. To move an app from using OAuth WRAP to OAuth 2.0, you'll need to know the following info:

  • If your app has a refresh token that contains one or more scopes that a user has consented to and that are specific to Live Connect version 4.1, your app can use that refresh token with Live Connect version 5 to get an access token that contains equivalent consented scopes in Live Connect version 5. This process allows your app to access a user's info in Live Connect version 5 without unnecessarily interrupting the user to provide consent again to scopes that he or she previously consented to in Live Connect version 4.1. For example, if a user previously consented to the WL_Photos.View scope in Live Connect version 4.1, and your app has a refresh token that contains this consented scope, your app can use that refresh token with Live Connect version 5 to get an access token that contains a scope with functionality equivalent to the WL_Photos.View scope. Your app can then use that access token with Live Connect version 5 to access photo albums and videos that the consenting user has uploaded, along with associated tags and comments. As long as your app has a valid refresh token that is specific to Live Connect version 4.1 and the user has not explicitly revoked consent, you can use that refresh token with Live Connect version 5—even after Live Connect version 4.1 services are turned off.
  • An app can't use Live Connect version 5 to request a user to consent to specific scopes that exist only in Live Connect version 4.1. For example, an app can't use Live Connect version 5 to ask a user to explicitly consent to the WL_Activities.Update scope, which doesn't exist in Live Connect version 5. In this example, we recommend that the app use Live Connect version 5 to ask the user to consent to the wl.share scope, which has equivalent functionality.

For more info, see Migrating your Live Connect v4.1 app to v5.0.

Top


Supported locales

Your JavaScript-based apps can use a localized version of the Live Connect JavaScript API file named wl.js. (Note that this does not apply to Windows Store apps using JavaScript, which use a copy of wl.js that is stored locally). For instructions, see the "International support" section of Using the JavaScript library.

Your apps can also display a localized version of the consent page. For JavaScript details, see the "International support" section of Using the JavaScript library. For C# details, see the tip in the "Signing a user in with C#" section of Signing users in.

Windows Live APIs support all of the culture codes listed in this table.

Note Windows Phone does not support all of the culture codes that the Windows Live APIs support. The culture codes supported by the Windows Phone are indicated by the green check ( Supported).

Culture code | Culture name | Windows Phone 8.0 | Windows Phone OS 7.1
af | Afrikaans |  |
am-et | Amharic (Ethiopia) |  |
ar | Arabic | Supported |
as-in | Assamese (India) |  |
az-latn-az | Azeri (Latin, Azerbaijan) | Supported |
be | Belarusian | Supported |
bg | Bulgarian | Supported |
bn-bd | Bangla (Bangladesh) |  |
bn-in | Bangla (India) |  |
bs-latn-ba | Bosnian (Latin, Bosnia and Herzegovina) |  |
ca | Catalan | Supported |
ca-es-valencia | Valencian (Spain) |  |
cs | Czech | Supported | Supported
cy-gb | Welsh (United Kingdom) |  |
da | Danish | Supported | Supported
de | German | Supported | Supported
el | Greek | Supported | Supported
en | English | Supported | Supported
en-GB | English (United Kingdom) | Supported | Supported
es | Spanish | Supported | Supported
et | Estonian | Supported |
eu | Basque |  |
fa | Persian | Supported |
fi | Finnish | Supported |
fil-ph | Filipino (Philippines) | Supported |
fr | French | Supported | Supported
ga-ie | Irish (Ireland) |  |
gd-latn | Scottish Gaelic |  |
gl | Galician |  |
gu | Gujarati |  |
ha-latn-ng | Hausa (Latin, Nigeria) |  |
he | Hebrew | Supported |
hi | Hindi | Supported |
hr | Croatian | Supported |
hu | Hungarian | Supported | Supported
hy | Armenian |  |
id | Indonesian | Supported | Supported
ig-ng | Igbo (Nigeria) |  |
is | Icelandic |  |
it | Italian | Supported | Supported
iu-latn-ca | Inuktitut (Latin, Canada) |  |
ja | Japanese | Supported | Supported
ka | Georgian |  |
kk | Kazakh | Supported |
km-kh | Khmer (Cambodia) |  |
kn | Kannada |  |
ko | Korean | Supported | Supported
kok | Konkani |  |
ku-arab | Central Kurdish |  |
ky | Kyrgyz |  |
lb-lu | Luxembourgish (Luxembourg) |  |
lt | Lithuanian | Supported |
lv | Latvian | Supported |
mi-nz | Maori (New Zealand) |  |
mk | Macedonian (FYROM) | Supported |
ml-in | Malayalam (India) |  |
mn | Mongolian (Cyrillic) |  |
mr | Marathi |  |
ms | Malay | Supported | Supported
mt-mt | Maltese (Malta) |  |
nb-no | Norwegian, Bokmål (Norway) | Supported | Supported
ne-np | Nepali (Nepal) |  |
nl | Dutch | Supported | Supported
nn-no | Norwegian, Nynorsk (Norway) |  |
nso-za | Sesotho sa Leboa (South Africa) |  |
or-in | Odia |  |
pa | Punjabi |  |
pa-arab | Punjabi |  |
pl | Polish | Supported | Supported
prs-af | Dari (Afghanistan) |  |
pt-br | Portuguese (Brazil) | Supported | Supported
pt-pt | Portuguese (Portugal) | Supported | Supported
qut-latn | K'iche' |  |
quz-pe | Quecha (Peru) |  |
ro | Romanian | Supported |
ru | Russian | Supported | Supported
rw | Kinyarwanda |  |
sd-arab | Sindhi |  |
si-lk | Sinhala (Sri Lanka) |  |
sk | Slovak | Supported |
sl | Slovenian | Supported |
sq | Albanian | Supported |
sr-cyrl-ba | Serbian (Cyrillic, Bosnia and Herzegovina) |  |
sr-cyrl-cs | Serbian (Cyrillic, Serbia and Montenegro (Former)) |  |
sr-latn-cs | Serbian (Latin, Serbia and Montenegro (Former)) | Supported |
sv | Swedish | Supported | Supported
sw | Kiswahili |  |
ta | Tamil |  |
te | Telugu |  |
tg-cyrl | Tajik (Cyrillic) |  |
th | Thai | Supported |
ti | Tigrinya |  |
tk-tm | Turkmen (Turkmenistan) |  |
tn-za | Setswana (South Africa) |  |
tr | Turkish | Supported |
tt | Tatar |  |
ug-arab | Uyghur |  |
uk | Ukrainian | Supported |
ur | Urdu |  |
uz-latn-uz | Uzbek (Latin, Uzbekistan) | Supported |
vi | Vietnamese | Supported |
wo | Wolof |  |
xh-za | isiXhosa (South Africa) |  |
yo-ng | Yoruba (Nigeria) |  |
zh-hans | Chinese Simplified |  |
zh-hant | Chinese Traditional |  |
zu-za | isiZulu (South Africa) |  |

Related topics

Culture and Language Support for the Windows Phone
Globalization and Localization for Windows Phone


Identity API

Learn how to use the Live Connect APIs to identify users and to use what you know about them to create a personalized app experience.

The more info you have about a user, the better you can customize that user's experience. By identifying the user and personalizing his or her experience, you can influence users to return to your app regularly.

In this section

Topic | Description
Greeting the user | Call the Live Connect APIs to greet users by name and display the users' profile picture.
Streamlining account registration | Use the Live Connect APIs to streamline the account registration process for your app.
Contacting users | Use the Live Connect APIs to get contact info for a user.
Determining a user's age | Determine a user's age by calling the Live Connect APIs.


Greeting the user

This topic describes and demonstrates how to use the Live Connect APIs to greet a user by name and how to display the user's profile picture.

Greeting a user by name when he or she visits your app is a simple but effective way of building a stronger connection between the user and your app. This connection can help you influence users to return to your app.

This topic describes how to display the users name and display their profile picture in these languages. The code examples assume that your app initialized the APIs, the user signed in, and he or she consented to the wl.basic scope, which enables access to get the user's name. For more info about these initial steps, see Signing users in and Obtaining user consent.

  • Get the user's name and profile picture in JavaScript for Windows Store apps and HTML
  • Get the user's name and profile picture in C# for Windows Store apps and Windows Phone apps
  • Get the user's name and profile picture in Objective-C for iOS
  • Get the user's name and profile picture in Java for Android
  • Get the user's name and profile picture using REST
  • Next steps

To make full use of the code examples in this topic, you can use them in the context of larger code reference samples that we provide in Working with the code examples.

Get the user's name and profile picture in JavaScript for Windows Store apps and HTML

Here's how to display the user's name.

JavaScript
function greetUser_onClick() {
    WL.login({
        scope: "wl.basic"
    }).then(
        function (response)
        {
            WL.api({
                path: "me",
                method: "GET"
            }).then(
                function (response){
                    document.getElementById("infoArea").innerText =
                        "Hello, " + response.first_name + " " +
                        response.last_name + "!";
                },
                function (responseFailed){
                    document.getElementById("infoArea").innerText =
                        "Error calling API: " + responseFailed.error.message;
                }
            );
        },
        function (responseFailed){
            document.getElementById("infoArea").innerText =
                "Error signing in: " + responseFailed.error_description;
        }
    );
}

The code calls the WL.api function. If the call is successful, and a textarea control exists with the name infoArea, the code changes the control's text to display a message with the signed-in user's first and last name. The code gets this info from response.first_name and response.last_name.

Here's how to display the user's profile picture.

JavaScript
function getImage_onClick() {
    WL.login({
        scope: "wl.basic"
    }).then(
        function (response)
        {
            WL.api({
                path: "me/picture",
                method: "GET"
            }).then(
                function (response) {
                    if (response.location) {
                        imgTagString = "<img src='" + response.location + "' />";
                        document.getElementById("userImage").innerHTML = imgTagString;
                    }
                },
                function (responseFailed) {
                    document.getElementById("infoArea").innerText =
                        "Error calling API: " + responseFailed.error.message;
                }
            );
        },
        function (responseFailed) {
            document.getElementById("infoArea").innerText =
                "Error signing in: " + responseFailed.error_description;
        }
     );
}

The code uses the WL.login function to sign the user in with the wl.basic scope. If the sign-in is successful, and an img control with the name userImage exists, the code sets the src attribute of the userImage control to a GET call to the signed-in user's profile picture.

Top

Get the user's name and profile picture in C# for Windows Store apps and Windows Phone apps

Here's how to display the user's name.

C#
private async void btnGreetUser_Click(object sender, RoutedEventArgs e)
{
    try
    {
        LiveAuthClient auth = new LiveAuthClient();
        LiveLoginResult initializeResult = await auth.InitializeAsync();
        try
        {
            LiveLoginResult loginResult = await auth.LoginAsync(new string[] { "wl.basic" });
            if (loginResult.Status == LiveConnectSessionStatus.Connected)
            {
                LiveConnectClient connect = new LiveConnectClient(auth.Session);
                LiveOperationResult operationResult = await connect.GetAsync("me");
                dynamic result = operationResult.Result;
                if (result != null)
                {
                    this.infoTextBlock.Text = string.Join(" ", "Hello", result.name, "!");
                }
                else
                {
                    this.infoTextBlock.Text = "Error getting name.";
                }
            }
        }
        catch (LiveAuthException exception)
        {
            this.infoTextBlock.Text = "Error signing in: " + exception.Message;
        }
        catch (LiveConnectException exception)
        {
            this.infoTextBlock.Text = "Error calling API: " + exception.Message;
        }
    }
    catch (LiveAuthException exception)
    {
        this.infoTextBlock.Text = "Error initializing: " + exception.Message;
    }
}

In the custom btnGreetUser_Click event handler method, the code calls the GetAsync method from the instance of LiveConnectClient. If the call is successful, the code displays a message that contains the signed-in user's name. The code gets the signed-in user's name from the Result property of the LiveOperationResult instance. The Result property contains a representation of the JavaScript Object Notation (JSON)-formatted info.

Here's how to display the user's profile picture.

C#
private async void btnDisplayProfile_Click(object sender, RoutedEventArgs e)
{
    try
    {
        LiveConnectClient liveClient = new LiveConnectClient(this.session);
        LiveOperationResult operationResult = await liveClient.GetAsync("me/picture");
        dynamic result = operationResult.Result;
        BitmapImage image = new BitmapImage(new Uri(result.location, UriKind.Absolute));
        this.imgResult.Source = image;
    }
    catch (LiveConnectException exception)
    {
        this.infoTextBlock.Text = "Error getting user picture: " + exception.Message;
    }
}

The code does this:

  1. The GetAsync method of the LiveConnectClient instance calls me/picture to get info about the user's profile picture.
  2. If the call succeeds, the Result property of the LiveOperationResult instance contains info about the user's profile picture as a JSON-formatted object.
  3. In this JSON-formatted object, the location structure contains a link to the user's profile picture.

Top

Get the user's name and profile picture in Objective-C for iOS

Here's how to display the user's name and profile picture.

ObjectiveC
- (void) getMe
{
    if (self.liveClient) {
        [self.liveClient getWithPath:@"me"
                            delegate:self
                           userState:@"me"];
        [self.liveClient getWithPath:@"me/picture"
                            delegate:self
                           userState:@"me-picture"];
    }
}

- (void) liveOperationSucceeded:(LiveOperation *)operation
{
    if ([operation.userState isEqual:@"me"]) {
        self.nameLabel.text = [operation.result objectForKey:@"name"];
        self.genderLabel.text = [operation.result objectForKey:@"gender"];
        self.profileLinkLabel.text = [operation.result objectForKey:@"link"];
    }
    if ([operation.userState isEqual:@"me-picture"]) {
        NSString *location = [operation.result objectForKey:@"location"];
        if (location) {
            NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:location]];
            self.profilePictureView.image = [UIImage imageWithData:data];
        }
    }
}

In this example, the getWithPath:delegate:userState method of the LiveConnectClient variable calls the Live Connect APIs to get info about the signed-in user. If the call is successful, this example code is part of a larger interface that implements the LiveOperationDelegate interface and so its liveOperationSucceeded method is called; otherwise, if the call by userState is unsuccessful, the example's liveOperationFailed:operation method is called. Note that the userState parameter, when set to @"me" or @"me-picture", is used to find the correct logic to call to get the user's name, gender, and profile link, and to get the user's profile picture, and to display them in the correct controls.

Top

Get the user's name and profile picture in Java for Android

Here's how to display the user's name.

Java
public void greetUser() {
    client.getAsync("me", new LiveOperationListener() {
        public void onComplete(LiveOperation operation) {
            JSONObject result = operation.getResult();
            resultTextView.setText("Hello, " + result.optString("name") + "!");
        }
        public void onError(LiveOperationException exception, LiveOperation operation) {
            resultTextView.setText("Error getting name: " + exception.getMessage());
        }
    });
}

In the onClick event handler method, the code calls the getAsync method from the instance of LiveConnectClient. If the call is successful, the code displays a message that contains the signed-in user's first and last name. The code gets the user's first and last name from the getResult method of the LiveOperation argument instance. The getResult method call gets a representation of the JSON-formatted info.

Here's how to display the user's profile picture.

Java
public void getUserImage() {
    client.getAsync("me/picture", new LiveOperationListener() {
        public void onComplete(LiveOperation operation)
        {
            JSONObject result = operation.getResult();
            String link = result.optString("location");
            showImage(link);
        }
        public void onError(LiveOperationException exception, LiveOperation operation)
        {
            resultTextView.setText("Error getting user's profile picture: " + exception.getMessage());
        }
    });
}

private void showImage(String url)
{
    client.downloadAsync(url, new LiveDownloadOperationListener() {
        public void onDownloadCompleted(LiveDownloadOperation operation)
        {
            InputStream input =  operation.getStream();
            try {
                Bitmap bMap = BitmapFactory.decodeStream(input);
                picture.setImageBitmap(bMap);
            }
            finally {
                try {
                    input.close();
                }
                catch (IOException e) {
                }
            }
        }
        public void onDownloadFailed(LiveOperationException exception, LiveDownloadOperation operation)
        {
            resultTextView.setText("Error getting user's profile picture: " + exception.getMessage());
        }
        public void onDownloadProgress(int totalBytes, int bytesRemaining, LiveDownloadOperation operation)
        {
            resultTextView.setText("Downloading user's profile picture... " + bytesRemaining + " bytes downloaded " +
                    "(" + (bytesRemaining / totalBytes) * 100 + "%)");
        }
    });
}

The code does this:

  1. The getAsync method of the LiveConnectClient instance calls me/picture to get the user's profile picture.
  2. If the call to get the user's profile picture succeeds, the getResult method of the onComplete method's operation parameter gets info about the user's picture as a JSON-formatted object.
  3. The custom showImage method then uses the location structure in the JSON-formatted object to get the user's profile picture and then show it in a picture viewer control.

Top

Get the user's name and profile picture using REST

To get the user's name, after you make the appropriate GET call in Representational State Transfer (REST), the user's first and last names are in the response. Here's how to make a GET call, where me represents the signed-in user.

GET https://apis.live.net/v5.0/me?access_token=ACCESS_TOKEN

And here's how to get the user's profile picture, where me represents the signed-in user.

GET https://apis.live.net/v5.0/me/picture?access_token=ACCESS_TOKEN

Top

Next steps

You now have an app that can greet a user by name and display his or her profile picture. Learn more about:

  • Streamlining account registration
  • Contacting users
  • Determining a user's age

Top


Streamlining account registration

This topic describes how your app can get a user's consent to access his or her info—specifically, the user's first name, last name, email address, gender, and birthday.

Most users don't like to enter their personal info in multiple apps, especially if it requires them to create an app-specific account. If your app needs to create an account for a user, you can use the Live Connect APIs to streamline your account registration process by using the info that the user has already stored in their Microsoft account, such as an email address, which your app can access by using the Live Connect APIs. This can make creating an app-specific account as simple for the user as clicking a link and typing his or her Microsoft account credentials.

The examples on this page illustrate how to get the users info from their Microsoft account by using the Live Connect APIs. The code examples in this topic assume that your app has initialized the APIs, the user has signed in, and he or she has consented to the wl.basic scope, which allows your app to get the user's name and gender, the wl.emails scope, which allows your app to get the user's email address, and the wl.birthday scope, which allows your app to get the user's birthday info. For more info about these initial steps, see Signing users in and Obtaining user consent.

  • Getting and working with user info in JavaScript for Windows Store apps and HTML
  • Getting and working with user info in C# for Windows Store apps and Windows Phone apps
  • Getting and working with user info in Objective-C for iOS
  • Getting and working with user info in Java for Android
  • Getting and working with user info using REST
  • Next steps

In these examples, the GET calls request info about me, which is a reserved word that returns info from the signed-in user's profile. After the Live Connect APIs return the data to your app, your app can insert the user's info into UI controls. This is demonstrated in some of these examples.

To make full use of the code examples in this topic, you can use them in the context of larger code reference samples that we provide in Working with the code examples.

Getting and working with user info in JavaScript for Windows Store apps and HTML

In this example, response.structure_name is used to get the info in the corresponding structure. For example, response.first_name returns the user's first name. Also, note that you can access response.emails.preferred to get info from the preferred structure.

JavaScript
function streamlineAccountReg_onClick() {
    WL.login({
        scope: ["wl.signin", "wl.basic", "wl.birthday", "wl.emails"]
    }).then(
        function (response) {
            WL.api({
                path: "me",
                method: "GET"
            }).then(
                function (response) {
                    document.getElementById("first_name").innerText = response.first_name;
                    document.getElementById("last_name").innerText = response.last_name;
                    document.getElementById("email").innerText = response.emails.preferred;
                    document.getElementById("gender").innerText = response.gender;
                    document.getElementById("birthday").innerText =
                        response.birth_month + " " + response.birth_day + " " + response.birth_year;
                },
                function (responseFailed) {
                    document.getElementById("infoArea").innerText =
                        "Error calling API: " + responseFailed.error.message;
                }
            );
        },
        function (responseFailed)
        {
            document.getElementById("infoArea").innerText =
                "Error signing in: " + responseFailed.error_description;
        }
    );
}

Getting and working with user info in C# for Windows Store apps and Windows Phone apps

C#
private async void btnFillRegistration_Click(object sender, RoutedEventArgs e)
{
    try
    {
        LiveConnectClient liveClient = new LiveConnectClient(this.session);
        LiveOperationResult operationResult = await liveClient.GetAsync("me");
        dynamic result = operationResult.Result;
        firstNameTextBlock.Text = result.first_name;
        lastNameTextBlock.Text = result.last_name;
        emailTextBlock.Text = result.emails.preferred;
        genderTextBlock.Text = result.gender;
        birthdayTextBlock.Text = string.Join("/", result.birth_month, result.birth_day, result.birth_year);
    }
    catch (LiveConnectException exception)
    {
        this.infoTextBlock.Text = "Error getting user info: " + exception.Message;
    }
}

Getting and working with user info in Objective-C for iOS

ObjectiveC
-(void) streamlineAccountRegistration
{
    [self.liveClient getWithPath:@"me"
                        delegate:self];
}

- (void) liveOperationSucceeded: (LiveOperation *)operation
{
    NSDictionary *emails = [operation.result objectForKey:@"emails"];
    NSString *preferred = [emails objectForKey:@"preferred"];
    NSString *birth_month = [operation.result objectForKey:@"birth_month"];
    NSString *birth_day = [operation.result objectForKey:@"birth_day"];
    NSString *birth_year = [operation.result objectForKey:@"birth_year"];
    [self.firstNameLabel setText:[NSString stringWithFormat: @"%@", [operation.result objectForKey:@"first_name"]]];
    [self.lastNameLabel setText:[NSString stringWithFormat: @"%@", [operation.result objectForKey:@"last_name"]]];
    [self.emailLabel setText:[NSString stringWithFormat: @"%@", preferred]];
    [self.genderLabel setText:[NSString stringWithFormat: @"%@", [operation.result objectForKey:@"gender"]]];
    [self.birthdayLabel setText:[NSString stringWithFormat: @"%@ %@ %@", birth_day, birth_month, birth_year]];
}

Getting and working with user info in Java for Android

Java
public void streamlineAccountRegistration() {
    client.getAsync("me", new LiveOperationListener() {
        public void onError(LiveOperationException exception, LiveOperation operation) {
            resultTextView.setText("Error getting user info: " + exception.getMessage());
        }
        public void onComplete(LiveOperation operation) {
            JSONObject result = operation.getResult();
            fillUserForm(result);
        }
    });
}

private void fillUserForm(JSONObject user) {
    String firstName = user.optString("first_name");
    String lastName = user.optString("last_name");
    JSONObject emails = user.optJSONObject("emails");
    String email = "";
       if (emails != null) {
        email = emails.optString("preferred");
       }
    resultTextView.setText("First name = " + firstName + "\n" +
        "Last name = " + lastName + "\n" +
        "Preferred email = " + email);
}

Getting and working with user info using REST

After you make the appropriate GET call in REST, the user's info is in the response. Here's how to make a GET call, where the signed-in user is represented as me and ACCESS_TOKEN is replaced by the actual access token string returned when the user signed-in.

GET https://apis.live.net/v5.0/me?access_token=ACCESS_TOKEN

The Live Connect APIs return data to your app as a JavaScript Object Notation (JSON) object, which contains structures that correspond to the scopes that you requested for your app.

Here's an example of a JSON object returned by a REST call to a Live Connect API.

{
    "first_name" : "Luka",
    "last_name" : "Abrus",
    "emails : {
        "preferred": "luka.abrus@fabrikam.com"
    },
    "birth_month" : 6,
    "birth_date" : 26,
    "birth_year" : 1973
}

Next steps

This topic shows how to streamline app-specific account registration by using the Live Connect APIs. Learn more about:

  • Greeting the user
  • Contacting users
  • Determining a user's age

Top


Contacting users

This topic describes and demonstrates how to get a user's contact info, and display the contact info in a set of UI controls.

Users can store their contact info in Live services. By using the Live Connect APIs, your app can use this info to contact a user by email, by mail, or by phone.

The code examples in this topic describe how to get the user's contact info in the languages that the Live Connect APIs. They also assume that your app has initialized the APIs successfully, the user has signed in successfully, and he or she has consented to these scopes:

  • wl.basic, to get the user's name
  • wl.emails, to get the user's email address
  • wl.postal_addresses, to get the user's postal address info
  • wl.phone_numbers, to get the user's phone number info

For details about these initialization steps, see Signing users in and Obtaining user consent.

  • Getting and working with user contact info in JavaScript for Windows Store apps and HTML
  • Getting and working with user contact info in C# for Windows Store apps and C# for Windows Phone apps
  • Getting and working with user contact info in Objective-C for iOS
  • Getting and working with user contact info in Java for Android
  • Getting and working with user contact info using REST
  • Next steps

Note The Live Connect APIs return null for any object or structure that does not have a value. We recommend that your app check for null values before it uses a returned value, especially if you're using C#.

To make full use of the code examples in this topic, you can use them in the context of larger code reference samples that we provide in Working with the code examples.

Getting and working with user contact info in JavaScript for Windows Store apps and HTML

In this code, the WL.api function requests info about me, which returns the signed-in user's profile info.

After the Live Connect APIs return the data to your app, the response function in the WL.api method call inserts the user's info into UI controls.

JavaScript
function contactingUsers_onClick() {
    WL.login({
        scope: ["wl.signin", "wl.basic", "wl.postal_addresses", "wl.phone_numbers", "wl.emails"]
    }).then(
        function (response) {
            WL.api({
                path: "me",
                method: "GET"
            }).then(
                function (response) {
                    document.getElementById("first_name").innerText = response.first_name;
                    document.getElementById("last_name").innerText = response.last_name;
                    document.getElementById("email").innerText = response.emails.preferred;
                    document.getElementById("address").innerText = response.addresses.personal.street + " " +
                        response.addresses.personal.city + " " +
                        response.addresses.personal.state + " " +
                        response.addresses.personal.postal_code + " " +
                        response.addresses.personal.region
                    document.getElementById("phone").innerText = response.phones.personal;
                },
                function (responseFailed) {
                    document.getElementById("infoArea").innerText =
                        "Error calling API: " + responseFailed.error.message;
                }
            );
        },
        function (responseFailed)
        {
            document.getElementById("infoArea").innerText =
                "Error signing in: " + responseFailed.error_description;
        }
    );
}

In this code, response.structure_name in JavaScript is used to get the info from the corresponding structure. For example, response.first_name returns the first name of the signed-in user. Also, note that in JavaScript, response.addresses.personal.postal_code accesses info in the postal_code structure.

Getting and working with user contact info in C# for Windows Store apps and C# for Windows Phone apps

C#
private async void btnContact_Click(object sender, RoutedEventArgs e)
{
    try
    {
        LiveConnectClient liveClient = new LiveConnectClient(this.session);
        LiveOperationResult operationResult = await liveClient.GetAsync("me");
        dynamic result = operationResult.Result;
        firstNameTextBlock.Text = result.first_name;
        lastNameTextBlock.Text = result.last_name;
        emailTextBlock.Text = result.emails.preferred;
        genderTextBlock.Text = result.gender;
        birthdayTextBlock.Text = string.Join(" ", result.birth_month, result.birth_day, result.birth_year);
        addressTextBlock.Text = string.Join(" ",
            result.addresses.personal.street,
            result.addresses.personal.city,
            result.addresses.personal.state,
            result.addresses.personal.postal_code,
            result.addresses.personal.region);
        phoneTextBlock.Text = result.phones.personal;
    }
    catch (LiveConnectException exception)
    {
        this.infoTextBlock.Text = "Error getting user info: " + exception.Message;
    }
}

In this code, the LiveConnectClient.GetAsync method makes a request to me, which returns the signed-in user's contact info.

Getting and working with user contact info in Objective-C for iOS

In this code example, LiveConnectClient getWithPath:delegate requests info about me, which returns the signed-in user's contact info. Then, liveOperationSucceeded:operation displays the user's contact info.

ObjectiveC
-(void) contactUser
{
    [self.liveClient getWithPath:@"me"
                        delegate:self];
}

- (void) liveOperationSucceeded: (LiveOperation *)operation
{
    NSDictionary *emails = [operation.result objectForKey:@"emails"];
    NSString *preferred = [emails objectForKey:@"preferred"];
    NSDictionary *addresses = [operation.result objectForKey:@"addresses"];
    NSDictionary *personalAddress = [addresses objectForKey:@"personal"];
    NSString *street = [personalAddress objectForKey:@"street"];
    NSString *city = [personalAddress objectForKey:@"city"];
    NSString *state = [personalAddress objectForKey:@"state"];
    NSString *postal_code = [personalAddress objectForKey:@"postal_code"];
    NSString *region = [personalAddress objectForKey:@"region"];
    NSDictionary *phones = [operation.result objectForKey:@"phones"];
    NSString *personalPhone = [phones objectForKey:@"personal"];
    [self.firstNameLabel setText:[NSString stringWithFormat: @"%@", [operation.result objectForKey:@"first_name"]]];
    [self.lastNameLabel setText:[NSString stringWithFormat: @"%@", [operation.result objectForKey:@"last_name"]]];
    [self.emailLabel setText:[NSString stringWithFormat: @"%@", preferred]];
    [self.addressLabel setText:[NSString stringWithFormat: @"%@ %@ %@ %@ %@", street, city, state, postal_code, region]];
    [self.phoneNumberLabel setText:[NSString stringWithFormat: @"%@", personalPhone]];
}

Getting and working with user contact info in Java for Android

In this code example, LiveConnectClient.getAsync requests info about me, which returns the signed-in user's contact info. Then, the custom fillUserContactForm method displays the user's contact info.

Java
public void contactUser() {
    client.getAsync("me", new LiveOperationListener() {
        public void onError(LiveOperationException exception, LiveOperation operation) {
            resultTextView.setText("Error getting user info: " + exception.getMessage());
        }
        public void onComplete(LiveOperation operation) {
            JSONObject result = operation.getResult();
            fillUserContactForm(result);
        }
    });
}

private void fillUserContactForm(JSONObject user) {
    String firstName = user.optString("first_name");
       String lastName = user.optString("last_name");
    JSONObject emails = user.optJSONObject("emails");
    String email = "";
       if (emails != null){
           email = emails.optString("preferred");
       }
    JSONObject addresses = user.optJSONObject("addresses");
    String address = "";
       if (addresses != null) {
           JSONObject personalAddr = addresses.optJSONObject("personal");
           if (personalAddr != null) {
               address = personalAddr.optString("street") + " " +
                personalAddr.optString("city") + " " +
                   personalAddr.optString("state") + " " +
                personalAddr.optString("postal_code") + " " +
                personalAddr.optString("region");
           }
       }
       JSONObject phones = user.optJSONObject("phones");
       String phone = "";
       if (phones != null) {
        phone = phones.optString("personal");
       }
       resultTextView.setText("First name = " + firstName + "\n" +
        "Last name = " + lastName + "\n" +
        "Preferred email = " + email + "\n" +
        "Address = " + address + "\n" +
        "Personal phone = " + phone);
}

Getting and working with user contact info using REST

After you make the appropriate GET call in Representational State Transfer (REST), the user's info is in the response. The response is returned in JavaScript Object Notation (JSON) format, which you can parse to get the individual structures that are stored within.

Here's how to make a GET call where the signed-in user is represented as me and where ACCESS_TOKEN is the actual access token.

GET https://apis.live.net/v5.0/me?access_token=ACCESS_TOKEN

Objects such as postal_addresses, emails, and phone_numbers contain structures. In addition, the emails object contains multiple structures that correspond to the different email addresses that a user might have in his or her Live Connect profile info. These e-mail accounts include: preferred, personal, and business. Here are some email addresses, postal addresses, and phone numbers for a user that could be returned by the Live Connect APIs in JSON format.

{
    ...
    "emails": {
        "preferred": "lukas.abrus@fabrikam.com",
        "account": "lukas.abrus.account@fabrikam.com",
        "personal": "lukas.abrus.personal@fabrikam.com",
        "business": "lukas.abrus.business@fabrikam.com"
    },
    "addresses": {
        "personal": {
            "street": "1235 Main St",
            "street_2": null,
            "city": "Buffalo",
            "postal_code": "98074",
            "state": "NY",
            "region": "USA"
        },
        "business": {
            "street": "One Fabrikam Place",
            "street_2": "Unit 5",
            "city": "Buffalo",
            "postal_code": "98074",
            "state": "WA",
            "region": "USA"
        }
    },
    "phones": {
        "personal": "(425)555-0101",
        "business": "(425)555-0155",
        "mobile": "(425)555-0167"
    }
    ...
}

The REST reference topic includes more info about the elements of the emails, phones, and addresses objects.

Next steps

This topic demonstrates how to use the wl.postal_addresses, wl.email_addresses, and wl.phone_numbers scopes to get a user's contact info. Learn more about:

  • Greeting the user
  • Streamlining account registration
  • Determining a user's age

Top


Determining a user's age

This topic describes and demonstrates how to get a user's age, if he or she chose to store this info in Live services. The example provided here, disables a purchase control until the app can verify that the signed-in user is at least 18 years old.

When your apps interact with users, some info is critical to ensuring the right user experience, such as knowing the user's age. This is especially true if your apps allow actions such as in-app purchases of age-restricted media.

This topic assumes that your app has already initialized the Live Connect APIs, the user has signed in, and he or she has consented to the wl.birthday scope, which grants access to the user's birthday info. For details about these initial steps, see Signing users in and Obtaining user consent.

  • Working with the user's age in JavaScript for Windows Store apps and HTML
  • Working with the user's age in C# for Windows Store apps and Windows Phone apps
  • Working with the user's age in Objective-C for iOS
  • Working with the user's age in Java for Android
  • Working with the user's age using REST
  • Next steps

To make full use of the code examples in this topic, you can use them in the context of larger code reference samples that we provide in Working with the code examples.

Working with the user's age in JavaScript for Windows Store apps and HTML

In this code example, the WL.api function requests info for me, which returns the signed-in user's profile info.

After WL.api returns, response.birth_year contains the birth year the user stored in their profile, which the code uses to compute the user's age.

JavaScript
function userAge_onClick() {
    WL.login({
        scope: ["wl.signin", "wl.birthday"]
    }).then(
        function (response) {
            WL.api({
                path: "me",
                method: "GET"
            }).then(
                function (response) {
                    if (response.birth_year) {
                        var date = new Date();
                        var year = date.getFullYear();
                        var age = year - response.birth_year;
                        if (age >= 18) {
                            document.getElementById("purchaseButton").disabled = "";
                            document.getElementById("infoArea").innerText =
                                "Age is 18 or older. Purchase button enabled.";
                        }
                        else {
                            document.getElementById("purchaseButton").disabled = "disabled";
                            document.getElementById("infoArea").innerText =
                                "Age is under 18. Purchase button disabled.";
                        }
                    }
                    else {
                        document.getElementById("purchaseButton").disabled = "disabled";
                        document.getElementById("infoArea").innerText =
                            "Cannot determine age. Purchase button disabled.";
                    }
                },
                function (responseFailed) {
                    document.getElementById("infoArea").innerText =
                        "Error calling API: " + responseFailed.error.message;
                }
            );
        },
        function (responseFailed) {
            document.getElementById("infoArea").innerText =
                "Error signing in: " + responseFailed.error_description;
        }
    );
}

function purchaseButton_onClick() {
    document.getElementById("infoArea").innerText =
        "Purchase button clicked.";
}

Top

Working with the user's age in C# for Windows Store apps and Windows Phone apps

In this code example, the LiveConnectClient.GetAsync method request's info for me, which returns the signed-in user's profile info. The user's age is computed from the birth year in the returned info.

C#
private async void btnAge_Click(object sender, RoutedEventArgs e)
{
    try
    {
        LiveConnectClient liveClient = new LiveConnectClient(this.session);
        LiveOperationResult operationResult = await liveClient.GetAsync("me");
        dynamic result = operationResult.Result;
        if (result.birth_year != null)
        {
            DateTime date = DateTime.Now;
            int year = date.Year;
            int age = year - (int)result.birth_year;
            if (age >= 18)
            {
                infoTextBlock.Text = "Age is 18 or older. Purchase button enabled.";
                btnPurchase.IsEnabled = true;
            }
            else
            {
                infoTextBlock.Text = "Age is under 18. Purchase button disabled.";
            }
        }
        else
        {
            infoTextBlock.Text = "Could not determine birth year. Purchase button disabled.";
        }

    }
    catch (LiveConnectException exception)
    {
        infoTextBlock.Text = "Error getting user info: " + exception.Message;
    }
}

private void btnPurchase_Click(object sender, RoutedEventArgs e)
{
    infoTextBlock.Text = "Purchase button clicked.";
}

Top

Working with the user's age in Objective-C for iOS

In this code example, the LiveConnectClient getWithPath:delegate method requests info for me, which returns the signed-in user's profile info. Then the liveOperationSucceeded:operation method computes the user's age from the birth year in the returned info to determine whether the purchase button should be enabled.

ObjectiveC
- (void) getAge
{
    [self.liveClient getWithPath:@"me"
                        delegate:self];
}

- (void) liveOperationSucceeded:(LiveOperation *)operation
{
    NSDate *currentDate = [NSDate date];
    NSCalendar* calendar = [NSCalendar currentCalendar];
    NSDateComponents* dateComponents = [calendar components:NSYearCalendarUnit
                                                   fromDate:currentDate];
    NSInteger currentYear = [dateComponents year];
    NSInteger usersBirthYear = (int)[operation.result objectForKey:@"birth_year"];
    NSInteger age = currentYear - usersBirthYear;
    if (age >= 18)
    {
        self.purchaseButton.enabled = YES;
    }
    else
    {
        self.purchaseButton.enabled = NO;
    }
}

Top

Working with the user's age in Java for Android

In this code example, the LiveConnectClient.getAsync method requests info for me, which returns the signed-in user's profile info. Then the custom updateRestrictedButton method computes the user's age from the birth year in the returned info to determine whether the purchase button should be enabled.

Java
public void getUserAge() {
    client.getAsync("me", new LiveOperationListener() {
        public void onError(LiveOperationException exception, LiveOperation operation) {
            resultTextView.setText("Error getting user info: " + exception.getMessage());
        }
        public void onComplete(LiveOperation operation) {
            JSONObject result = operation.getResult();
            updateRestrictedButton(result);
        }
    });
}

private void updateRestrictedButton(JSONObject user) {
    boolean enable = false;
    if (user != null) {
        int birthYear = user.optInt("birth_year");
        if (birthYear > 0) {
            int year = new Date().getYear();
            int age = year - birthYear;
            if (age >= 18) {
                enable = true;
            }
        }
    }
    if (enable == true) {
        resultTextView.setText("Purchase button enabled.");
    }
    else {
        resultTextView.setText("Purchase button disabled.");
    }
}

Top

Working with the user's age using REST

After you make the appropriate GET call in Representational State Transfer (REST), the user's info is in the response. The response is returned in JavaScript Object Notation (JSON) format, which you can parse to get the individual structures within. Here's how to make a GET call where the signed-in user is represented as me.

GET https://apis.live.net/v5.0/me?access_token=ACCESS_TOKEN

Here's what the JSON-formatted info that is returned for a user might look like.

{
  "first_name" : "Luka",
  "last_name" : "Abrus",
  "birth_month" : 6,
  "birth_date" : 26,
  "birth_year" : 1968
}

Top

Next steps

This topic demonstrates how to use the wl.birthday scope to get a user's birth year and determine whether the user is old enough to make a certain type of purchase through your app. From here, you can learn how to work with additional user info by going to Greeting the user, Streamlining account registration, and Contacting users.

Top


Hotmail API

Important

If you are a Hotmail customer who needs help with your Hotmail account, go to Microsoft Answers—Hotmail, Windows Live Messenger & Microsoft SkyDrive or your Account overview.

This topic is for software developers and does not describe how to resolve problems with your Hotmail account. Help requests entered in this topic's Did you find this helpful dialog box will not be answered.

Try out code samples

This topic describes how to use the Live Connect APIs to work with a Hotmail user's contacts and calendars.

In this section

Topic | Description
Reading and writing contacts | Use the Live Connect APIs to create and read a Hotmail user's contacts.
Interacting with calendars | Use the Live Connect APIs to create, read, update, and delete a Hotmail user's calendars.
Linking to and embedding calendars | This topic describes how to add an Add to Calendar link or button to a web page and also, how to embed a Hotmail calendar in a web page.
Find people in a user's contact list | Use the Live Connect APIs to determine whether any contacts of a visiting user are also registered users of your website.


Reading and writing a user's Hotmail contacts

Important

If you are a Hotmail customer who needs help with your Hotmail account, go to Microsoft Answers—Hotmail, Windows Live Messenger & Microsoft SkyDrive or your Account overview.

This topic is for software developers and does not describe how to resolve problems with your Hotmail account. Help requests entered in this topic's Did you find this helpful dialog box will not be answered.

This topic describes how your apps can use the Live Connect APIs to create and read a Hotmail user's contacts in these languages.

  • JavaScript for Windows Store apps and HTML
  • C# for Windows Store apps and Windows Phone apps
  • Objective-C for iOS
  • Java for Android
  • REST API

To read a user's contacts, the wl.basic scope must been granted by the user and to add a new contact to a user's contacts list, the wl.contacts_create scope is required. For info about requesting the required scope from your app, see Obtaining user consent.

To fully leverage the code examples in this topic, you can use them in the context of larger code reference samples that we provide in Working with the code examples.

Specifying a contact ID

The contact ID shown in these code examples is fictitious and won't work in your app. In your app, you'll need use a valid contact ID. Here are some examples of contact IDs that can be used in the path parameter.

  • The contact ID of a contact.
  • You can get info about the currently signed-in user's contacts and friends by specifying me as the user id as in:
    • me/contacts, to get info about all of the signed-in user's contacts.
    • me/friends, to get info about all of the signed-in user's friends.

      Note A friend is another Hotmail user that a user has invited to be a friend and that has accepted the friend request. A friend is a contact that has its is_friend structure set to true. (You can't set the is_friend structure programmatically.)

  • If you have the user ID of someone, you can get info about their contacts and friends by using their user ID in place of USER_ID as shown in these examples.
    • USER_ID/contacts, to get info about all of the contact entries for the user represented by USER_ID.
    • USER_ID/friends, to get info about all of the friend entries for the user represented by USER_ID.

You can also use the contact ID argument to filter the results returned in a collection. For example:

  • Get a limited number of contact or friend entries by using the limit parameter in the preceding code to specify the number of entries to get. For example, to get the first two contact entries for the signed-in user, use me/contacts?limit=2.
  • Specify the first contact or friend entry to get by setting the offset parameter in the preceding code to the index of the first entry that you want to get. For example, to get two contact entries for the signed-in user, starting at the third contact entry, use me/contacts?limit=2&offset=3.

    Note In the JavaScript Object Notation (JSON)-formatted object that's returned, you can look in the paging object for the previous and next structures to get the offset and limit parameter values of the previous and next entries.

Reading and writing contacts in JavaScript for Windows Store apps and HTML

Reading contacts in JavaScript

Note This code example uses a fictitious contact ID in the path argument. You'll need to replace the value in the example with a valid contact ID.

JavaScript
function readContact_onClick() {
    WL.login({
        scope: "wl.contacts"
    }).then(
        function (response) {
            WL.api({
                path: "contact.83960a61000000000000000000000000",
                method: "GET"
            }).then(
                function (response) {
                    document.getElementById("resultDiv").innerHTML =
                        "ID: " + response.id +
                        "<br/>Name: " + response.first_name +
                        " " + response.last_name;
                },
                function (responseFailed) {
                    document.getElementById("infoArea").innerText =
                        "Error calling API: " + responseFailed.error.message;
                }
            );
        },
        function (responseFailed) {
            document.getElementById("infoArea").innerText =
                "Error signing in: " + responseFailed.error_description;
        }
    );
}

Writing contacts in JavaScript

JavaScript
function createContact_onClick() {
    WL.login({
        scope: "wl.contacts_create"
    }).then(
        function (response) {
            WL.api({
                path: "me/contacts",
                method: "POST",
                body: {
                    first_name: "William",
                    last_name: "Flash"
                }
            }).then(
                function (response) {
                    document.getElementById("resultDiv").innerHTML =
                        "ID: " + response.id +
                        "<br/> Name: " + response.first_name +
                        " " + response.last_name;
                },
                function (responseFailed) {
                    document.getElementById("infoArea").innerText =
                        "Error calling API: " + responseFailed.error.message;
                }
            );
        },
        function (responseFailed) {
            document.getElementById("infoArea").innerText =
                "Error signing in: " + responseFailed.error_description;
        }
    );
}

Top

Reading and writing contacts in C# for Windows Store apps and Windows Phone apps

Reading contacts in C#

Note This code example uses a fictitious contact ID in the GetAsync call. You'll need to replace the value in the example with a valid contact ID.

C#
private async void btnReadContact_Click(object sender, RoutedEventArgs e)
{
    try
    {
        LiveConnectClient liveClient = new LiveConnectClient(this.session);
        LiveOperationResult operationResult =
            await liveClient.GetAsync("contact.b4466224b2ca42798c3d4ea90c75aa56");
        dynamic result = operationResult.Result;
        this.infoTextBlock.Text = "Contact: " + result.name;
    }
    catch (LiveConnectException exception)
    {
        this.infoTextBlock.Text = "Error getting contact info: " + exception.Message;
    }
}

Writing contacts in C#

C#
private async void btnCreateContact_Click(object sender, RoutedEventArgs e)
{
    try
    {
        var contact = new Dictionary<string, object>();
        contact.Add("first_name", "Roberto");
        contact.Add("last_name", "Tamburello");
        LiveConnectClient liveClient = new LiveConnectClient(this.session);
        LiveOperationResult operationResult = await liveClient.PostAsync("me/contacts", contact);
        dynamic result = operationResult.Result;
        this.infoTextBlock.Text = string.Join(" ", "Contact:", result.name, "ID:", result.id);
    }
    catch (LiveConnectException exception)
    {
        this.infoTextBlock.Text = "Error creating contact: " + exception.Message;
    }
}

Top

Reading and writing contacts in Objective-C for iOS

Reading contacts in Objective-C

Note This code example uses a fictitious contact ID in the getWithPath:delegate: call. You'll need to replace the value in the example with a valid contact ID.

ObjectiveC
-(void) getContact
{
    [self.liveClient getWithPath:@"contact.f347aa9f000000000000000000000000"
                        delegate:self];
}

-(void) liveOperationSucceeded:(LiveOperation *)operation
{
    NSString *firstName = [operation.result objectForKey:@"first_name"];
    NSString *lastName = [operation.result objectForKey:@"last_name"];
    NSString *gender = [operation.result objectForKey:@"gender"];
    self.displayLabel.text = [NSString stringWithFormat:@"Last Name: %@\n First Name: %@\n Gender: %@", lastName, firstName, gender];
}

Writing contacts in Objective-C

ObjectiveC
- (void) createContact
{
    NSString *firstName = firstNameTextField.text;
    NSString *lastName = lastNameTextField.text;
    NSDictionary *postBody = [NSDictionary dictionaryWithObjectsAndKeys:
                              firstName, @"first_name",
                              lastName, @"last_name", nil];
    [self.liveClient postWithPath:@"me/contacts"
                         dictBody:postBody
                         delegate:self
                        userState:@"create contact"];
}

- (void) liveOperationSucceeded:(LiveOperation *)operation
{
    if ([operation.userState isEqual:@"create contact"]) {
        NSString *contactId = [operation.result objectForKey:@"id"];
        NSString *firstName = [operation.result objectForKey:@"first_name"];
        NSString *lastName = [operation.result objectForKey:@"last_name"];
        self.statusLabel.text = [NSString stringWithFormat: @"The contact(id: %@, first_name: %@, last_name: %@) was created.", contactId, firstName, lastName];
    }
}

- (void) liveOperationFailed:(NSError *)error
                   operation:(LiveOperation *)operation
{
    if ([operation.userState isEqual:@"create contact"]) {
        self.statusLabel.text = @"The contact creation failed.";
    }
}

Top

Reading and writing contacts in Java for Android

Reading contacts in Java

Note This code example uses a fictitious contact ID in the contactID string. You'll need to replace the value in the example with a valid contact ID.

Java
public void readContact() {
    final String contactId = "contact.c1678ab4000000000000000000000000";
       final LiveOperationListener opListener = new LiveOperationListener() {
        public void onError(LiveOperationException exception, LiveOperation operation) {
            resultTextView.setText("Error getting contact info: " + exception.getMessage());
        }
        public void onComplete(LiveOperation operation) {
            JSONObject result = operation.getResult();
            resultTextView.setText("Contact's name is " + result.optString("name"));
        }
       };
    auth.login(this, Arrays.asList(new String[] { "wl.basic" }), new LiveAuthListener() {
        public void onAuthError(LiveAuthException exception, Object userState) {
            resultTextView.setText("Error signing in: " + exception.getMessage());
        }
        public void onAuthComplete(LiveStatus status, LiveConnectSession session, Object userState) {
            client.getAsync(contactId, opListener);
        }
    });
}

Writing contacts in Java

Java
public void createContact() {
    JSONObject contact = new JSONObject();
    try {
        contact.put("first_name", "Roberto");
        contact.put("last_name", "Tamburello");
    } catch (JSONException e) {
        resultTextView.setText("Error building contact: " + e.getMessage());
        return;
    }
    client.postAsync("me/contacts", contact, new LiveOperationListener() {
        public void onComplete(LiveOperation operation) {
            JSONObject result = operation.getResult();
            resultTextView.setText("Contact created. Contact ID = " + result.optString("id") +
                ", name = " + result.optString("name"));
        }
        public void onError(LiveOperationException exception, LiveOperation operation) {
            resultTextView.setText("Error creating contact: " + exception.getMessage());
        }
    });
}

In the preceding code, you can change me to USER_ID, where USER_ID represents the signed-in user's user ID.

For details about the minimum required and optional structures that your app must provide when using POST, see the "Contact object" section in REST reference.

Note The Live Connect APIs don't enable you to create friend entries. However, you can create a contact entry, and then use the Hotmail UI to invite that contact to become a friend.

Top

Reading and writing contacts using REST

Reading contacts using REST

Note This code example uses a fictitious contact ID in the path. You'll need to replace the value in the example with a valid contact ID.

GET https://apis.live.netv5.0/contact.de3413e6000000000000000000000000?access_token=ACCESS_TOKEN

Writing contacts using REST

POST https://apis.live.net/v5.0/me/contacts

Authorization: Bearer ACCESS_TOKEN
Content-Type: application/json

{
    "first_name": "Roberto",
    "last_name": "Tamburello"
}

Top


Interacting with calendars (Live Connect API)

Important

If you are a Hotmail customer who needs help with your Hotmail account, go to Microsoft Answers—Hotmail, Windows Live Messenger & Microsoft SkyDrive or your Account overview.

This topic is for software developers and does not describe how to resolve problems with your Hotmail account. Help requests entered in this topic's Did you find this helpful dialog box will not be answered.

This topic describes how your apps can use the Live Connect APIs to create, read, update, and delete a Hotmail user's calendars. Your apps can also subscribe to public calendars, such as a list of holidays. The code examples in this topic describe how to do the following tasks.

  • Reading calendar properties
  • Deleting calendars
  • Creating calendars
  • Updating calendar properties
  • Subscribing to public calendars
  • Reading calendar events
  • Deleting calendar events
  • Creating calendar events
  • Updating calendar events

Code examples for these tasks are provided in these languages, which are supported by the Live Connect APIs.

  • Interacting with calendars in JavaScript for Windows Store apps and HTML
    • Interacting with calendars in C# for Windows Store apps and Windows Phone apps
      • Interacting with calendars in Objective-C for iOS
        • Interacting with calendars in Java for Android
          • Interacting with calendars using REST

            To fully leverage the code examples in this topic, you can use them in the context of larger code reference samples that we provide in Working with the code examples. To request the required scopes, see the code patterns in Obtaining user consent.

            Specifying a calendar or an event ID

            The calendar ID and event ID values used in the path parameters of these code examples are fictitious and won't work in your app. You'll need to replace the values in the in the path parameter of the examples with a valid ID.

            Specifying a calendar ID

            In your app, you'll need use a different calendar ID. Here are some examples of calendar IDs.

            • A calendar ID to get info about a calendar.
            • You can reference the signed-in user's calendars by specifying me as the user id as in:
              • me/calendars to get info about all of the signed-in user's calendars.
            • USER_ID/calendars to get info about all of the calendars for the signed-in user that is represented by USER_ID.

              Note If USER_ID is not the user who the current access token belongs to, you can get only those calendars that are shared with the current user, not any calendars that the user represented by USER_ID has made publicly available.

            You can also use the calendar ID argument to filter the results returned in a collection. For example:

            • Get a limited number of calendar entries by using the limit parameter in the preceding code to specify the number of entries to get. For example, to get the first two calendar entries for the signed-in user, use me/calendars?limit=2.
            • Specify the first calendar entry to get by setting the offset parameter in the preceding code to the index of the first entry that you want to get. For example, to get two calendar entries for the signed-in user, starting at the third calendar entry, use me/calendars?limit=2&offset=3.

              Note In the JavaScript Object Notation (JSON)-formatted object that's returned, you can look in the paging object for the previous and next structures to get the offset and limit parameter values of the previous and next entries.

            Specifying an event ID

            In your app, you'll need use a different event ID. Here are some examples of event IDs.

            • An event ID to get info about an event.
            • me/events, to get info about events in all of the signed-in user's calendars.
            • USER_ID/events, to get info about events in all of the calendars for the signed-in user represented by USER_ID.
            • CALENDAR_ID/events, to get info about events in the calendar represented by CALENDAR_ID.

            You can also use the calendar ID argument to filter the results returned in a collection. For example:

            • Get a limited number of events based on their starting and ending times in Coordinated Universal Time (UTC) format by using the start_time and end_time parameters in the preceding code. For example, to get all calendar events from August 1 to August 3, inclusive, use CALENDAR_ID/events?start_time=2011-08-01T00:00:00Z&end_time=2011-08-03T00:00:00Z. For info about time formatting options here, see the Creating calendar events section later in this topic.

              Note If you don't specify the start_time and end_time parameters, you get only those events between the current day and 30 days in the future, by default. If there are no events within this time period, you get an empty result.

            Note You can get info about recurring events. However, you can get only the first occurrence of a recurring event for the specified time period.

            Creating events

            This section describes the information required to create an event in a calendar. How to do this in an app depends on your app's platform and is illustrated in the following code examples.

            Adding an event to a user's calendar requires the wl.calendars_update scope.

            Note To create a calendar event, the corresponding calendar's permissions structure must have a value of owner, co-owner, or read-write.

            The start and end times of the event must be expressed in one of these supported formats.

            • Times must begin in one of these formats: yyyy-mm-dd T hh:mm:ss, yyyy-mm-dd T hh:mm:ss.sss, or yyyy-mm-dd hh:mm:ss. For example, 2011-05-10T14:29:00.000 represents 10 May 2011, at 2:29 P.M.
            • Times must end in one of these formats: +hhmm, -hhmm, +hh:mm, -hh:mm, or Z, which represents the number of hours and minutes as an offset to, or in coordination with, UTC. For example, -0700 represents seven hours preceding UTC. If this time is combined with the preceding example, the result is 2011-05-10T14:29:00.000-0700, or 10 May 2011, at 7:29 A.M.

              Note If Z is not specified, the time is treated as local time. Also, if end_time is not specified, the default end time is 30 minutes after the specified start_time.

            For details about the minimum required and optional structures that your app must provide when using POST, see the Event object section in REST reference.

            Note You cannot create recurring events programmatically.

            Interacting with calendars in JavaScript for Windows Store apps and HTML

            Reading calendar properties in JavaScript

            To get info about a calendar, use code like this. The wl.calendars scope is required.

            Note This code example uses a fictitious calendar ID in the path argument. You'll need to replace the value in the example with a valid calendar ID.

            JavaScript
            function onReadCalendar() {
    WL.login({
        scope: "wl.calendars"
    }).then(
        function (response) {
            WL.api({
                path: "calendar.a6b2a7e8f2515e5e.c46e5429f0c6451cb469f622b260fa1c",
                method: "GET"
            }).then(
                function (response) {
                    document.getElementById("resultDiv").innerHTML =
                        "ID: " + response.id +
                        "<br/>Name: " + response.name;
                },
                function (responseFailed) {
                    document.getElementById("infoArea").innerText =
                        "Error calling API: " + responseFailed.error.message;
                }
            );
        },
        function (responseFailed) {
            document.getElementById("infoArea").innerText =
                "Error signing in: " + responseFailed.error_description;
        }
    );
}

            Deleting calendars in JavaScript

            To remove a calendar, use code like this. The wl.calendars_update scope is required.

            Note This code example uses a fictitious calendar ID in the path argument. You'll need to replace the value in the example with a valid calendar ID.

            JavaScript
            function onDeleteCalendar() {
    WL.login({
        scope: "wl.calendars_update"
    }).then(
        function (response) {
            WL.api({
                path: "calendar.a6b2a7e8f2515e5e.11a088a04c28495e8672ecf2bf645461",
                method: "DELETE"
            }).then(
                function (response) {
                    document.getElementById("resultDiv").innerHTML = "Deleted.";
                },
                function (responseFailed) {
                    document.getElementById("infoArea").innerText =
                        "Error calling API: " + responseFailed.error.message;
                }
            );
        },
        function (responseFailed) {
            document.getElementById("infoArea").innerText =
                "Error signing in: " + responseFailed.error_description;
        }
    );
}

            Creating calendars in JavaScript

            To add a new calendar, use code like this. The wl.calendars_update scope is required.

            JavaScript
            function onCreateCalendar() {
    WL.login({
        scope: "wl.calendars_update "
    }).then(
        function (response) {
            WL.api({
                path: "me/calendars",
                method: "POST",
                body: {
                    name: "My example calendar"
                }
            }).then(
                function (response) {
                    document.getElementById("resultDiv").innerHTML =
                        "ID: " + response.id +
                        "<br/>Name: " + response.name;
                },
                function (responseFailed) {
                    document.getElementById("infoArea").innerText =
                        "Error calling API: " + responseFailed.error.message;
                }
            );
        },
        function (responseFailed) {
            document.getElementById("infoArea").innerText =
                "Error signing in: " + responseFailed.error_description;
        }
    );
}

            Updating calendar properties in JavaScript

            To change info for an existing calendar, use code like this. The wl.calendars_update scope is required.

            Note This code example uses a fictitious calendar ID in the path argument. You'll need to replace the value in the example with a valid calendar ID.

            JavaScript
            function onUpdateCalendar() {
    WL.login({
        scope: "wl.calendars_update"
    }).then(
        function (response) {
            WL.api({
                path: "calendar.a6b2a7e8f2515e5e.11a088a04c28495e8672ecf2bf645461",
                method: "PUT",
                body: {
                    name: "My example calendar updated"
                }
            }).then(
                function (response) {
                    document.getElementById("resultDiv").innerHTML =
                        "ID: " + response.id +
                        "<br/>Name: " + response.name;
                },
                function (responseFailed) {
                    document.getElementById("infoArea").innerText =
                    "Error calling API: " + responseFailed.error.message;
                }
            );
        },
        function (responseFailed) {
            document.getElementById("infoArea").innerText =
                "Error signing in: " + responseFailed.error_description;
        }
    );
}

            Subscribing to public calendars in JavaScript

            To subscribe to a public calendar, use code like the following. The subscription URL must use the webcal scheme, and the calendar file must use the iCalendar format and the file extension .ics. The wl.calendars_update scope is required.

            JavaScript
            function onSubscribeCalendar() {
    WL.login({
        scope: "wl.calendars_update"
    }).then(
        function (response)
        {
            WL.api({
                path: "me/calendars",
                method: "POST",
                body: {
                    name: "Xbox 360 U.S. Release Schedule",
                    subscription_location: "webcal://www.trulycertifiable.com/calendars/Xbox_360.ics"
                }
            }).then(
                function (response) {
                    document.getElementById("resultDiv").innerHTML = "Subscribed.";
                },
                function (responseFailed) {
                    document.getElementById("infoArea").innerText =
                        "Error calling API: " + responseFailed.error.message;
                }
            );
        },
        function (responseFailed){
            document.getElementById("infoArea").innerText =
                "Error signing in: " + responseFailed.error_description;
        }
    );
}

            Reading calendar events in JavaScript

            To get info about an event, use code like this. The wl.calendars scope is required.

            Note This code example uses a fictitious event ID in the path argument. You'll need to replace the value in the example with a valid event ID.

            JavaScript
            function onReadEvent() {
    WL.login({
        scope: "wl.calendars"
    }).then(
        function (response) {
            WL.api({
                path: "event.a6b2a7e8f2515e5e.16c27f2b66ac4ffdae6d59236b692e20.21e30d8fc00841b8841dd16c7ec7a503",
                method: "GET"
            }).then(
                function (response) {
                    document.getElementById("resultDiv").innerHTML =
                        "ID: " + response.id +
                        "<br/>Location: " + response.location;
                },
                function (responseFailed) {
                    document.getElementById("infoArea").innerText =
                        "Error calling API: " + responseFailed.error.message;
                }
            );
        },
        function (responseFailed) {
            document.getElementById("infoArea").innerText =
                "Error signing in: " + responseFailed.error_description;
        }
    );
}

            Deleting calendar events in JavaScript

            To remove an event, use code like the following. The wl.calendars_update scope is required.

            Note This code example uses a fictitious event ID in the path argument. You'll need to replace the value in the example with a valid event ID.

            JavaScript
            function onDeleteEvent() {
    WL.login({
        scope: "wl.calendars_update"
    }).then(
        function (response)
        {
            WL.api({
                path: "event.a6b2a7e8f2515e5e.16c27f2b66ac4ffdae6d59236b692e20.21e30d8fc00841b8841dd16c7ec7a503",
                method: "DELETE"
            }).then(
                function (response) {
                    document.getElementById("resultDiv").innerHTML = "Deleted";
                },
                function (responseFailed) {
                    document.getElementById("infoArea").innerText =
                        "Error calling API: " + responseFailed.error.message;
                }
            );
        },
        function (responseFailed) {
            document.getElementById("infoArea").innerText =
                "Error signing in: " + responseFailed.error_description;
        }
     );
}

            Creating calendar events in JavaScript

            To add a new event in the user's default calendar, use code like this. The wl.events_create scope is required. See Creating events for info on the data formats and required fields.

            JavaScript
            function onCreateEvent() {
    WL.login({
        scope: "wl.events_create"
    }).then(
        function (response) {
            WL.api({
                path: "me/events",
                method: "POST",
                body: {
                    name: "Family Dinner",
                    description: "Dinner with Cynthia's family",
                    start_time: "2011-12-05T01:30:00-08:00",
                    end_time: "2011-12-05T03:00:00-08:00",
                    location: "Coho Vineyard and Winery, 123 Main St., Redmond WA 19532",
                    is_all_day_event: "false",
                    availability: "busy",
                    visibility: "public"
                }
            }).then(
                function (response) {
                    document.getElementById("resultDiv").innerHTML =
                        "ID: " + response.id +
                        "<br/>Name: " + response.name;
                },
                function (responseFailed) {
                    document.getElementById("infoArea").innerText =
                        "Error calling API: " + responseFailed.error.message;
                }
            );
        },
        function (responseFailed) {
            document.getElementById("infoArea").innerText =
                "Error signing in: " + responseFailed.error_description;
        }
    );
}

            Updating calendar events in JavaScript

            To change info for an existing event, use code like this. The wl.calendars scope is required.

            Note This code example uses a fictitious event ID in the path argument. You'll need to replace the value in the example with a valid event ID.

            JavaScript
            function onUpdateEvent() {
    WL.login({
        scope: "wl.calendars_update"
    }).then(
        function (response)
        {
            WL.api({
                path: "event.a6b2a7e8f2515e5e.16c27f2b66ac4ffdae6d59236b692e20.21e30d8fc00841b8841dd16c7ec7a503",
                method: "PUT",
                body: {
                    name: "My example event has changed"
                }
            }).then(
                function (response) {
                    document.getElementById("resultDiv").innerHTML =
                        "ID: " + response.id +
                        "<br/>Name: " + response.name;
                },
                function (responseFailed) {
                    document.getElementById("infoArea").innerText =
                        "Error calling API: " + responseFailed.error.message;
                }
            );
        },
        function (responseFailed){
            document.getElementById("infoArea").innerText =
                "Error signing in: " + responseFailed.error_description;
        }
    );
}

            Top

            Interacting with calendars in C# for Windows Store apps and Windows Phone apps

            Reading calendar properties in C#

            To get info about a calendar, use code like this. The wl.calendars scope is required.

            Note This code example uses a fictitious calendar ID in the GetAsync call. You'll need to replace the value in the example with a valid calendar ID.

            C#
            private async void btnReadCalendar_Click(object sender, RoutedEventArgs e)
{
    try
    {
        LiveConnectClient liveClient = new LiveConnectClient(this.session);
        LiveOperationResult operationResult =
            await liveClient.GetAsync("calendar.8c8ce076ca27823f.9690899aeeae4e97be18cdc75b644454");
        dynamic result = operationResult.Result;
        this.infoTextBlock.Text = "Calendar name: " + result.name;
    }
    catch (LiveConnectException exception)
    {
        this.infoTextBlock.Text = "Error getting calendar info: " + exception.Message;
    }
}

            Deleting calendars in C#

            To remove a calendar, use code like this. The wl.calendars_update scope is required.

            Note This code example uses a fictitious calendar ID in the DeleteAsync call. You'll need to replace the value in the example with a valid calendar ID.

            C#
            private async void btnDeleteCalendar_Click(object sender, RoutedEventArgs e)
{
    try
    {
        LiveConnectClient liveClient = new LiveConnectClient(this.session);
        LiveOperationResult operationResult =
            await liveClient.DeleteAsync("calendar.a6b2a7e8f2515e5e.212e9b5c4fce4662bfda971a10519b8b");
        this.infoTextBlock.Text = "Calendar deleted.";
    }
    catch (LiveConnectException exception)
    {
        this.infoTextBlock.Text = "Error deleting calendar: " + exception.Message;
    }
}

            Creating calendars in C#

            To add a new calendar, use code like this. The wl.calendars_update scope is required.

            C#
            private async void btnCreateCalendar_Click(object sender, RoutedEventArgs e)
{
    try
    {
        LiveConnectClient liveClient = new LiveConnectClient(this.session);
        var calendar = new Dictionary<string, object>();
        calendar.Add("name", "My Example Calendar");
        LiveOperationResult operationResult = await liveClient.PostAsync("me/calendars", calendar);
        dynamic result = operationResult.Result;
        this.infoTextBlock.Text = string.Join(" ", "Created calendar:", result.name, "ID:", result.id);
    }
    catch (LiveConnectException exception)
    {
        this.infoTextBlock.Text = "Error creating calendar: " + exception.Message;
    }
}

            Updating calendar properties in C#

            To change info for an existing calendar, use code like this. The wl.calendars_update scope is required.

            Note This code example uses a fictitious calendar ID in the PutAsync call. You'll need to replace the value in the example with a valid calendar ID.

            C#
            private async void btnUpdateCalendar_Click(object sender, RoutedEventArgs e)
{
    try
    {
        LiveConnectClient liveClient = new LiveConnectClient(this.session);
        var calendar = new Dictionary<string, object>();
        calendar.Add("name", "Roberto's Calendar Updated");
        LiveOperationResult operationResult =
            await liveClient.PutAsync("calendar.8c8ce076ca27823f.9690899aeeae4e97be18cdc75b644454", calendar);
        dynamic result = operationResult.Result;
        this.infoTextBlock.Text = string.Join(" ", "Updated calendar:", result.name, "ID:", result.id);
    }
    catch (LiveConnectException exception)
    {
        this.infoTextBlock.Text = "Error updating calendar: " + exception.Message;
    }
}

            Subscribing to public calendars in C#

            To subscribe to a public calendar, use code like the following. The subscription URL must use the webcal scheme, and the calendar file must use the iCalendar format and the file extension .ics. The wl.calendars_update scope is required.

            C#
            private async void btnSubscribe_Click(object sender, RoutedEventArgs e)
{
    try
    {
        LiveConnectClient liveClient = new LiveConnectClient(this.session);
        var calendar = new Dictionary<string, object>();
        calendar.Add("name", "Anime/Game Character Birthdays");
        calendar.Add("subscription_url", "webcal://ical.mac.com/fredduck/Anime47Game32Birthdays.ics");
        LiveOperationResult operationResult = await liveClient.PostAsync("me/calendars", calendar);
        this.infoTextBlock.Text = "Calendar subscribed.";
    }
    catch (LiveConnectException exception)
    {
        this.infoTextBlock.Text = "Error subscribing to calendar: " + exception.Message;
    }
}

            Reading calendar events in C#

            To get info about an event, use code like this. The wl.calendars scope is required.

            Note This code example uses a fictitious event ID in the GetAsync call. You'll need to replace the value in the example with a valid event ID.

            C#
            private async void btnReadEvent_Click(object sender, RoutedEventArgs e)
{
    try
    {
        LiveConnectClient liveClient = new LiveConnectClient(this.session);
        var calendar = new Dictionary<string, object>();
        calendar.Add("name", "My Example Calendar");
        LiveOperationResult operationResult =
            await liveClient.GetAsync("event.8c8ce076ca27823f.9690899aeeae4e97be18cdc75b644454.87bfc5dc263c403eacadd35b1e64bdf3");
        dynamic result = operationResult.Result;
        this.infoTextBlock.Text = "Event: " + result.name + ", Location: " + result.location;
    }
    catch (LiveConnectException exception)
    {
        this.infoTextBlock.Text = "Error getting event info: " + exception.Message;
    }
}

            Deleting calendar events in C#

            To remove an event, use code like the following. The wl.calendars_update scope is required.

            Note This code example uses a fictitious event ID in the DeleteAsync call. You'll need to replace the value in the example with a valid event ID.

            C#
            private async void btnDeleteEvent_Click(object sender, RoutedEventArgs e)
{
    try
    {
        LiveConnectClient liveClient = new LiveConnectClient(this.session);
        LiveOperationResult operationResult =
            await liveClient.DeleteAsync("event.d050fdffbb314d9bb40bc20a3c961d84.57f866fd013f4a14adcf18d9a9dc23bc");

        this.infoTextBlock.Text = "Event deleted.";
    }
    catch (LiveConnectException exception)
    {
        this.infoTextBlock.Text = "Error deleting event: " + exception.Message;
    }
}

            Creating calendar events in C#

            To add a new event in the user's default calendar, use code like this. The wl.events_create scope is required.

            C#
            private async void btnCreateEvent_Click(object sender, RoutedEventArgs e)
{
    try
    {
        var calEvent = new Dictionary<string, object>();
        calEvent.Add("name", "Family Dinner");
        calEvent.Add("description", "Dinner with Cynthia's family");
        calEvent.Add("start_time", "2012-04-07T01:30:00-08:00");
        calEvent.Add("end_time", "2012-04-07T03:00:00-08:00");
        calEvent.Add("location", "Coho Vineyard and Winery, 123 Main St., Redmond WA 19532");
        calEvent.Add("is_all_day_event", false);
        calEvent.Add("availability", "busy");
        calEvent.Add("visibility", "public");
        LiveConnectClient liveClient = new LiveConnectClient(this.session);
        LiveOperationResult operationResult = await liveClient.PostAsync("me/events", calEvent);
        dynamic result = operationResult.Result;
        this.infoTextBlock.Text = string.Join(" ", "Created event:", result.name, "ID:", result.id);
    }
    catch (LiveConnectException exception)
    {
        this.infoTextBlock.Text = "Error creating event: " + exception.Message;
    }
}

            Updating calendar events in C#

            To change info for an existing event, use code like this. The wl.calendars scope is required.

            Note This code example uses a fictitious event ID in the PutAsync call. You'll need to replace the value in the example with a valid event ID.

            C#
            private async void btnUpdateEvent_Click(object sender, RoutedEventArgs e)
{
    try
    {
        LiveConnectClient liveClient = new LiveConnectClient(this.session);
        var calEvent = new Dictionary<string, object>();
        calEvent.Add("name", "My Example Event Has Changed Yet Again");
        LiveOperationResult operationResult =
            await liveClient.PutAsync("event.8c8ce076ca27823f.9690899aeeae4e97be18cdc75b644454.87bfc5dc263c403eacadd35b1e64bdf3", calEvent);
        dynamic result = operationResult.Result;
        this.infoTextBlock.Text = "Event updated: " + result.name;
    }
    catch (LiveConnectException exception)
    {
        this.infoTextBlock.Text = "Error updating event: " + exception.Message;
    }
}

            Top

            Interacting with calendars in Objective-C for iOS

            Reading calendar properties in Objective-C

            To get info about a calendar, use code like this. The wl.calendars scope is required.

            Note This code example uses a fictitious calendar ID in the getWithPath:delegate: call. You'll need to replace the value in the example with a valid calendar ID.

            ObjectiveC
            -(void) getCalendar
{
    [self.liveClient getWithPath:@"calendar.95d463b9efcca0e1.476023a3b4a54f06b7776e21d1b001fa"
                        delegate:self];
}

-(void) liveOperationSucceeded:(LiveOperation *)operation
{
    NSString *calendarId = [operation.result objectForKey:@"id"];
    NSString *calendarName = [operation.result objectForKey:@"name"];
    NSString *calendarDescription = [operation.result objectForKey:@"description"];
    self.displayLabel.text = [NSString stringWithFormat:@"Id: %@\n Name: %@\n Description: %@", calendarId, calendarName, calendarDescription];
}

            Deleting calendars in Objective-C

            To remove a calendar, use code like this. The wl.calendars_update scope is required.

            Note This code example uses a fictitious calendar ID in the deleteWithPath:delegate: call. You'll need to replace the value in the example with a valid calendar ID.

            ObjectiveC
            - (void) deleteCalendar
{
    NSString *calendarId = @"calendar.1234567890";
    [liveClient deleteWithPath:calendarId
                      delegate:self
                     userState:@"delete calendar"];
}

- (void) liveOperationSucceeded:(LiveOperation *)operation
{
    if ([operation.userState isEqual:@"delete calendar"]) {
        self.statusLabel.text = [NSString stringWithFormat: @"The calendar (%@) was deleted.", operation.path];
    }
}

- (void) liveOperationFailed:(NSError *)error
                   operation:(LiveOperation *)operation
{
    if ([operation.userState isEqual:@"delete calendar"]) {
        self.statusLabel.text = @"The request to delete the calendar failed.";
    }
}

            Creating calendars in Objective-C

            To add a new calendar, use code like this. The wl.calendars_update scope is required.

            ObjectiveC
            -(void) createCalendar
{
    NSDictionary * newCalendar = [[NSDictionary dictionaryWithObjectsAndKeys:
                                   @"Payments", @"name",
                                   @"When to pay the bills", @"description",
                                   nil] retain];
    [self.liveClient postWithPath:@"me/calendars"
                         dictBody:newCalendar
                         delegate:self
                         userState:@"CREATE_CALENDAR"];
    [newCalendar release];
}

- (void) liveOperationSucceeded:(LiveOperation *)operation
{
    if (operation.userState == @"CREATE_CALENDAR")
    {
        NSString *calendarId = [operation.result objectForKey:@"id"];
        [self.liveClient getWithPath:calendarId
                                   delegate:self
                                  userState:@"GET_CALENDAR_INFO"];
    }
    else if (operation.userState == @"GET_CALENDAR_INFO")
    {
        NSString *calendarId = [operation.result objectForKey:@"id"];
        NSString *calendarName = [operation.result objectForKey:@"name"];
        NSString *calendarDescription = [operation.result objectForKey:@"description"];
        self.displayLabel.text = [NSString stringWithFormat:@"Id: %@\n Name: %@\n Description: %@", calendarId, calendarName, calendarDescription];
    }
}

            Updating calendar properties in Objective-C

            To change info for an existing calendar, use code like this. The wl.calendars_update scope is required.

            Note This code example uses a fictitious calendar ID in the putWithPath:delegate: call. You'll need to replace the value in the example with a valid calendar ID.

            ObjectiveC
            -(void) updateCalendar
{
    NSDictionary * newCalendar = [[NSDictionary dictionaryWithObjectsAndKeys:
                                   @"Updated Calendar Name", @"name",
                                   @"Description updated...", @"description",
                                   nil] retain];
    [self.liveClient putWithPath:@"calendar.95d463b9efcca0e1.5780dd54f046438687c00e723941dea0"
                        dictBody:newCalendar
                        delegate:self];
    [newCalendar release];
}

- (void) liveOperationSucceeded:(LiveOperation *)operation
{
    NSString *calendarId = [operation.result objectForKey:@"id"];
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"API call successful!"
                                                    message:[NSString stringWithFormat:@"Calendar with id: %@ created successfully", calendarId]
                                                   delegate:self
                                          cancelButtonTitle:@"Ok"
                                          otherButtonTitles:nil,
                           nil];
    [alert show];
    [alert release];
}

            Subscribing to public calendars in Objective-C

            To subscribe to a public calendar, use code like the following. The subscription URL must use the webcal scheme, and the calendar file must use the iCalendar format and the file extension .ics. The wl.calendars_update scope is required.

            ObjectiveC
            - (void) subscribeCalenar
{
    NSDictionary * newCalendar = [[NSDictionary dictionaryWithObjectsAndKeys:
                                   @"US Holidays", @"name",
                                   @"webcal://ical.mac.com/ical/US32Holidays.ics", @"susbscription_location",
                                   nil] retain];
    [self.liveClient postWithPath:@"me/calendars"
                         dictBody:newCalendar
                         delegate:self
                        userState:@"SUBSCRIBE_CALENDAR"];
    [newCalendar release];
}

- (void) liveOperationSucceeded:(LiveOperation *)operation
{
    if (operation.userState == @"SUBSCRIBE_CALENDAR")
    {
        NSString *calendarId = [operation.result objectForKey:@"id"];
        [self.liveClient getWithPath:calendarId
                            delegate:self
                           userState:@"GET_CALENDAR_INFO"];
    }
    else if (operation.userState == @"GET_CALENDAR_INFO")
    {
        NSString *calendarId = [operation.result objectForKey:@"id"];
        NSString *calendarName = [operation.result objectForKey:@"name"];
        NSString *calendarDescription = [operation.result objectForKey:@"description"];
        self.displayLabel.text = [NSString stringWithFormat:@"Id: %@\n Name: %@\n Description: %@", calendarId, calendarName, calendarDescription];
    }
}

            Reading calendar events in Objective-C

            To get info about an event, use code like this. The wl.calendars scope is required.

            Note This code example uses a fictitious event ID in the getWithPath:delegate: call. You'll need to replace the value in the example with a valid event ID.

            ObjectiveC
            -(void) getEvent
    [self.liveClient getWithPath:@"event.95d463b9efcca0e1.5780dd54f046438687c00e723941dea0.d18afec00677494f857e44fe0c6937c7"
                        delegate:self];
}

- (void) liveOperationSucceeded:(LiveOperation *)operation
{
    NSString *eventId = [operation.result objectForKey:@"id"];
    NSString *eventName = [operation.result objectForKey:@"name"];
    NSString *eventDescription = [operation.result objectForKey:@"description"];
    NSString *eventLocation = [operation.result objectForKey:@"location"];
    NSString *eventCalendarId = [operation.result objectForKey:@"calendar_id"];
    NSString *eventStartTime = [operation.result objectForKey:@"start_time"];
    NSString *eventEndTime = [operation.result objectForKey:@"end_time"];
    NSString *eventIsAllDay = [operation.result objectForKey:@"is_all_day"];
    NSString *eventRecurrence = [operation.result objectForKey:@"recurrence"];
    NSString *eventAvailability = [operation.result objectForKey:@"availability"];
    NSString *eventVisibility = [operation.result objectForKey:@"visibility"];
    self.displayLabel.text = [NSString stringWithFormat:
                              @"Event Properties:\n"
                              @"\tId. %@\n"
                              @"\tName. %@\n"
                              @"\tDescription. %@\n"
                              @"\tLocation. %@\n"
                              @"\tCalendar Id. %@\n"
                              @"\tStart Time. %@\n"
                              @"\tEnd Time. %@\n"
                              @"\tIs All Day. %@\n"
                              @"\tRecurrence. %@\n"
                              @"\tAvailability. %@\n"
                              @"\tVisibility. %@"
                              , eventId,
                              eventName,
                              eventDescription,
                              eventLocation,
                              eventCalendarId,
                              eventStartTime,
                              eventEndTime,
                              eventIsAllDay,
                              eventRecurrence,
                              eventAvailability,
                              eventVisibility];

}

            Deleting calendar events in Objective-C

            To remove an event, use code like the following. The wl.calendars_update scope is required.

            Note This code example uses a fictitious event ID in the deleteWithPath:delegate: call. You'll need to replace the value in the example with a valid event ID.

            ObjectiveC
            - (void) deleteEvent
{
    [self.liveClient deleteWithPath:@"event.95d463b9efcca0e1.5780dd54f046438687c00e723941dea0.d18afec00677494f857e44fe0c6937c7"
                           delegate:self];

}

- (void) liveOperationSucceeded:(LiveOperation *)operation
{
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"API call successful!"
                                                    message:@"Event was deleted successfully!"
                                                   delegate:self
                                          cancelButtonTitle:@"Ok"
                                          otherButtonTitles:nil,
                          nil];
    [alert show];
    [alert release];
}

            Creating calendar events in Objective-C

            To add a new event in the user's default calendar, use code like this. The wl.events_create scope is required. See Creating events for info on the data formats and required fields.

            ObjectiveC
            -(void) createEvent
{
    NSDictionary * newEvent = [[NSDictionary dictionaryWithObjectsAndKeys:
                                @"John's Bday", @"name",
                                @"BBQ @ his place", @"description",
                                @"2012-01-12T21:00:00+00:00",@"start_time",
                                @"2012-01-13T03:00:00+00:00",@"end_time",
                                @"John's Pad",@"location",
                                @"busy",@"availability",
                                @"2012-01-12T21:00:00+00:00",@"start_time",
                                nil] retain];
    [self.liveClient postWithPath:@"me/events"
                         dictBody:newEvent
                         delegate:self];
    [newEvent release];
}

- (void) liveOperationSucceeded:(LiveOperation *)operation
{
    NSString *eventId = [operation.result objectForKey:@"id"];
    NSString *eventName = [operation.result objectForKey:@"name"];
    NSString *eventDescription = [operation.result objectForKey:@"description"];
    NSString *eventLocation = [operation.result objectForKey:@"location"];
    NSString *eventCalendarId = [operation.result objectForKey:@"calendar_id"];
    NSString *eventStartTime = [operation.result objectForKey:@"start_time"];
    NSString *eventEndTime = [operation.result objectForKey:@"end_time"];
    NSString *eventIsAllDay = [operation.result objectForKey:@"is_all_day"];
    NSString *eventRecurrence = [operation.result objectForKey:@"recurrence"];
    NSString *eventAvailability = [operation.result objectForKey:@"availability"];
    NSString *eventVisibility = [operation.result objectForKey:@"visibility"];
    self.displayLabel.text = [NSString stringWithFormat:
                              @"Event Properties:\n"
                              @"\tId. %@\n"
                              @"\tName. %@\n"
                              @"\tDescription. %@\n"
                              @"\tLocation. %@\n"
                              @"\tCalendar Id. %@\n"
                              @"\tStart Time. %@\n"
                              @"\tEnd Time. %@\n"
                              @"\tIs All Day. %@\n"
                              @"\tRecurrence. %@\n"
                              @"\tAvailability. %@\n"
                              @"\tVisibility. %@"
                              , eventId,
                              eventName,
                              eventDescription,
                              eventLocation,
                              eventCalendarId,
                              eventStartTime,
                              eventEndTime,
                              eventIsAllDay,
                              eventRecurrence,
                              eventAvailability,
                              eventVisibility];
}

            Updating calendar events in Objective-C

            To change info for an existing event, use code like this. The wl.calendars scope is required.

            Note This code example uses a fictitious event ID in the putWithPath:delegate: call. You'll need to replace the value in the example with a valid event ID.

            ObjectiveC
            -(void) updateEvent
{
    NSDictionary * updatedEvent = [[NSDictionary dictionaryWithObjectsAndKeys:
                                    @"BBQ Grill @ Smith Street. (Updated location)",@"location",
                                    @"2012-01-12T20:30:00+00:00",@"start_time",
                                    nil] retain];
    [self.liveClient putWithPath:@"event.95d463b9efcca0e1.88c4c26007194319a717a8aa8f51fb00.1c1d09bb0d7743e2b32a97f419632061"
                        dictBody:updatedEvent
                        delegate:self];
    [updatedEvent release];
}

- (void) liveOperationSucceeded:(LiveOperation *)operation
{
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"API call successful!"
                                                    message:@"Event was updated successfully!"
                                                   delegate:self
                                          cancelButtonTitle:@"Ok"
                                          otherButtonTitles:nil,
                          nil];
    [alert show];
    [alert release];
}

            Top

            Interacting with calendars in Java for Android

            Reading calendar properties in Java

            To get info about a calendar, use code like this. The wl.calendars scope is required.

            Note This code example uses a fictitious calendar ID in the GetAsync call. You'll need to replace the value in the example with a valid calendar ID.

            Java
            public void readCalendar() {
    final String calendarId = "calendar.a6b2a7e8f2515e5e.16c27f2b66ac4ffdae6d59236b692e20";
       final LiveOperationListener opListener = new LiveOperationListener() {
        public void onError(LiveOperationException exception, LiveOperation operation) {
               resultTextView.setText("Error getting calendar info: " + exception.getMessage());
           }
        public void onComplete(LiveOperation operation) {
            JSONObject result = operation.getResult();
            resultTextView.setText("Calendar info:" +
                "\n ID = " + result.optString("id") +
                "\nName = " + result.optString("name") +
                "\nPermissions = " + result.optString("permissions"));
        }
       };
    auth.login(this, Arrays.asList(new String[] { "wl.calendars" }),
        new LiveAuthListener() {
               public void onAuthError(LiveAuthException exception, Object userState) {
                   resultTextView.setText("Error signing in: " + exception.getMessage());
               }
            public void onAuthComplete(LiveStatus status, LiveConnectSession session, Object userState) {
                   client.getAsync(calendarId, opListener);
               }
        }
    );
}

            Deleting calendars in Java

            To remove a calendar, use code like this. The wl.calendars_update scope is required.

            Note This code example uses a fictitious calendar ID in the DeleteAsync call. You'll need to replace the value in the example with a valid calendar ID.

            Java
            public void deleteCalendar() {
    client.deleteAsync("calendar.a6b2a7e8f2515e5e.f69bbd89e2cd42859a8e44a36f9e8f7d", new LiveOperationListener() {
        public void onComplete(LiveOperation operation) {
            resultTextView.setText("Calendar deleted.");
        }
        public void onError(LiveOperationException exception, LiveOperation operation) {
            resultTextView.setText("Error deleting calendar: " + exception.getMessage());
        }
    });
}

            Creating calendars in Java

            To add a new calendar, use code like this. The wl.calendars_update scope is required.

            Java
            public void createCalendar() {
    final LiveOperationListener opListener = new LiveOperationListener() {
        public void onError(LiveOperationException exception, LiveOperation operation) {
               resultTextView.setText("Error creating calendar: " + exception.getMessage());
           }
        public void onComplete(LiveOperation operation) {
            JSONObject result = operation.getResult();
            String text = "Calendar created:\n" +
                "\nID = " + result.optString("id") +
                "\nName = " + result.optString("name");
               resultTextView.setText(text);
           }
       };
    auth.login(this, Arrays.asList(new String[] { "wl.calendars_update" }), new LiveAuthListener() {
           public void onAuthError(LiveAuthException exception, Object userState) {
            resultTextView.setText("Error signing in: " + exception.getMessage());
         }
        public void onAuthComplete(LiveStatus status, LiveConnectSession session, Object userState) {
            try {
                JSONObject body = new JSONObject();
                body.put("name", "My New Calendar");
                body.put("description", "Manage some new calendar events");
                client.postAsync("me/calendars", body, opListener);
            }
            catch(JSONException ex) {
                resultTextView.setText("Error building calendar: " + ex.getMessage());
            }
           }
    });
}

            For details about the minimum required and optional structures that your app must provide when using POST, see the "Calendar object" section in REST reference.

            Updating calendar properties in Java

            To change info for an existing calendar, use code like this. The wl.calendars_update scope is required.

            Note This code example uses a fictitious calendar ID in the PutAsync call. You'll need to replace the value in the example with a valid calendar ID.

            Java
            public void updateCalendar() {
    final String calendarId = "calendar.a6b2a7e8f2515e5e.16c27f2b66ac4ffdae6d59236b692e20";
    final LiveOperationListener opListener = new LiveOperationListener() {
        public void onError(LiveOperationException exception, LiveOperation operation) {
            resultTextView.setText("Error updating calendar: " + exception.getMessage());
        }
        public void onComplete(LiveOperation operation) {
            JSONObject result = operation.getResult();
            String text = "Calendar updated:\n" +
                "\nID = " + result.optString("id") +
                "\rName = " + result.optString("name");
            resultTextView.setText(text);
        }
       };
    auth.login(this, Arrays.asList(new String[] { "wl.calendars_update" }),
        new LiveAuthListener() {
               public void onAuthError(LiveAuthException exception, Object userState) {
                   resultTextView.setText("Error signing in: " + exception.getMessage());
               }
            public void onAuthComplete(LiveStatus status, LiveConnectSession session, Object userState) {
                try {
                    JSONObject body = new JSONObject();
                    body.put("name", "My Updated Calendar");
                       client.putAsync(calendarId, body, opListener);
                }
                catch(JSONException ex) {
                    resultTextView.setText("Error updating calendar: " + ex.getMessage());
                }
               }
        }
    );
}

            Note To update a calendar's properties, the calendar's permissions structure must have a value of owner, co-owner, or read-write.

            For details about the minimum required and optional structures that your app must provide when using PUT, see the "Calendar object" section in REST reference.

            Subscribing to public calendars in Java

            To subscribe to a public calendar, use code like the following. The subscription URL must use the webcal scheme, and the calendar file must use the iCalendar format and the file extension .ics. The wl.calendars_update scope is required.

            Java
            public void subscribeCalendar() {
    final LiveOperationListener opListener = new LiveOperationListener() {
        public void onError(LiveOperationException exception, LiveOperation operation) {
               resultTextView.setText("Error subscribing to calendar: " + exception.getMessage());
           }
        public void onComplete(LiveOperation operation) {
            JSONObject result = operation.getResult();
            String text = "Calendar subscribed:\n" +
                "\nID = " + result.optString("id") +
                "\nName = " + result.optString("name");
               resultTextView.setText(text);
           }
       };
    auth.login(this, Arrays.asList(new String[] { "wl.calendars_update" }),
        new LiveAuthListener() {
               public void onAuthError(LiveAuthException exception, Object userState) {
                   resultTextView.setText("Error signing in: " + exception.getMessage());
               }
            public void onAuthComplete(LiveStatus status, LiveConnectSession session, Object userState) {
                try {
                    JSONObject body = new JSONObject();
                    body.put("name", "US Holidays");
                    body.put("subscription_location", "webcal://ical.mac.com/ical/US32Holidays.ics");
                       client.postAsync("me/calendars", body, opListener);
                }
                catch(JSONException ex) {
                    resultTextView.setText("Error subscribing to calendar: " + ex.getMessage());
                }
               }
        }
    );
}

            Reading calendar events in Java

            To get info about an event, use code like this. The wl.calendars scope is required.

            Note This code example uses a fictitious event ID in the GetAsync call. You'll need to replace the value in the example with a valid event ID.

            Java
            public void readEvent() {
    final String eventId = "event.a6b2a7e8f2515e5e.16c27f2b66ac4ffdae6d59236b692e20.e671b72b6a024b67ace52e88f7185f36";
    client.getAsync(eventId, new LiveOperationListener() {
        public void onError(LiveOperationException exception, LiveOperation operation) {
               resultTextView.setText("Error reading event: " + exception.getMessage());
           }
        public void onComplete(LiveOperation operation) {
            JSONObject result = operation.getResult();
            String text = "Event info:" +
                "\nID = " + result.optString("id") +
                "\nName = " + result.optString("name") +
                "\nLocation = " + result.optString("location") +
                "\nDescription = " + result.optString("description") +
                "\nStart time = " + result.optString("start_time") +
                "\nEnd time = " + result.optString("end_time") +
                "\nAll day event = " + result.optString("is_all_day_event") +
                "\nRecurrence = " + result.optString("recurrence");
               resultTextView.setText(text);
           }
       });
}

            Deleting calendar events in Java

            To remove an event, use code like the following. The wl.calendars_update scope is required.

            Note This code example uses a fictitious event ID in the DeleteAsync call. You'll need to replace the value in the example with a valid event ID.

            Java
            public void deleteEvent() {
    String eventId = "event.a6b2a7e8f2515e5e.16c27f2b66ac4ffdae6d59236b692e20.2f136a42169a4fc9903652a8fbade918";
    client.deleteAsync(eventId, new LiveOperationListener() {
        public void onError(LiveOperationException exception, LiveOperation operation) {
               resultTextView.setText("Error deleting event: " + exception.getMessage());
           }
        public void onComplete(LiveOperation operation) {
            resultTextView.setText("Event deleted.");
           }
       });
}

            Creating calendar events in Java

            To add a new event in the user's default calendar, use code like this. The wl.events_create scope is required. See Creating events for info on the data formats and required fields.

            Java
            public void createEvent() {
    final LiveOperationListener opListener = new LiveOperationListener() {
        public void onError(LiveOperationException exception, LiveOperation operation) {
               resultTextView.setText("Error creating event: " + exception.getMessage());
           }
        public void onComplete(LiveOperation operation) {
            JSONObject result = operation.getResult();
            String text = "Event created:\n" +
                "\nID = " + result.optString("id") +
                "\nName = " + result.optString("name");
               resultTextView.setText(text);
           }
       };
    auth.login(this, Arrays.asList(new String[] { "wl.calendars_update" }),
        new LiveAuthListener() {
               public void onAuthError(LiveAuthException exception, Object userState) {
                   resultTextView.setText("Error signing in: " + exception.getMessage());
               }
            public void onAuthComplete(LiveStatus status, LiveConnectSession session, Object userState) {
                try {
                    JSONObject body = new JSONObject();
                    body.put("name", "Family Dinner");
                    body.put("description", "Dinner with Cynthia's family");
                    body.put("start_time", "2012-01-22T01:30:00-08:00");
                    body.put("end_time", "2012-01-22T03:00:00-08:00");
                    body.put("location", "Coho Vineyard and Winery, 123 Main St., Redmond WA 19532");
                    body.put("is_all_day_event", false);
                    body.put("availability", "busy");
                    body.put("visibility", "public");
                       client.postAsync("me/events", body, opListener);
                }
                catch(JSONException ex) {
                    resultTextView.setText("Error building event: " + ex.getMessage());
                }
               }
        }
    );
}

            Updating calendar events in Java

            To change info for an existing event, use code like this. The wl.calendars scope is required.

            Note This code example uses a fictitious event ID in the PutAsync call. You'll need to replace the value in the example with a valid event ID.

            Java
            public void updateEvent() {
    final String eventId = "event.a6b2a7e8f2515e5e.16c27f2b66ac4ffdae6d59236b692e20.e671b72b6a024b67ace52e88f7185f36";
    final LiveOperationListener opListener = new LiveOperationListener() {
        public void onError(LiveOperationException exception, LiveOperation operation) {
               resultTextView.setText("Error updating event: " + exception.getMessage());
           }
        public void onComplete(LiveOperation operation) {
            JSONObject result = operation.getResult();
            String text = "Event updated:\n" +
                "\nID = " + result.optString("id") +
                "\nName = " + result.optString("name");
               resultTextView.setText(text);
           }
       };
    auth.login(this, Arrays.asList(new String[] { "wl.calendars_update" }),
        new LiveAuthListener() {
               public void onAuthError(LiveAuthException exception, Object userState) {
                   resultTextView.setText("Error signing in: " + exception.getMessage());
               }
            public void onAuthComplete(LiveStatus status, LiveConnectSession session, Object userState) {
                try {
                    JSONObject body = new JSONObject();
                    body.put("name", "Family dinner with some guests");
                       client.putAsync(eventId, body, opListener);
                }
                catch(JSONException ex) {
                    resultTextView.setText("Error updating event: " + ex.getMessage());
                }
               }
        }
    );
}

            Note To update a calendar event, the corresponding calendar's permissions structure must have a value of owner, co-owner, or read-write.

            For details about the required and optional structures that your app must provide when using PUT, see the "Event object" section in REST reference.

            Note You cannot update recurring events programmatically.

            Top

            Interacting with calendars using REST

            Reading calendar properties using REST

            To get info about a calendar, use code like this. The wl.calendars scope is required.

            Note This code example uses a fictitious calendar ID in the URL. You'll need to replace the value in the example with a valid calendar ID.

            GET https://apis.live.net/v5.0/calendar.611afb17fa9448f28cdb8277e8ffeb77?access_token=ACCESS_TOKEN

            Deleting calendars using REST

            To remove a calendar, use code like this. The wl.calendars_update scope is required.

            Note This code example uses a fictitious calendar ID in the URL. You'll need to replace the value in the example with a valid calendar ID.

            DELETE https://apis.live.net/v5.0/calendar.611afb17fa9448f28cdb8277e8ffeb77?access_token=ACCESS_TOKEN

            Creating calendars using REST

            To add a new calendar, use code like this. The wl.calendars_update scope is required.

            POST https://apis.live.net/v5.0/me/calendars

Authorization: Bearer ACCESS_TOKEN
Content-Type: application/json

{
    "name": "My example calendar"
}

            Updating calendar properties using REST

            To change info for an existing calendar, use code like this. The wl.calendars_update scope is required.

            Note This code example uses a fictitious calendar ID in the URL. You'll need to replace the value in the example with a valid calendar ID.

            PUT https://apis.live.net/v5.0/calendar.611afb17fa9448f28cdb8277e8ffeb77

Authorization: Bearer ACCESS_TOKEN
Content-Type: application/json

{
    "name": "My example calendar has changed"
}

            Subscribing to public calendars using REST

            To subscribe to a public calendar, use code like the following. The subscription URL must use the webcal scheme, and the calendar file must use the iCalendar format and the file extension .ics. The wl.calendars_update scope is required.

            POST https://apis.live.net/v5.0/me/calendars

Authorization: Bearer ACCESS_TOKEN
Content-Type: application/json

{
    "name": "Anime/game character birthdays",
    "subscription_location": "webcal://ical.mac.com/fredduck/Anime47Game32Birthdays.ics"
}

            Reading calendar events using REST

            To get info about an event, use code like this. The wl.calendars scope is required.

            Note This code example uses a fictitious event ID in the URL. You'll need to replace the value in the example with a valid event ID.

            GET https://apis.live.net/v5.0/event.c76d2a8c4e674ff9bc96f17dee3c34c9.b987b00b77194723b8c16bbe57a03037?access_token=ACCESS_TOKEN

            Deleting calendar events using REST

            To remove an event, use code like the following. The wl.calendars_update scope is required.

            Note This code example uses a fictitious event ID in the URL. You'll need to replace the value in the example with a valid event ID.

            DELETE https://apis.live.net/v5.0/event.c76d2a8c4e674ff9bc96f17dee3c34c9.b987b00b77194723b8c16bbe57a03037?access_token=ACCESS_TOKEN

            Creating calendar events using REST

            To add a new event in the user's default calendar, use code like this. The wl.events_create scope is required. See Creating events for info on the data formats and required fields.

            POST https://apis.live.net/v5.0/me/events

Authorization: Bearer ACCESS_TOKEN
Content-Type: application/json

{
    "name: "Family Dinner",
    "description": "Dinner with Cynthia's family",
    "start_time": "2011-03-22T01:30:00-08:00",
    "end_time": "2011-03-22T03:00:00-08:00",
    "location": "Coho Vineyard and Winery, 123 Main St., Redmond WA 19532",
    "is_all_day_event": false,
    "availability": "busy",
    "visibility": "public"
}

            Updating calendar events using REST

            Note This code example uses a fictitious event ID in the URL. You'll need to replace the value in the example with a valid event ID.

            PUT https://apis.live.net/v5.0/event.c76d2a8c4e674ff9bc96f17dee3c34c9.b987b00b77194723b8c16bbe57a03037

Authorization: Bearer ACCESS_TOKEN
Content-Type: application/json

{
    "name": "My example event has changed"
}

            Top


Linking to and embedding calendars

Important

If you are a Hotmail customer who needs help with your Hotmail account, go to Microsoft Answers—Hotmail, Windows Live Messenger & Microsoft SkyDrive or your Account overview.

This topic is for software developers and does not describe how to resolve problems with your Hotmail account. Help requests entered in this topic's Did you find this helpful dialog box will not be answered.

This topic describes how to add an Add to Calendar link or button to a web page and also, how to embed a Hotmail calendar in a web page. Users can add events to their calendars by clicking an Add to Calendar link or button on a web page. You can also keep users informed of events and activities that are related to your site by using Hotmail calendars.

  • Adding events and tasks to calendars from a web page
    • Creating a synced-calendar link
    • Creating a single-event link
    • Creating a single-to-do item link
  • Embedding calendars in a web page
    • Calendar options

Adding events and tasks to calendars from a web page

You can create these types of Add to Calendar links:

  • Synced-calendar link

    A synced-calendar link keeps the user's calendar synchronized with your website's calendar.

  • Single-event link

    A single-event link adds a specific event or activity to a user's calendar.

  • Single-to-do-item link

    A single-to-do item link adds a new task to a user's calendar.

Creating a synced-calendar link

You can create a synced-calendar link in one of three ways:

  • Create an iCal subscription file.
  • Create a URL with which users subscribe to the iCal file.
  • Use an existing iCal-compliant file that is publicly accessible on the web.

After a user subscribes to your calendar, any changes you make to the original calendar appear in the user's calendar.

To create an iCal subscription file

  1. Go to http://www.calendar.live.com/ and sign in with your Microsoft account.
  2. From the New menu, select Calendar.
  3. In the Sharing section of the Add a new calendar page, click Edit sharing.
  4. Select the Share this calendar option.
  5. Select the Make your calendar public check box.
  6. In the Permissions list, click View details.
  7. Click Save. The calendar appears in the calendar picker on the left side of the page.
  8. You can now access the URL that is required for users to subscribe to the calendar.

To create a URL for users to subscribe to your calendar

  1. Click the name of the calendar that you created.
  2. Click the Edit sharing link.
  3. Click the Import into another calendar application link. A dialog box appears that contains the URL of your public iCal calendar.
  4. Create a link that enables users to add your calendar to theirs. The link URL must have this format: http://calendar.live.com/calendar/calendar.aspx?rru=addsubscription&url=ICAL_SUBSCRIPTION_URL&name=YOUR_CALENDAR_NAME, where ICAL_SUBSCRIPTION_URL is the URL to the iCal calendar and YOUR_CALENDAR_NAME is the calendar's name.
  5. You can now add the link to your website. When users click the link, they are presented with the option to subscribe to your calendar. Once users subscribe, their calendars are automatically kept synchronized with the calendar on your website.

Creating a single-event link

To create a single-event link, create a URL in this format.

http://calendar.live.com/calendar/calendar.aspx?rru=addevent&dtstart=START_DATE_AND_TIME&dtend=END_DATE_AND_TIME&summary=EVENT_TITLE&location=LOCATION_TEXT

The following table describes the parameters used in a single-event link's URL.

Parameter | Format | Description
START_DATE_AND_TIME | yyyymmddThhmmss | Required. Specifies the event's start date and time. For example, 20110101T120000 represents January 1, 2011, at noon. Note that the portion specifying the event time (T120000) is optional.
END_DATE_AND_TIME | yyyymmddThhmmss | Required. Specifies the event's end date and time. For example, 20110101T120000 represents January 1, 2011, at noon. Note that the portion specifying the event time (T120000) is optional.
EVENT_TITLE | escaped string | Optional. Specifies the event's title.
LOCATION_TEXT | escaped string | Optional. Specifies the event’s location text.

Top

Creating a single-to-do item link

To create a to-do item, create a URL in this format.

http://calendar.live.com/calendar/calendar.aspx?rru=addevent&summary=EVENT_TITLE&dtdue=DUE_DATE_AND_TIME

The following table describes the parameters used for to-do events.

Parameter | Format | Description
EVENT_TITLE | escaped string | Optional. Specifies the to-do event's title.
DUE_DATE_AND_TIME | yyyymmddThhmmss | Required. Specifies the due date and time of the to-do event. For example, 20110101T120000 represents January 1, 2011, at noon. Note that the portion specifying the event time (T120000) is optional.

Top

Embedding calendars in a web page

Before you embed a calendar in a web page, pick the size you want the calendar to be and whether you want the users to be able to change the view. The possible settings are described in calendar options. When you have picked the settings for the calendar you want to embed, follow this procedure to configure the calendar and create the HTML code for your web page.

To configure an embedded calendar

  1. Sign in to http://calendar.live.com using your Microsoft account.
  2. From the Share menu, select the calendar you want to share.
  3. Enable the Make your calendar public option.
  4. Click the Put on your website link. An Embed your calendar page appears, which contains the settings that control the calendar’s appearance and the actions a user can take with the calendar.
  5. Configure the settings for the embedded calendar.
  6. Copy the HTML in the Copy and paste this embed code on your webpage section.
  7. Paste the code in your web page.

Calendar options

The options available to you when you embed a calendar depend on whether you want a large calendar or a small calendar.

Large calendar options

A large calendar is 800 by 600 pixels in size, and contains the following configurable settings.

Setting | Description
View | Specifies whether the calendar shows a daily, weekly, or monthly view of dates and events.
Let users switch their view | If you select this check box, users can click a tab at the top of the calendar to switch between different views. If you clear this box, only a single view is available.
Show calendar title | If you select this check box, the calendar title is displayed above the calendar.
Language | Specifies the language you want to use for the calendar.

Small calendar options

A small calendar varies in size. It can be either 141 or 192 pixels wide and can be 428, 560, or 692 pixels in height. The following table lists the configurable settings for small calendars.

Setting | Description
Show calendar above events | If you select this check box, the calendar is displayed above upcoming events. If you clear this box, only upcoming events appear in the embedded calendar.
Width | Specifies the width of the calendar. Available options are Narrow (141 pixels wide) or Wide (192 pixels wide).
Height | Determines the height of the calendar. Available options are Short (428 pixels), Medium (560 pixels), or Tall (692 pixels).
Language | Specifies the language you want to use for the calendar.

Top


Find people in a user's contact list that be registered with your site

Important

If you are a Hotmail customer who needs help with your Hotmail account, go to Microsoft Answers—Hotmail, Windows Live Messenger & Microsoft SkyDrive or your Account overview.

This topic is for software developers and does not describe how to resolve problems with your Hotmail account. Help requests entered in this topic's Did you find this helpful dialog box will not be answered.

This topic describes how your website can determine if any contacts of a visiting user are also registered users of your website.

When a user with a Microsoft account visits your website, you can determine whether any contacts of the visiting user are also registered users of your website by using a combination of client-side JavaScript code and server-side code.

To tell if any of a user's contact are registered with your site, do this:

  • Generate a set of email-address hashes

    For each user registered with your site, you must create a hash of their email address. The hash you create must follow the format that is recognized by the Live Connect APIs, which is described in this section.

  • Get a list of email-address hashes with client-side code

    This section describes how to get list of hashes that represent the e-mail addresses of the user's contacts using code that runs in the web page on the user's computer.

  • Get a list of email-address hashes with server-side code

    This section describes how to get list of hashes that represent the e-mail addresses of the user's contacts using code that runs in the web server.

After you have the list of hashes that represent your registered users' email addresses, and the list of hashes from the e-mail addresses in the user's contacts, you can compare them to find the matches.

To fully leverage the JavaScript, C#, Objective-C, and Java code examples in this topic, you can use them in the context of larger code reference samples that we provide in Working with the code examples.

Generate a set of email-address hashes

Generate a hash that corresponds to the email address for each of your website's registered users. Each hash must be generated by following these steps:

  1. Trim leading and trailing white spaces from the email address, for example, Someone@Example.org.
  2. Trim leading and trailing white spaces from the requesting app's client ID, for example, 0000000603DB0F.
  3. Concatenate the results of steps 1 and 2, for example, Someone@Example.org0000000603DB0F.
  4. Convert the result of step 3 to lowercase, for example, someone@example.org0000000603db0f.
  5. Convert the result of step 4 to binary using UTF8 encoding.
  6. Calculate the SHA-256 value of step 5 and convert the value to its hexadecimal equivalent, for example, 6A9F...63A4. (Part of the value is omitted here for brevity.)
  7. Convert the results of step 5 to lowercase, for example, 6a9f...63a4. The result of this step is the email-address hash.

Top

Get a list of email-address hashes with client-side code

You can get a list of email addresses for a user's contacts with code like this.

Get a list of email-address hashes in JavaScript

JavaScript
function friendFinder_onClick() {
    WL.login({
        scope: "wl.basic"
    }).then(
        function (response) {
            WL.api({
                path: "me/contacts",
                method: "GET"
            }).then(
                function (response) {
                    var resultData = response.data;
                    var emailHashes = new Array;
                    for (i = 0; i < resultData.length; i++) {
                        for (j = 0; j < resultData[i].email_hashes.length; j++) {
                            emailHashes[emailHashes.length] = resultData[i].email_hashes[j];
                        }
                    }
                    var resultText = "";
                    for (k = 0; k < emailHashes.length; k++) {
                        resultText += emailHashes[k] + "\r\n";
                    }
                    document.getElementById("infoArea").setAttribute("rows", emailHashes.length);
                    document.getElementById("infoArea").value = resultText;
                },
                function (responseFailed) {
                    document.getElementById("infoArea").value =
                        "Error calling API: " + responseFailed.error.message;
                }
            );
        },
        function (responseFailed) {
            document.getElementById("infoArea").innerText =
                "Error signing in: " + responseFailed.error_description;
        }
    );
}

Get a list of email-address hashes in C# for Windows Store apps and Windows Phone apps

C#
private async void btnGetEmailHashes_Click(object sender, RoutedEventArgs e)
{
    try
    {
        LiveConnectClient liveClient = new LiveConnectClient(this.session);
        LiveOperationResult operationResult = await liveClient.GetAsync("me");
        dynamic result = operationResult.Result;
        string message = "";
        List<object> data = null;
        IDictionary<string, object> contact = null;
        List<object> emailHashes = null;
        if (result.ContainsKey("data"))
        {
            data = (List<object>)result["data"];
            for (int i = 0; i < data.Count; i++)
            {
                contact = (IDictionary<string, object>)data[i];
                if (contact.ContainsKey("email_hashes"))
                {
                    emailHashes = (List<object>)contact["email_hashes"];
                    for (int j = 0; j < emailHashes.Count; j++)
                    {
                        message += emailHashes[j].ToString() + "\r\n";
                    }
                }
            }
        }
        infoTextBlock.Text = message;
    }
    catch (LiveConnectException exception)
    {
        this.infoTextBlock.Text = "Error getting email hashes: " + exception.Message;
    }
}

[]

Get a list of email-address hashes in Objective-C for iOS

ObjectiveC
- (void) getEmailHashes
{
    [self.liveClient getWithPath:@"me/contacts"
                        delegate:self];
}

- (void) liveOperationSucceeded:(NSDictionary *)result
{
    NSArray *contacts = [result objectForKey:@"data"];
    for (NSDictionary *contact in contacts)
    {
        NSArray *emailHashes = [contact objectForKey:@"email_hashes"];
        for (NSString *emailHash in emailHashes)
        {
            self.displayLabel.text = [NSString stringWithFormat:@"%@,\n %@", self.displayLabel.text, emailHash];
        }
    }
}

Get a list of email-address hashes in Java for Android

Java
public void friendFinder() {
    final LiveOperationListener opListener = new LiveOperationListener() {
        public void onError(LiveOperationException exception, LiveOperation operation) {
               resultTextView.setText(exception.getMessage());
           }
        public void onComplete(LiveOperation operation) {
            JSONObject result = operation.getResult();
               try {
                   JSONArray contacts = result.optJSONArray("data");
                   List<String> emailHashes = new ArrayList<String>();
                   for (int i = 0; i < contacts.length(); i++) {
                      JSONObject contact = contacts.getJSONObject(i);
                      JSONArray contactEmailHashes = contact.getJSONArray("email_hashes");
                      if (contactEmailHashes != null) {
                          for (int j = 0; j < contactEmailHashes.length(); j++) {
                              emailHashes.add(contactEmailHashes.optString(j));
                          }
                      }
                  }
                  String resultText = "Email hashes:\n";
                  for (int k = 0; k < emailHashes.size(); k++) {
                      resultText += emailHashes.get(k) + "\n";
                  }
                  resultTextView.setText(resultText);
               }
               catch(JSONException ex) {
                   resultTextView.setText("Error getting email hashes: " + ex.getMessage());
               }
        }
       };
    auth.login(this, Arrays.asList(new String[] { "wl.basic" }),
        new LiveAuthListener() {
               public void onAuthError(LiveAuthException exception, Object userState) {
                   resultTextView.setText("Error signing in: " + exception.getMessage());
               }
            public void onAuthComplete(LiveStatus status, LiveConnectSession session, Object userState) {
                client.getAsync("me/contacts", opListener);
               }
        }
    );
}

Top

Get a list of email-address hashes with server-side code

If a user signs in and consents to a wl.basic scope request, and you have an access token that corresponds to this request, you can retrieve a list of the user's contacts. For each email address that is available for a given contact, an email-address hash is displayed. You can extract the email-address hash by using your preferred coding language and platform. To get the list of email-address hashes, make a server-side HTTP GET call with REST and the following request parameters.

https://apis.live.net/v5.0/me/contacts?access_token=ACCESS_TOKEN

In the preceding code examples, replace ACCESS_TOKEN with your access token string.

The JavaScript Object Notation (JSON)-formatted response collection will look similar to the following. (Ellipses are displayed in place of information that is omitted for brevity.)

{
   "data": [
      {
         "id": "contact.b4466224b2ca42798c3d4ea90c75aa56",
         "first_name": "Henrik",
         "last_name": "Jensen",
         ...
         "email_hashes": [
            "9ecdb19f4eb8e04304c5d1280368c42e85b6e4fe39f08b0c837ec592b905a620",
            "fc05492f50da6488aa14dcf221d395bcb29a4e43b43b250d60c68df4f831cad3"
         ],
         ...
      }, {
         ...
      }
   ]
}

For more information about how to make server-side HTTP calls with REST, see Server-side scenarios.

Top


SkyDrive API

Try out code samples

Your apps can work with a Microsoft SkyDrive user's folders, files, albums, photos, videos, audio, tags, and comments by using the Live Connect APIs.

In this section

Topic | Description
Common tasks | How to do common tasks when accessing a user's SkyDrive contents from your app.
Folders and files | How to create, read, update, and delete folders and files from a user's SkyDrive.
Albums, photos, videos, audio, and tags | How to create, read, update, and delete albums, photos, videos, and audio from a user's SkyDrive.
Comments | How to read, delete, and create comments associated with the folders, files, albums, photos, and videos in a user's SkyDrive.
File picker for web apps | How to include a file picker in your web page or web app that provides a consistent UI to upload and download files to and from a user's SkyDrive.
SkyDrive core concepts | The concepts used when discussing how to access a user's SkyDrive contents from your app.

Guidelines for apps that interact with SkyDrive

Apps that interact with SkyDrive must conform to these principles:

  • Upload files to SkyDrive only in response to an explicit user request or choice. Your apps must always ensure that a user intentionally chooses to save any new data to SkyDrive. Apps must not upload files to SkyDrive automatically without a user making an explicit choice to upload those files.

    Here are some examples of conforming apps:

    • Apps that display an "Upload to SkyDrive" or "Share on SkyDrive" button that a user must click before each upload of a photo, video, document, or other file.
    • Document-editing apps that require a user to click an "Upload to SkyDrive" button initially, so that the app can save that document later without further user interaction.

    Here are some examples of nonconforming apps:

    • Apps that automatically upload to SkyDrive any file added to a specific location on a user’s devices.
    • Apps that automatically back up files or folders to SkyDrive.
  • Use SkyDrive for the things that it’s good at. SkyDrive includes features both for high-quality document viewing and editing, and for creating and sharing beautiful photo albums. If possible, have your apps take advantage of these features.

  • Don't undermine trust in SkyDrive. Over the years that SkyDrive has been available, users have come to trust it. Preserving that trust is critical and your apps must not undermine it by doing things that users don’t expect, especially with regard to data privacy.

    Here are some examples of conforming apps:

    • Apps that upload documents or photos to SkyDrive with user-only access as the default.
    • Apps that warn users that, when the users send a link to their content stored on SkyDrive, anyone who receives that link can read the associated files.

    Here is an example of a nonconforming app:

    • An app that makes all shared files in SkyDrive publicly accessible by default, without clearly communicating this behavior to users.

Top

See also

  • Video: The complete developer’s guide to the SkyDrive API

    Learn how you can easily enable your users to read and write documents, photos, and other files to and from their SkyDrive account using simple Representational State Transfer (REST) API calls.

  • ExcelMashup.com

    Learn how to develop rich, interactive mashups on your web site using this Microsoft Excel Web App on SkyDrive.


Common tasks in accessing Microsoft SkyDrive from your app

In this article

  • Traversing the SkyDrive directory
  • Getting a list of SkyDrive objects that are shared with the signed-in user
  • Using friendly names to access certain SkyDrive folders
  • Getting a list of the user's most recently used documents
  • Getting a user's total and remaining SkyDrive storage quota
  • Displaying a preview of a SkyDrive item

This topic describes how to do common tasks when accessing a user's Microsoft SkyDrive contents from your app.

Traversing the SkyDrive directory

To use the Live Connect APIs to get info about a user's top-level folder in the SkyDrive directory, you make a request to me/skydrive or USER_ID/skydrive. Here's how to make this call:

  • In Representational State Transfer (REST), use GET.
  • In JavaScript, use the WL.api function, specifying a method parameter of "GET".
  • In C#, use the LiveConnectClient.GetAsync method.
  • In Objective-C, use the LiveConnectClient getWithPath method.
  • In Java, use the LiveConnectClient.getAsync method.

In the JavaScript Object Notation (JSON)-formatted object that's returned, two structures are important to note: the id structure that represents the top-level folder's folder ID, and the upload_location structure that represents the location for the top-level folder to which you can upload files, photos, videos, and audios.

If you make a request to me/skydrive/files or USER_ID/skydrive/files, the JSON-formatted object that's returned contains info about all of the child folders, child albums, and files in the user's top-level folder only.

From there, you can traverse a user's entire SkyDrive directory by making a request with FOLDER_ID/files or ALBUM_ID/files, where FOLDER_ID or ALBUM_ID represents the id structure that corresponds to a folder ID or album ID, respectively, anywhere in the directory.

As with a user's top-level SkyDrive folder, you can use the upload_location structure for any folder or album to upload files to that folder or album. Additionally, you can use the upload_location structure for any file, photo, video, or audio to overwrite the contents of that file, photo, video, or audio.

For example, here's what a user's SkyDrive directory might look like conceptually.

GET https://apis.live.net/v5.0/me/skydrive?access_token=ACCESS_TOKEN
---
200 OK
{
    "id": "folder.a6b2a7e8f2515e5e",
    ...
    "upload_location": "https://apis.live.net/v5.0/folder.a6b2a7e8f2515e5e/files",
    ...
    "type": "folder",
    ...
}
---
GET https://apis.live.net/v5.0/folder.a6b2a7e8f2515e5e/files?access_token=ACCESS_TOKEN
---
200 OK
{
    "data": [
        {
            "id": "folder.a6b2a7e8f2515e5e.A6B2A7E8F2515E5E!110",
            ...
            "upload_location": "https://apis.live.net/v5.0/folder.a6b2a7e8f2515e5e.A6B2A7E8F2515E5E!110/files/"
            ...
            "type": "folder",
            ...
        }, {
            "id": "photo.a6b2a7e8f2515e5e.A6B2A7E8F2515E5E!131",
            ...
            "upload_location": "https://apis.live.net/v5.0/photo.a6b2a7e8f2515e5e.A6B2A7E8F2515E5E!131/content/",
            ...
            "type": "photo",
            ...
        }, {
            "id": "file.a6b2a7e8f2515e5e.A6B2A7E8F2515E5E!119",
            ...
            "upload_location": "https://apis.live.net/v5.0/file.a6b2a7e8f2515e5e.A6B2A7E8F2515E5E!119/content/",
            ...
            "type": "file",
            ...
        }
    ]
}

Top

Getting a list of SkyDrive objects that are shared with the signed-in user

To discover all SkyDrive objects that are shared with the signed-in user, use the wl.contacts_skydrive scope to make a GET request to /USER_ID/skydrive/shared, where USER_ID is either me or the user ID of the consenting user. Here's an example.

GET https://apis.live.netv5.0/me/skydrive/shared?access_token=ACCESS_TOKEN

Note Creating, updating, or deleting files in a folder that is shared with the signed-in user is not supported by the SkyDrive API. Apps can only manipulate files that are owned by the signed-in user.

Important We don't support third-party apps that upload files to shared folders.

Top

Using friendly names to access certain SkyDrive folders

To access certain SkyDrive folders, you can use friendly names instead of folder IDs. Use the following friendly names to access these corresponding folders in the SkyDrive UI:

  • USER_ID/skydrive/camera_roll represents the SkyDrive camera roll folder.
  • USER_ID/skydrive/my_documents represents the Documents folder.
  • USER_ID/skydrive/my_photos represents the Pictures folder.
  • USER_ID/skydrive/public_documents represents the Public folder.

In each case, replace USER_ID with either me for the signed-in user or a user ID for any other consenting user.

For example, reading the Documents folder's properties with a REST API call to the folder's ID looks like this.

GET https://apis.live.netv5.0/folder.a6b2a7e8f2515e5e.A6B2A7E8F2515E5E!110?access_token=ACCESS_TOKEN

But you can also read the Documents folder's properties with a REST API call to the folder's friendly name, like this:

GET https://apis.live.netv5.0/me/skydrive/my_documents?access_token=ACCESS_TOKEN

Note To move or copy a file into a folder with a friendly name, you provide only the friendly name as the value of the destination structure. Here's an example of how to call the REST API to move a file into the Documents folder.

MOVE https://apis.live.net/v5.0/file.a6b2a7e8f2515e5e.A6B2A7E8F2515E5E!126

Authorization: Bearer ACCESS_TOKEN
Content-Type: application/json

{
    "destination": "my_documents"
}

Top

Getting a list of the user's most recently used documents

To get a list of SkyDrive documents that the user has most recently used, use the wl.skydrive scope to make a GET request to /USER_ID/skydrive/recent_docs, where USER_ID is either me or the user ID of the consenting user. Here's an example.

GET https://apis.live.netv5.0/me/skydrive/recent_docs?access_token=ACCESS_TOKEN

Top

Getting a user's total and remaining SkyDrive storage quota

To get info about a user's available and unused storage space in SkyDrive, make a GET call to /me/skydrive/quota or /USER_ID/skydrive/quota, where USER_ID is the signed-in user's ID. Here's an example using the REST API.

GET https://apis.live.netv5.0/me/skydrive/quota?access_token=ACCESS_TOKEN

The JSON-formatted object that's returned looks like this.

{
    "quota": 26843545600,
    "available": 26805319016
}

In the preceding example, the quota field is the user's total available storage space, in bytes; the available field is the user's remaining unused storage space, also in bytes.

Tip Before uploading a file, have your app check to make sure that there is enough available storage space. For example, your app could get the size of the file in bytes and then compare it to the number of bytes in the available field. If the file size is greater than the available field, your app should not try to upload the file. If your app tries to upload the file anyway, the upload request will fail and SkyDrive will return the following error.

{
    "error": {
        "code": "resource_quota_exceeded",
        "message": "The user has reached his or her storage quota limit."
    }
}

Top

Displaying a preview of a SkyDrive item

To display a preview of an item in SkyDrive, make a GET request to /skydrive/get_item_preview?type=TYPE&url=URL. The optional type query-string parameter is one of the following: thumbnail, small (to get a maximum 100 × 100-pixel preview), album (maximum 200 × 200), or normal (maximum 800 × 800). The required url query-string parameter is a shared link to the item in SkyDrive. Here are two examples, one using a longer SkyDrive URL and one using a shorter sdrv.ms URL (sdrv.ms is a URL-shortening service that's unique to SkyDrive).

GET https://apis.live.net/v5.0/skydrive/get_item_preview?type=normal&url=https%3A%2F%2Fskydrive.live.com%2Fredir.aspx%3Fcid%3Da6b2a7e8f2515e5e%26amp%3Bresid%3DA6B2A7E8F2515E5E!132%26amp%3Bparid%3DA6B2A7E8F2515E5E!110%26amp%3Bauthkey%3D!ACuMMo37Ju8_xw0x

GET https://apis.live.net/v5.0/skydrive/get_item_preview?type=normal&url=http%3A%2F%2Fsdrv.ms%2FLTIvcyx

Note the following:

  • To make the get_item_preview request, you don't need to request any scopes or provide an access token.
  • If the item is not a photo, and a preview is associated with the item, a thumbnail preview is displayed and the type parameter is ignored even if provided.
  • If a particular size of preview doesn't exist, the next-largest size preview that's available is displayed. If no preview is associated with the item, a 404 (Not Found) error is returned.
  • You can get a shared link to an item in one of three ways:
    • Make a GET request to ITEM_ID/shared_read_link, where ITEM_ID is the SkyDrive item's ID. Here's an example.
      GET https://apis.live.netv5.0/file.a6b2a7e8f2515e5e.A6B2A7E8F2515E5E!131/shared_read_link?access_token=ACCESS_TOKEN
      You can find the shared link value in the JSON-formatted response object's link structure.
    • In the SkyDrive UI, select the item, and then click Share. Click Get a link and then, next to View only, click Create. SkyDrive displays the shared link value, which you can use in your get_item_preview request. The value should look something like this: https://skydrive.live.com/redir.aspx?cid=a6b2a7e8f2515e5e&resid=A6B2A7E8F2515E5E!132&parid=A6B2A7E8F2515E5E!110&authkey=!ACuMMo37Ju8_xw0x.
    • In the SkyDrive UI, select the item, and then click Share. Click Post to Twitter, follow the on-screen directions, and then click Post. The newly created Twitter post includes the shared link value, which you can use in your get_item_preview request. The value should look something like this: http://sdrv.ms/LTIvcyx.
  • The url query-string parameter's value must be URL-encoded. For example, use %3A for the colon (":") character, %2F for the forward slash ("/") character, %3F for the question mark ("?") character, and %26 for the ampersand ("&") character.

Top


Working with Microsoft SkyDrive folders and files

Your apps can use the Live Connect APIs to create, read, update, and delete a Microsoft SkyDrive user's folders and files.

Note In this context, a file represents a file of any supported format, including a photo, video, or audio. A folder can contain child folders and files. (An album is a special type of folder; for more info, see Albums, photos, videos, audio, and tags.)

Your apps can also use the APIs to get a link to an uploaded file. Then you can share this link with others so that they can access the file directly.

  • Reading folder properties
  • Deleting folders
  • Creating folders
  • Updating folder properties
  • Reading file properties
  • Updating file properties
  • Downloading files
  • Uploading files
  • Updating uploaded files
  • Deleting uploaded files
  • Getting links to folders and files
  • Moving folders and files
  • Copying files

To make full use of the code examples in this topic, you can use them in the context of larger code reference samples that we provide in Working with the code examples. To request the required scopes, see the code patterns in Obtaining user consent.

Reading folder properties

To get info about a folder, use code like this. The wl.skydrive scope is required.

[JavaScript for Windows Store apps and HTML]

JavaScript
function readFolderProperties_onClick() {
    WL.login({
        scope: "wl.skydrive"
    }).then(
        function (response) {
            WL.api({
                path: "folder.a6b2a7e8f2515e5e.A6B2A7E8F2515E5E!164",
                method: "GET"
            }).then(
                function (response) {
                    document.getElementById("infoArea").innerText =
                        "Folder properties: name = " + response.name + ", ID = " + response.id;
                },
                function (responseFailed) {
                    document.getElementById("infoArea").innerText =
                        "Error reading folder properties: " + responseFailed.error.message;
                }
            );
        },
        function (responseFailed) {
            document.getElementById("infoArea").innerText =
                "Error signing in: " + responseFailed.error_description;
        }
    );
}

[C# for Windows Store apps and Windows Phone apps]

C#
private async void btnReadFolder_Click(object sender, RoutedEventArgs e)
{
    try
    {
        LiveConnectClient liveClient = new LiveConnectClient(this.session);
        LiveOperationResult operationResult =
            await liveClient.GetAsync("folder.8c8ce076ca27823f.8C8CE076CA27823F!126");
        dynamic result = operationResult.Result;
        infoTextBlock.Text = "Folder name: " + result.name + ", ID: " + result.id;
    }
    catch (LiveConnectException exception)
    {
        infoTextBlock.Text = "Error getting folder info: " + exception.Message;
    }
}

[Objective-C for iOS]

ObjectiveC
- (void) getFolderInfo
{
    NSString *folderId = @"folder.2e82e8a5445fe036";
    [self.liveClient getWithPath:folderId
                        delegate:self
                       userState:@"get folder"];
}

- (void) liveOperationSucceeded:(LiveOperation *)operation
{
    if ([operation.userState isEqual:@"get folder"]) {
        self.folderIdLabel.text = [operation.result objectForKey:@"id"];
        self.folderNameLabel.text = [operation.result objectForKey:@"name"];
        self.folderUploadPathLabel.text = [operation.result objectForKey:@"upload_location"];
        self.folderLinkLabel.text = [operation.result objectForKey:@"link"];
        self.folderTypeLabel.text = [operation.result objectForKey:@"type"];
    };
}

- (void) liveOperationFailed:(NSError *)error
                   operation:(LiveOperation *)operation
{
    if ([operation.userState isEqual:@"get folder"]) {
        self.statusLabel.text = @"The request to read the SkyDrive folder information failed.";
    };
}

[Java for Android]

Java
public void readFolder() {
    client.getAsync("folder.a6b2a7e8f2515e5e.A6B2A7E8F2515E5E!125", new LiveOperationListener() {
        public void onComplete(LiveOperation operation) {
            JSONObject result = operation.getResult();
            resultTextView.setText("Folder ID = " + result.optString("id") +
                ", name = " + result.optString("name"));
        }
        public void onError(LiveOperationException exception, LiveOperation operation) {
            resultTextView.setText("Error reading folder: " + exception.getMessage());
        }
    });
}

[REST]

GET https://apis.live.netv5.0/folder.a6b2a7e8f2515e5e.A6B2A7E8F2515E5E!114?access_token=ACCESS_TOKEN

In the preceding code, change the folder ID to this:

  • A different folder ID, to get info about another folder.
  • FOLDER_ID/files, where FOLDER_ID represents a valid folder ID, to get a list of all items in a folder. Your code can check to see whether any of these items has its type structure set to folder. Then your code can make another call that uses the item's folder ID to get that folder's info, too.

You can also do this:

  • Get info about a user's top-level folder in the SkyDrive directory. To do this, replace the folder ID with me/skydrive (or USER_ID/skydrive).
  • Get info about certain folders by using their friendly names. To do this, use me/skydrive/FRIENDLY_FOLDER_NAME or USER_ID/skydrive/FRIENDLY_FOLDER_NAME, where me represents the current consenting user, USER_ID represents the consenting user's ID, and FRIENDLY_FOLDER_NAME represents an allowed friendly folder name such as my_documents (which represents the Documents folder). For more info, see the SkyDrive core concepts topic's "Use friendly names to access certain SkyDrive folders" section.
  • Get only certain types of items by using the filter parameter in the preceding code and specifying the item type: all (default), photos, videos, audio, folders, or albums. For example, to get only photos, use FOLDER_ID/files?filter=photos.
  • Get a limited number of items by using the limit parameter in the preceding code to specify the number of items to get. For example, to get the first two items, use FOLDER_ID/files?limit=2.
  • Specify the first item to get by setting the offset parameter in the preceding code to the index of the first item that you want to get. For example, to get two items starting with the third item, use FOLDER_ID/files?limit=2&offset=3.

    Note In the JavaScript Object Notation (JSON)-formatted object that's returned, you can look in the paging object for the previous and next structures, if they apply, to get the offset and limit parameter values of the previous and next entries, if they exist.

  • Set the items' sort criteria by using the sort_by parameter in the preceding code to specify the following criteria: created, updated, name, size, or default. For example, to sort the items by name, use FOLDER_ID/files?sort_by=name.
  • Set the items' sort order by using the sort_order parameter in the preceding code to specify the order: ascending or descending. For example, to sort the items in descending order, use FOLDER_ID/files?sort_order=descending.

Top

Deleting folders

To remove a folder, use code like this. The wl.skydrive_update scope is required.

[JavaScript for Windows Store apps and HTML]

JavaScript
function deleteFolder_onClick() {
    WL.login({
        scope: "wl.skydrive_update"
    }).then(
        function (response) {
            WL.api({
                path: "folder.a6b2a7e8f2515e5e.A6B2A7E8F2515E5E!164",
                method: "DELETE"
            }).then(
                function (response) {
                    document.getElementById("infoArea").innerText = "Deleted folder";
                },
                function (responseFailed) {
                    document.getElementById("infoArea").innerText =
                        "Error calling API: " + responseFailed.error.message;
                }
            );
        },
        function (responseFailed) {
            document.getElementById("infoArea").innerText =
                "Error signing in: " + responseFailed.error_description;
        }
    );
}

[C# for Windows Store apps and Windows Phone apps]

C#
private async void btnDeleteFolder_Click(object sender, RoutedEventArgs e)
{
    try
    {
        LiveConnectClient liveClient = new LiveConnectClient(this.session);
        LiveOperationResult operationResult =
            await liveClient.DeleteAsync("folder.a6b2a7e8f2515e5e.A6B2A7E8F2515E5E!147");
        this.infoTextBlock.Text = "Folder deleted.";
    }
    catch (LiveConnectException exception)
    {
        this.infoTextBlock.Text = "Error deleting folder: " + exception.Message;
    }
}

[Objective-C for iOS]

ObjectiveC
-(void) deleteFolder
{
    [self.liveClient deleteWithPath:@"folder.95d463b9efcca0e1.95D463B9EFCCA0E1!108"
                           delegate:self];
}

- (void) liveOperationSucceeded:(LiveOperation *)operation
{
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"API call successful!"
                                                    message:@"Folder deleted successfully"
                                                   delegate:self
                                          cancelButtonTitle:@"Ok"
                                          otherButtonTitles:nil,
                          nil];
    [alert show];
    [alert release];
}

[Java for Android]

Java
public void deleteFile() {
    final String fileId = "file.a6b2a7e8f2515e5e.A6B2A7E8F2515E5E!125";
    client.deleteAsync(fileId, new LiveOperationListener() {
        public void onError(LiveOperationException exception, LiveOperation operation) {
               resultTextView.setText("Error deleting file: " + exception.getMessage());
           }
           public void onComplete(LiveOperation operation) {
            resultTextView.setText("File deleted.");
           }
       });

}

[REST]

DELETE https://apis.live.netv5.0/folder.a6b2a7e8f2515e5e.A6B2A7E8F2515E5E!114?access_token=ACCESS_TOKEN

In the preceding code, change the folder ID to the folder ID (or, in certain cases, the friendly name) of the folder that you want to remove.

Top

Creating folders

To add a new folder, use code like this. The wl.skydrive_update scope is required.

[JavaScript for Windows Store apps and HTML]

JavaScript
function createFolder_onClick() {
    WL.login({
        scope: "wl.skydrive_update"
    }).then(
        function (response) {
            WL.api({
                path: "me/skydrive",
                method: "POST",
                body: {
                    "name": "This is a new folder",
                    "description": "A new folder"
                }
            }).then(
                function(response) {
                    document.getElementById("infoArea").innerText =
                        "Created folder. Name: " + response.name + ", ID: " + response.id;
                },
                function (responseFailed) {
                    document.getElementById("infoArea").innerText =
                        "Error calling API: " + responseFailed.error.message;
                }
            );
        },
        function (responseFailed) {
            document.getElementById("infoArea").innerText =
                "Error signing in: " + responseFailed.error_description;
        }
    );
}

[C# for Windows Store apps and Windows Phone apps]

C#
private async void btnCreateFolder_Click(object sender, RoutedEventArgs e)
{
    try
    {
        var folderData = new Dictionary<string, object>();
        folderData.Add("name", "A brand new folder was created");
        LiveConnectClient liveClient = new LiveConnectClient(this.session);
        LiveOperationResult operationResult =
            await liveClient.PostAsync("me/skydrive", folderData);
        dynamic result = operationResult.Result;
        this.infoTextBlock.Text = string.Join(" ", "Created folder:", result.name, "ID:", result.id);
    }
    catch (LiveConnectException exception)
    {
        this.infoTextBlock.Text = "Error creating folder: " + exception.Message;
    }
}

[Objective-C for iOS]

ObjectiveC
-(void) createFolder
{
    NSDictionary * newFolder = [[NSDictionary dictionaryWithObjectsAndKeys:
                                 @"Vacation Pics",@"name",
                                 @"Family vacation",@"description",
                                 @"folder",@"type",
                                 nil] retain];
    [self.liveClient postWithPath:@"me/skydrive"
                         dictBody:newFolder
                         delegate:self];
    [newFolder release];
}

- (void) liveOperationSucceeded:(LiveOperation *)operation
{
    NSString *folderId = [operation.result objectForKey:@"id"];
    NSString *folderName = [operation.result objectForKey:@"name"];
    NSString *folderDescription = [operation.result objectForKey:@"description"];
    NSString *folderLink = [operation.result objectForKey:@"link"];
    NSString *folderType = [operation.result objectForKey:@"type"];
    self.displayLabel.text = [NSString stringWithFormat:
                              @"Folder Properties:\n"
                              @"\tId. %@\n"
                              @"\tName. %@\n"
                              @"\tDescription. %@\n"
                              @"\tLink. %@\n"
                              @"\tType. %@\n"
                              , folderId,
                              folderName,
                              folderDescription,
                              folderLink,
                              folderType];
}

[Java for Android]

Java
public void createFolder() {
    final LiveOperationListener opListener = new LiveOperationListener() {
        public void onError(LiveOperationException exception, LiveOperation operation) {
               resultTextView.setText("Error creating folder: " + exception.getMessage());
           }
        public void onComplete(LiveOperation operation) {
            JSONObject result = operation.getResult();
            String text = "Folder created:\n" +
                "\nID = " + result.optString("id") +
                "\nName = " + result.optString("name");
               resultTextView.setText(text);
           }
       };
    auth.login(this, Arrays.asList(new String[] { "wl.skydrive_update" }),
        new LiveAuthListener() {
               public void onAuthError(LiveAuthException exception, Object userState) {
                   resultTextView.setText("Error signing in: " + exception.getMessage());
               }
            public void onAuthComplete(LiveStatus status, LiveConnectSession session, Object userState) {
                try {
                    JSONObject body = new JSONObject();
                    body.put("name", "MyBrandNewFolder");
                    body.put("description", "My brand new folder");
                       client.postAsync("me/skydrive", body, opListener);
                }
                catch(JSONException ex) {
                    resultTextView.setText("Error building folder: " + ex.getMessage());
                }
               }
        }
    );
}

[REST]

POST https://apis.live.net/v5.0/me/skydrive

Authorization: Bearer ACCESS_TOKEN
Content-Type: application/json

{
    "name": "My example folder"
}

In the preceding code, you can change me/skydrive to the folder ID (or, in certain cases, the friendly name) of the folder in which the new folder will be created.

For details about the minimum required and optional structures that your app must provide to use POST, see the "Folder object" section in REST reference.

Top

Updating folder properties

To change info for an existing folder, use code like this. The wl.skydrive_update scope is required.

[JavaScript for Windows Store apps and HTML]

JavaScript
function updateFolderProperties_onClick() {
    WL.login({
        scope: "wl.skydrive_update"
    }).then(
        function (response) {
            WL.api({
                path: "folder.a6b2a7e8f2515e5e.A6B2A7E8F2515E5E!164",
                method: "PUT",
                body: {
                    name: "A different folder name"
                }
            }).then(
                function (response) {
                    document.getElementById("infoArea").innerText =
                        "Updated folder. Name: " + response.name + ", ID: " + response.id;
                },
                function (responseFailed) {
                    document.getElementById("infoArea").innerText =
                         "Error calling API: " + responseFailed.error.message;
                }
            );
        },
        function (responseFailed) {
            document.getElementById("infoArea").innerText =
                "Error signing in: " + responseFailed.error_description;
        }
    );
}

[C# for Windows Store apps and Windows Phone apps]

C#
private async void btnUpdateFolder_Click(object sender, RoutedEventArgs e)
{
    try
    {
        var folderData = new Dictionary<string, object>();
        folderData.Add("name", "Wildlife Pictures 5");
        LiveConnectClient liveClient = new LiveConnectClient(this.session);
        LiveOperationResult operationResult =
            await liveClient.PutAsync("folder.8c8ce076ca27823f.8C8CE076CA27823F!126", folderData);
        dynamic result = operationResult.Result;
        this.infoTextBlock.Text = "Folder updated: " + result.name;
    }
    catch (LiveConnectException exception)
    {
        this.infoTextBlock.Text = "Error updating folder: " + exception.Message;
    }
}

[Objective-C for iOS]

ObjectiveC
-(void) updateFolder
{
    NSDictionary * updatedFolder = [[NSDictionary dictionaryWithObjectsAndKeys:
                                     @"Family vacation in the snow",@"description",
                                     nil] retain];
    [self.liveClient putWithPath:@"folder.95d463b9efcca0e1.95D463B9EFCCA0E1!112"
                        dictBody:updatedFolder
                        delegate:self];
    [updatedFolder release];
}

- (void) liveOperationSucceeded:(LiveOperation *)operation
{
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"API call successful!"
                                                    message:@"Album updated successfully"
                                                   delegate:self
                                          cancelButtonTitle:@"Ok"
                                          otherButtonTitles:nil,
                          nil];
    [alert show];
    [alert release];
}

[Java for Android]

Java
public void updateFolder() {
    final String folderId = "folder.a6b2a7e8f2515e5e.A6B2A7E8F2515E5E!125";
    final LiveOperationListener opListener = new LiveOperationListener() {
        public void onError(LiveOperationException exception, LiveOperation operation) {
               resultTextView.setText("Error updating folder: " + exception.getMessage());
           }
        public void onComplete(LiveOperation operation) {
            JSONObject result = operation.getResult();
            String text = "Folder updated:\n" +
                "\nID = " + result.optString("id") +
                "\nName = " + result.optString("name");
               resultTextView.setText(text);
           }
       };
    auth.login(this, Arrays.asList(new String[] { "wl.skydrive_update" }),
        new LiveAuthListener() {
               public void onAuthError(LiveAuthException exception, Object userState) {
                   resultTextView.setText("Error signing in: " + exception.getMessage());
               }
            public void onAuthComplete(LiveStatus status, LiveConnectSession session, Object userState) {
                try {
                    JSONObject body = new JSONObject();
                    body.put("name", "MyFolderIsUpdated");
                    body.put("description", "My folder is updated");
                    client.putAsync(folderId, body, opListener);
                }
                catch(JSONException ex) {
                    resultTextView.setText("Error updating folder: " + ex.getMessage());
                }
            }
        }
    );
}

[REST]

PUT https://apis.live.net/v5.0/folder.a6b2a7e8f2515e5e.A6B2A7E8F2515E5E!114

Authorization: Bearer ACCESS_TOKEN
Content-Type: application/json

{
    "name": "My example folder has changed"
}

In the preceding code, change the folder ID to the folder ID (or, in certain cases, the friendly name) of the folder that you want to change.

For details about the minimum required and optional structures that your app must provide to use PUT, see the "Folder object" section in REST reference.

Top

Reading file properties

To get info about a file, photo, video, or audio, use code like this. The wl.skydrive scope is required.

[JavaScript for Windows Store apps and HTML]

JavaScript
function readFileProperties_onClick() {
    WL.login({
        scope: "wl.skydrive"
    }).then(
        function (response) {
            WL.api({
                path: "file.a6b2a7e8f2515e5e.A6B2A7E8F2515E5E!152",
                method: "GET"
            }).then(
                function (response) {
                    document.getElementById("infoArea").innerText =
                        "File properties: name = " + response.name + ", ID = " + response.id;
                },
                function (responseFailed) {
                    document.getElementById("infoArea").innerText =
                        "Error calling API: " + responseFailed.error.message;
                }
            );
        },
        function (responseFailed) {
            document.getElementById("infoArea").innerText =
                "Error signing in: " + responseFailed.error_description;
        }
    );
}

[C# for Windows Store apps and Windows Phone apps]

C#
private async void btnReadFile_Click(object sender, RoutedEventArgs e)
{
    try
    {
        LiveConnectClient liveClient = new LiveConnectClient(this.session);
        LiveOperationResult operationResult =
            await liveClient.GetAsync("file.8c8ce076ca27823f.8C8CE076CA27823F!129");
        dynamic result = operationResult.Result;
        this.infoTextBlock.Text = string.Join(" ", "File name:", result.name, "ID:", result.id);
    }
    catch (LiveConnectException exception)
    {
        this.infoTextBlock.Text = "Error getting file info: " + exception.Message;
    }
}

[Objective-C for iOS]

ObjectiveC
-(void) getFileProperties
{
    [self.liveClient getWithPath:@"file.95d463b9efcca0e1.95D463B9EFCCA0E1!113"
                        delegate:self];
}

- (void) liveOperationSucceeded:(LiveOperation *)operation
{
    NSString *fileId = [operation.result objectForKey:@"id"];
    NSString *fileName = [operation.result objectForKey:@"name"];
    NSString *fileDescription = [operation.result objectForKey:@"description"];
    NSString *fileSize = [operation.result objectForKey:@"size"];
    self.displayLabel.text = [NSString stringWithFormat:
                              @"File Properties:\n"
                              @"\tId. %@\n"
                              @"\tName. %@\n"
                              @"\tDescription. %@\n"
                              @"\tSize. %@\n"
                              , fileId,
                              fileName,
                              fileDescription,
                              fileSize];
}

[Java for Android]

Java
public void readFile() {
    String fileId =  "file.a6b2a7e8f2515e5e.A6B2A7E8F2515E5E!141";
       client.getAsync(fileId, new LiveOperationListener() {
        public void onError(LiveOperationException exception, LiveOperation operation) {
               resultTextView.setText("Error reading file: " + exception.getMessage());
           }
           public void onComplete(LiveOperation operation) {
            JSONObject result = operation.getResult();
            String text = "File info:" +
                "\nID = " + result.optString("id") +
                "\nName = " + result.optString("name");
               resultTextView.setText(text);
           }
       });
}

[REST]

GET https://apis.live.netv5.0/file.a6b2a7e8f2515e5e.A6B2A7E8F2515E5E!126?access_token=ACCESS_TOKEN

In the preceding code, change the file ID to a different file ID, photo ID, video ID, or audio ID to get info about a different file, photo, video, or audio.

Top

Updating file properties

To change info about a file, photo, video, or audio, use code like this. The wl.skydrive_update scope is required.

[JavaScript for Windows Store apps and HTML]

JavaScript
function updateFileProperties_onClick() {
    WL.login({
        scope: "wl.skydrive_update"
    }).then(
        function (response) {
            WL.api({
                path: "file.a6b2a7e8f2515e5e.A6B2A7E8F2515E5E!152",
                method: "PUT",
                body: {
                    name: "AnotherOneNoteNotebook"
                }
            }).then(
                function (response) {
                    document.getElementById("infoArea").innerText =
                        "Updated file properties. Name: " + response.name + ", ID: " + response.id;
                },
                function (responseFailed) {
                    document.getElementById("infoArea").innerText =
                        "Error calling API: " + responseFailed.error.message;
                }
            );
        },
        function (responseFailed) {
            document.getElementById("infoArea").innerText =
                "Login error.";
        }
    );
}

[C# for Windows Store apps and Windows Phone apps]

C#
private async void btnUpdateFile_Click(object sender, RoutedEventArgs e)
{
    try
    {
        var fileData = new Dictionary<string, object>();
        fileData.Add("name", "Tulips20.jpg");
        LiveConnectClient liveClient = new LiveConnectClient(this.session);
        LiveOperationResult operationResult =
            await liveClient.PutAsync("file.8c8ce076ca27823f.8C8CE076CA27823F!129", fileData);
        this.infoTextBlock.Text = "File renamed.";
    }
    catch (LiveConnectException exception)
    {
        this.infoTextBlock.Text = "Error renaming file: " + exception.Message;
    }
}

[Objective-C for iOS]

ObjectiveC
-(void) updateFileProperty
{
    NSDictionary * updatedFile = [[NSDictionary dictionaryWithObjectsAndKeys:
                                   @"Having fun at the beach",@"description",
                                   nil] retain];
    [self.liveClient putWithPath:@"file.95d463b9efcca0e1.95D463B9EFCCA0E1!113"
                        dictBody:updatedFile
                        delegate:self];
    [updatedFile release];
}

- (void) liveOperationSucceeded:(LiveOperation *)operation
{
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"API call successful!"
                                                    message:@"File updated successfully"
                                                   delegate:self
                                          cancelButtonTitle:@"Ok"
                                          otherButtonTitles:nil,
                          nil];
    [alert show];
    [alert release];
}

[Java for Android]

Java
public void updateFile() {
    final String fileId = "file.a6b2a7e8f2515e5e.A6B2A7E8F2515E5E!141";
    final LiveOperationListener opListener = new LiveOperationListener() {
        public void onError(LiveOperationException exception, LiveOperation operation) {
               resultTextView.setText("Error updating file: " + exception.getMessage());
           }
        public void onComplete(LiveOperation operation) {
            JSONObject result = operation.getResult();
            String text = "File updated:" +
                "\nID = " + result.optString("id") +
                "\nName = " + result.optString("name");
               resultTextView.setText(text);
           }
       };
    auth.login(this, Arrays.asList(new String[] { "wl.skydrive_update" }),
        new LiveAuthListener() {
               public void onAuthError(LiveAuthException exception, Object userState) {
                   resultTextView.setText("Error signing in: " + exception.getMessage());
               }
            public void onAuthComplete(LiveStatus status, LiveConnectSession session, Object userState) {
                try {
                    JSONObject body = new JSONObject();
                    body.put("name", "weather.txt");
                    body.put("description", "Local weather");
                       client.putAsync(fileId, body, opListener);
                }
                catch(JSONException ex){
                    resultTextView.setText("Error signing in: " + ex.getMessage());
                }
               }
        }
    );
}

[REST]

PUT https://apis.live.net/v5.0/file.a6b2a7e8f2515e5e.A6B2A7E8F2515E5E!126

Authorization: Bearer ACCESS_TOKEN
Content-Type: application/json

{
    "name": "MyNewFileName.doc"
}

In the preceding code, change the file ID to a different file ID, photo ID, video ID, or audio ID to change info about a different file, photo, video, or audio.

For details about the minimum required and optional structures that your app must provide to use PUT for a photo, video, or audio, see the "Audio object", "Photo object", or "Video object" section in REST reference.

For details about the minimum required and optional structures that your app must provide to use PUT for any other file type, see the "File object" section in REST reference.

Top

Downloading files

How to get the contents of a file, photo, video, or audio depends on your app type. The wl.skydrive scope is required.

For Windows Store apps using JavaScript, use code like this.

JavaScript
function downloadFile_onClick() {
    var picker = setupSavePicker();
    picker.pickSaveFileAsync().then(
        function (file) {
            if (file && (file instanceof Windows.Storage.StorageFile)) {
                WL.login({
                    scope: "wl.skydrive"
                }).then(
                    function (response) {
                        WL.backgroundDownload({
                            path: "file.8c8ce076ca27823f.8C8CE076CA27823F!129/picture?type=thumbnail",
                            file_output: file
                        }).then(
                            function (response) {
                                document.getElementById("infoLabel").innerText = "Downloaded file.";
                            },
                            function (responseFailed) {
                                document.getElementById("infoLabel").innerText =
                                "Error calling API: " + responseFailed.error.message;
                            }
                        );
                    },
                    function (responseFailed) {
                        document.getElementById("infoLabel").innerText =
                            "Error signing in: " + responseFailed.error.message;
                    }
                );
            }
            else {
                document.getElementById("infoLabel").innerText = "Cannot download file.";
            }
        },
        function (fileFailed) {
            document.getElementById("infoLabel").innerText = "Cannot download file.";
        }
    );
}

function setupSavePicker() {
    var savepicker = new Windows.Storage.Pickers.FileSavePicker();
    savepicker.suggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.documentsLibrary;
    savepicker.fileTypeChoices.insert("Picture", [".jpg"]);
    return savepicker;
}

[C#]

For Windows Store apps using C#, use code like this.

C#
private System.Threading.CancellationTokenSource ctsDownload;

private async void btnDownloadFile_Click(object sender, RoutedEventArgs e)
{
    try
    {
        var picker = new Windows.Storage.Pickers.FileSavePicker();
        picker.SuggestedFileName = "MyDownloadedPicutre.jpg";
        picker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.Downloads;
        picker.FileTypeChoices.Add("Picture", new List<string>(new string[] { ".jpg" }));
        StorageFile file = await picker.PickSaveFileAsync();
        if (file != null)
        {
            this.progressBar.Value = 0;
            var progressHandler = new Progress<LiveOperationProgress>(
                (progress) => { this.progressBar.Value = progress.ProgressPercentage; });
            this.ctsDownload = new System.Threading.CancellationTokenSource();
            LiveConnectClient liveClient = new LiveConnectClient(this.session);
            await liveClient.BackgroundDownloadAsync("file.8c8ce076ca27823f.8C8CE076CA27823F!161", file,
                this.ctsDownload.Token, progressHandler);
            this.infoTextBlock.Text = "Download completed.";
        }
    }
    catch (System.Threading.Tasks.TaskCanceledException)
    {
        this.infoTextBlock.Text = "Download cancelled.";
    }
    catch (LiveConnectException exception)
    {
        this.infoTextBlock.Text = "Error getting file contents: " + exception.Message;
    }
}

private void btnCancelDownload_Click(object sender, RoutedEventArgs e)
{
    if (this.ctsDownload != null)
    {
        this.ctsDownload.Cancel();
    }
}

Note For Windows Store apps using C#, the LiveConnectClient.BackgroundDownloadAsync method uses the background transfer service provided by Windows 8. For details, see Transferring a file from a network resource and Windows.Networking.BackgroundTransfer namespace.

For Windows Phone apps, use code like this.

C#
private void btnDownloadFile_Begin(object sender, RoutedEventArgs e)
{
    if (session == null)
    {
        infoTextBlock.Text = "You must sign in first.";
    }
    else
    {
        LiveConnectClient client = new LiveConnectClient(session);
        client.DownloadCompleted += new EventHandler<LiveDownloadCompletedEventArgs>(OnDownloadCompleted);
        client.DownloadAsync("file.a6b2a7e8f2515e5e.A6B2A7E8F2515E5E!131/picture?type=thumbnail");
    }
}

void OnDownloadCompleted(object sender, LiveDownloadCompletedEventArgs e)
{
    if (e.Result != null)
    {
        imageFrame.Visibility = Visibility.Visible;
        BitmapImage imgSource = new BitmapImage();
        imgSource.SetSource(e.Result);
        // imageFrame is a user-defined Image control.
        imageFrame.Source = imgSource;
        e.Result.Close();
    }
    else
    {
        infoTextBlock.Text = "Error downloading image: " + e.Error.ToString();
    }
}

Tip

For Windows Phone 7.5 apps, you can download files even if the app that started the download is suspended or quits. Here's how.

  1. In the code that initializes the LiveConnectClient variable, declare handlers for the LiveConnectClient.BackgroundDownloadCompleted event. (Optionally, you can also handle the LiveConnectClient class's BackgroundDownloadProgressChanged, BackgroundUploadCompleted, and BackgroundUploadProgressChanged events if you want to check the progress of a background file download, do something after a file has been uploaded, or check the progress of a background file upload.) Then call the LiveConnectClient.AttachPendingTransfers method, which checks for pending background file transfers that were started in a previous instance of the app. Here's the code.
    C#
    private void btnSignin_SessionChanged(object sender, LiveConnectSessionChangedEventArgs e)
{
    if (e.Status == LiveConnectSessionStatus.Connected)
    {
        session = e.Session;
        client = new LiveConnectClient(session);
        client.BackgroundDownloadProgressChanged +=
            new EventHandler<LiveDownloadProgressChangedEventArgs>(OnBackgroundDownloadProgressChanged);
        client.BackgroundDownloadCompleted +=
            new EventHandler<LiveOperationCompletedEventArgs>(OnBackgroundDownloadCompleted);
        client.BackgroundUploadProgressChanged +=
            new EventHandler<LiveUploadProgressChangedEventArgs>(OnBackgroundUploadProgressChanged);
        client.BackgroundUploadCompleted +=
            new EventHandler<LiveOperationCompletedEventArgs>(OnBackgroundUploadCompleted);
        client.AttachPendingTransfers();
        infoTextBlock.Text = "Signed in.";
    }
    else
    {
        infoTextBlock.Text = "Not signed in.";
        client = null;
    }
}
  2. Initiate the background file download and implement event handlers for the BackgroundDownloadCompleted event (and, optionally, the BackgroundDownloadProgressChanged event), like this.
    C#
    private void StartBackgroundDownload(object sender, RoutedEventArgs e)
{
    client.BackgroundDownloadAsync("file.8c8ce076ca27823f.8C8CE076CA27823F!161",
        new Uri("/shared/transfers/TheNumber5.jpg", UriKind.RelativeOrAbsolute), "TheNumber5Download");
}

void OnBackgroundDownloadProgressChanged(object sender, LiveDownloadProgressChangedEventArgs e)
{
    if (e.UserState.ToString() == "TheNumber5Download")
    {
        infoTextBlock.Text = e.UserState.ToString() + ": " + e.BytesReceived + " of " +
            e.TotalBytesToReceive + " bytes downloaded (" + e.ProgressPercentage + "%)";
    }
}

void OnBackgroundDownloadCompleted(object sender, LiveOperationCompletedEventArgs e)
{
    if (e.UserState.ToString() == "TheNumber5Download")
    {
        if (e.Error == null)
        {
            infoTextBlock.Text = "Download completed.";
        }
        else
        {
            infoTextBlock.Text = "Error downloading file: " + e.Error.ToString();
        }
    }
}

[Objective-C for iOS]

ObjectiveC
-(void) downloadFile
{
    [self.liveClient downloadFromPath:@"file.95d463b9efcca0e1.95D463B9EFCCA0E1!113/content"
                             delegate:self];
}

- (void) liveOperationSucceeded:(LiveOperation *)operation
{
    LiveDownloadOperation * downloadOperation = (LiveDownloadOperation *)operation;
    UIImage *downloadedPicture = [UIImage imageWithData:downloadOperation.data];
    imageView.image = downloadedPicture;
}

[Java for Android]

Java
public void downloadFile() {
    String file = "file.a6b2a7e8f2515e5e.A6B2A7E8F2515E5E!131/picture?type=thumbnail";
    client.downloadAsync(file, new LiveDownloadOperationListener() {
        public void onDownloadCompleted(LiveDownloadOperation operation)
        {
            try {
                resultTextView.setText("Picture downloaded.");
                InputStream input =  operation.getStream();
                Bitmap bMap = BitmapFactory.decodeStream(input);
                picture.setImageBitmap(bMap);
                input.close();
            }
            catch(java.io.IOException ex) {
                resultTextView.setText("Error downloading picture: " + ex.getMessage());
            }
        }
        public void onDownloadFailed(LiveOperationException exception, LiveDownloadOperation operation)
        {
            resultTextView.setText(exception.getMessage());
        }
        public void onDownloadProgress(int totalBytes, int bytesRemaining, LiveDownloadOperation operation)
        {
            resultTextView.setText("Downloading picture... " + bytesRemaining + " bytes downloaded " +
                "(" + (bytesRemaining / totalBytes) * 100 + "%)");
        }
    });
}

[REST]

For Representational State Transfer (REST), use the REST code in the preceding Reading file properties section, but insert /content after the file ID, photo ID, video ID, or audio ID, for example, FILE_ID/content.

Tip You can instruct the user's web browser to prompt the user to save the file that's downloading instead of having the browser try to download and display the file directly in its own window. To do this, add the download=true query-string parameter after /content (for example, FILE_ID/content?download=true). This call adds the Content-Disposition: attachment header to the response.

To get a download link to the contents of a file, photo, video, or audio, use the REST code in the preceding Reading file properties section, but insert /content?suppress_redirects=true after the file ID, photo ID, video ID, or audio ID, for example, FILE_ID/content?suppress_redirects=true.

[JavaScript for Windows Store apps and HTML]

For client-side websites and scripts that use JavaScript, use code like this.

HTML
function downloadFile() {
    WL.login({
        scope: "wl.skydrive"
    }).then(
        function (response) {
            WL.download({
                path: "file.a6b2a7e8f2515e5e.A6B2A7E8F2515E5E!131/content"
            }).then(
                function (response) {
                    // Will not be called for web apps.
                },
                function (responseFailed) {
                    document.getElementById("info").innerText =
                        "Error downloading file: " + responseFailed.error.message;
                }
            );
        },
        function (responseFailed) {
            document.getElementById("info").innerText =
                "Error signing in: " + responseFailed.error.message;
        }
    );
}

Tip Instead of hard-coding the file ID, your code can prompt the signed-in user to dynamically select the file (or even multiple files) to download from his or her SkyDrive storage location. For more info, see SkyDrive file picker for web apps.

To get a download link to the contents of a file, photo, video, or audio, use the JavaScript code in the preceding Reading file properties section, but insert /content?suppress_redirects=true after the file ID, photo ID, video ID, or audio ID, for example, FILE_ID/content?suppress_redirects=true.

Top

Uploading files

How to add contents for a file, photo, video, or audio depends on your app type. The wl.skydrive_update scope is required.

[JavaScript for HTML]

For client-side websites and scripts that use JavaScript, use code like this.

HTML
function uploadFile() {
    WL.login({
        scope: "wl.skydrive_update"
    }).then(
        function (response) {
            WL.upload({
                path: "folder.a6b2a7e8f2515e5e.A6B2A7E8F2515E5E!170",
                element: "file",
                overwrite: "rename"
            }).then(
                function (response) {
                    document.getElementById("info").innerText =
                        "File uploaded.";
                },
                function (responseFailed) {
                    document.getElementById("info").innerText =
                        "Error uploading file: " + responseFailed.error.message;
                }
            );
        },
        function (responseFailed) {
            document.getElementById("info").innerText =
                "Error signing in: " + responseFailed.error.message;
        }
    );
}

Tip Instead of hard-coding the file ID, your code can prompt the signed-in user to dynamically select the file to upload to his or her SkyDrive storage location. For more info, see SkyDrive file picker for web apps.

For Windows Store apps using JavaScript, use code like this.

JavaScript
function uploadFile_onClick() {
    var picker = setupOpenPicker();
    var filePickOp = picker.pickSingleFileAsync().then(
        function (file) {
            WL.login({
                scope: "wl.skydrive_update"
            }).then(
                function (response) {
                    WL.backgroundUpload({
                        path: "me/skydrive",
                        file_name: file.fileName,
                        file_input: file,
                        overwrite: "rename"
                    }).then(
                       function (response) {
                           document.getElementById("infoLabel").innerText = "Uploaded file.";
                       },
                       function (responseFailed) {
                           document.getElementById("infoLabel").innerText =
                               "Error calling API: " + responseFailed.error.message;
                       }
                    );
                },
                function (responseFailed) {
                    document.getElementById("infoLabel").innerText =
                        "Error signing in: " + responseFailed.error.message;
                }
            );
        },
        function (fileFailed) {
            document.getElementById("infoLabel").innerText = "Cannot upload file.";
        }
    );
}

function setupOpenPicker() {
    var openpicker = new Windows.Storage.Pickers.FileOpenPicker();
    openpicker.fileTypeFilter.replaceAll(["*"]);
    return openpicker;
}

Tip Before uploading a file, have your app check to make sure that there is enough available SkyDrive storage space by making a WL.api GET method call to USER_ID/skydrive/quota. For example, your app could get the size of the file in bytes and then compare it to the number of available storage bytes returned in the SkyDrive quota call. For more info, see the "Get a user's total and remaining SkyDrive storage quota" section in SkyDrive core concepts.

[C#]

For Windows Store apps using C#, use code like this.

C#
private System.Threading.CancellationTokenSource ctsUpload;

private async void btnUploadFile_Click(object sender, RoutedEventArgs e)
{
    try
    {
        var picker = new Windows.Storage.Pickers.FileOpenPicker();
        picker.ViewMode = Windows.Storage.Pickers.PickerViewMode.Thumbnail;
        picker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.PicturesLibrary;
        picker.FileTypeFilter.Add("*");
        Windows.Storage.StorageFile file = await picker.PickSingleFileAsync();
        if (file != null)
        {
            this.progressBar.Value = 0;
            var progressHandler = new Progress<LiveOperationProgress>(
                (progress) => { this.progressBar.Value = progress.ProgressPercentage; });
            this.ctsUpload = new System.Threading.CancellationTokenSource();
            LiveConnectClient liveClient = new LiveConnectClient(this.session);
            await liveClient.BackgroundUploadAsync("folder.8c8ce076ca27823f.8C8CE076CA27823F!134",
                "MyUploadedPicture.jpg", file, true, this.ctsUpload.Token, progressHandler);
            this.infoTextBlock.Text = "Upload completed.";
        }
    }
    catch (System.Threading.Tasks.TaskCanceledException)
    {
        this.infoTextBlock.Text = "Upload cancelled.";
    }
    catch (LiveConnectException exception)
    {
        this.infoTextBlock.Text = "Error uploading file: " + exception.Message;
    }
}

private void btnCancelUpload_Click(object sender, RoutedEventArgs e)
{
    if (this.ctsUpload != null)
    {
        this.ctsUpload.Cancel();
    }
}

Tip Before uploading a file, have your app check to make sure that there is enough available SkyDrive storage space by making a LiveConnectClient.GetAsync method call to USER_ID/skydrive/quota. For example, your app could get the size of the file in bytes and then compare it to the number of available storage bytes returned in the SkyDrive quota call. For more info, see the "Get a user's total and remaining SkyDrive storage quota" section in SkyDrive core concepts.

Note For Windows Store apps using C#, the LiveConnectClient.BackgroundUploadAsync method uses the background transfer service provided by Windows 8. For details, see Transferring a file from a network resource and Windows.Networking.BackgroundTransfer namespace.

For Windows Phone apps, use code like this.

C#
private void createFile_Click(object sender, RoutedEventArgs e)
{
    var picker = new PhotoChooserTask();
    picker.Completed +=
        new EventHandler<PhotoResult>(OnPhotoChooserTaskCompleted);
    picker.Show();
}

private void OnPhotoChooserTaskCompleted(object sender, PhotoResult e)
{
    if (e.Error != null)
    {
        this.infoTextBlock.Text = "Error choosing photo: " + e.Error.ToString();
    }
    else
    {
        string[] filePathSegments = e.OriginalFileName.Split('\\');
        string fileName = filePathSegments[filePathSegments.Length - 1];
        client.UploadCompleted
            += new EventHandler<LiveOperationCompletedEventArgs>(OnPhotoChooserTaskCompleted_UploadCompleted);
        client.UploadAsync("me/skydrive", fileName, e.ChosenPhoto);
    }
}
C#
private void OnPhotoChooserTaskCompleted_UploadCompleted(object sender, LiveOperationCompletedEventArgs args)
{
    if (args.Error == null)
    {
        IDictionary<string, object> file = (IDictionary<string, object>)args.Result;
        this.infoTextBlock.Text = "File uploaded. Link: " + file["source"];
    }
    else
    {
        this.infoTextBlock.Text =
            "Error uploading file: " + args.Error.ToString();
    }
}

Tip

For Windows Phone 7.5 apps, you can upload files even if the app that started the upload is suspended or quits. Here's how.

  1. In the code that initializes the LiveConnectClient variable, declare handlers for the LiveConnectClient.BackgroundUploadCompleted event. (Optionally, you can also handle the LiveConnectClient class's BackgroundUploadProgressChanged, BackgroundDownloadCompleted, and BackgroundDownloadProgressChanged events if you want to check the progress of a background file upload, do something after a file has downloaded, or check the progress of a background file download.) Then call the LiveConnectClient.AttachPendingTransfers method, which checks for pending background file transfers that were started in a previous instance of the app. Here's the code.
    C#
    private void btnSignin_SessionChanged(object sender, LiveConnectSessionChangedEventArgs e)
{
    if (e.Status == LiveConnectSessionStatus.Connected)
    {
        session = e.Session;
        client = new LiveConnectClient(session);
        client.BackgroundDownloadProgressChanged +=
            new EventHandler<LiveDownloadProgressChangedEventArgs>(OnBackgroundDownloadProgressChanged);
        client.BackgroundDownloadCompleted +=
            new EventHandler<LiveOperationCompletedEventArgs>(OnBackgroundDownloadCompleted);
        client.BackgroundUploadProgressChanged +=
            new EventHandler<LiveUploadProgressChangedEventArgs>(OnBackgroundUploadProgressChanged);
        client.BackgroundUploadCompleted +=
            new EventHandler<LiveOperationCompletedEventArgs>(OnBackgroundUploadCompleted);
        client.AttachPendingTransfers();
        infoTextBlock.Text = "Signed in.";
    }
    else
    {
        infoTextBlock.Text = "Not signed in.";
        client = null;
    }
}
  2. Initiate the background file upload and implement event handlers for the BackgroundUploadCompleted event (and, optionally, the BackgroundUploadProgressChanged event), like this.
    C#
    private void StartBackgroundUpload(object sender, RoutedEventArgs e)
{
    client.BackgroundUploadAsync("folder.8c8ce076ca27823f.8C8CE076CA27823F!134",
        new Uri("/shared/transfers/TheNumber5.jpg", UriKind.RelativeOrAbsolute), OverwriteOption.Rename, "TheNumber5Upload");
}

void OnBackgroundUploadProgressChanged(object sender, LiveUploadProgressChangedEventArgs e)
{
    if (e.UserState.ToString() == "TheNumber5Upload")
    {
        infoTextBlock.Text = e.UserState.ToString() + ": " + e.BytesSent + " of " +
            e.TotalBytesToSend + " bytes uploaded (" + e.ProgressPercentage + "%)";
    }
}

void OnBackgroundUploadCompleted(object sender, LiveOperationCompletedEventArgs e)
{
    if (e.UserState.ToString() == "TheNumber5Upload")
    {
        if (e.Error == null)
        {
            infoTextBlock.Text = "Upload completed.";
        }
        else
        {
            infoTextBlock.Text = "Error uploading file: " + e.Error.ToString();
        }
    }
}

[Objective-C for iOS]

ObjectiveC
-(void) uploadFile
{
    NSString *path = [[NSBundle mainBundle] pathForResource:@"Fire-Phoenix" ofType:@"jpg"];
    NSData *fileToUpload = [[[NSData alloc]initWithContentsOfFile:path] retain];
    [self.liveClient uploadToPath:@"me/skydrive"
                         fileName:@"Favorite pic.jpg"
                             data:fileToUpload
                         delegate:self];
}

- (void) liveOperationSucceeded:(LiveOperation *)operation
{
    NSString *fileId = [operation.result objectForKey:@"id"];
    NSString *fileName = [operation.result objectForKey:@"name"];
    NSString *fileDescription = [operation.result objectForKey:@"description"];
    NSString *fileSize = [operation.result objectForKey:@"size"];
    self.displayLabel.text = [NSString stringWithFormat:
                              @"File Properties:\n"
                              @"\tId. %@\n"
                              @"\tName. %@\n"
                              @"\tDescription. %@\n"
                              @"\tSize. %@\n"
                              , fileId,
                              fileName,
                              fileDescription,
                              fileSize];
}

Tip Before uploading a file, have your app check to make sure that there is enough available SkyDrive storage space by making a LiveConnectClient getWithPath:delegate:userState method call to USER_ID/skydrive/quota. For example, your app could get the size of the file in bytes and then compare it to the number of available storage bytes returned in the SkyDrive quota call. For more info, see the "Get a user's total and remaining SkyDrive storage quota" section in SkyDrive core concepts.

[Java for Android]

Java
public void createFile() {
    final Runnable uploadImage = new Runnable() {
        public void run() {
            final String imageUrl = "http://i.imgur.com/LYZEGB.jpg";
            final String fileName = "Vase-Cup.jpg";
            final URL url;
            final URLConnection ucon;
            final InputStream is;
            try {
                url = new URL(imageUrl);
                ucon = url.openConnection();
                is = ucon.getInputStream();
                client.uploadAsync("me/skydrive", fileName, is, new LiveUploadOperationListener() {
                    public void onUploadFailed(LiveOperationException exception, LiveOperation operation) {
                        resultTextView.setText("Error uploading file: " + exception.getMessage());
                    }
                    public void onUploadCompleted(LiveOperation operation) {
                        resultTextView.setText("File uploaded.");
                        try {
                            is.close();
                        }
                        catch(IOException ioe) {
                            resultTextView.setText("Error uploading file: " + ioe.getMessage());
                        }
                    }
                    public void onUploadProgress(int totalBytes, int bytesRemaining, LiveOperation operation)
                          {
                              resultTextView.setText("Uploading file... " + bytesRemaining + " bytes remaining " +
                                "(" + (bytesRemaining / totalBytes) * 100 + "%)");
                          }
                });
            }
            catch(IOException ioex) {
                resultTextView.setText("Error uploading file: " + ioex.getMessage());
                return;
            }
            catch(Exception ex)
            {
                resultTextView.setText("Error uploading file: " + ex.getMessage());
                return;
            }
        }
    };
    auth.login(this, Arrays.asList(new String[] { "wl.skydrive_update" }), new LiveAuthListener() {
        public void onAuthError(LiveAuthException exception, Object userState) {
            resultTextView.setText("Error signing in: " + exception.getMessage());
        }
          public void onAuthComplete(LiveStatus status, LiveConnectSession session, Object userState) {
              new Thread(uploadImage).start();
        }
      });

}

Tip Before uploading a file, have your app check to make sure that there is enough available SkyDrive storage space by making a LiveConnectClient.getAsync method call to USER_ID/skydrive/quota. For example, your app could get the size of the file in bytes and then compare it to the number of available storage bytes returned in the SkyDrive quota call. For more info, see the "Get a user's total and remaining SkyDrive storage quota" section in SkyDrive core concepts.

If you're using a PUT request, you can use one of these specifiers.

  • me/skydrive/files/FILE_NAME
  • The value of the upload_location structure for the folder to which the file, photo, video, or audio will be uploaded, followed by a forward slash character (/) and the file name.
  • The folder ID of the folder to which the file, photo, video, or audio will be uploaded, followed by /files/ and the file name.
  • If the file already exists from a previous upload operation, the value of the existing file's upload_location structure.
  • If the file already exists from a previous upload operation, the file ID of the file, followed by /content.

For details about the minimum required and optional structures that your app must provide when you use POST or PUT to upload a photo, video, or audio, see the "Audio object", "Photo object", or "Video object" section in REST reference.

For details about the minimum required and optional structures that your app must provide when you use POST or PUT to upload any other file type, see the "File object" section in REST reference.

[REST]

For REST, you can use PUT or POST, depending on your platform's recommended approach.

Important On platforms that support the PUT request, PUT should be used to upload files to SkyDrive when possible to avoid errors that can occur when POST is used.

Here's an example of code that uses PUT.

PUT https://apis.live.net/v5.0/me/skydrive/files/HelloWorld.txt?access_token=ACCESS_TOKEN

Hello, World!

Note By default, the file, photo, video, or audio with the same name will be overwritten, if it already exists. You can add an overwrite query-string parameter with a value of false to not overwrite the existing file, photo, video, or audio. Or you can add an overwrite query-string parameter of ChooseNewName if you want to upload a duplicate copy of the file but let SkyDrive choose a new file name for the uploaded file.

Here's an example of code that uses POST.

POST https://apis.live.net/v5.0/me/skydrive/files?access_token=ACCESS_TOKEN

Content-Type: multipart/form-data; boundary=A300x

--A300x
Content-Disposition: form-data; name="file"; filename="HelloWorld.txt"
Content-Type: application/octet-stream

Hello, World!
--A300x--

For REST, if you're using POST as shown here, you must format the request as multipart/form-data. You provide the file to upload in a multipart section, while you provide the file name in the Content-Disposition header's filename parameter. For more info, see RFC 2388. Note that only one multipart section is supported in the body of the request.

Also for REST, if you're using POST, you can use any of these.

  • me/skydrive/files
  • FOLDER_ID/files, where FOLDER_ID is the ID of the parent folder.
  • The value of the upload_location structure for the folder to which the file, photo, video, or audio will be uploaded.

You can instruct SkyDrive to notify the web browser when the upload finishes. You can also attach a unique identifier to each upload request so that you can identify a particular file if you are uploading multiple files in quick succession. To do this, use a POST multipart/form-data request, like this:

POST https://apis.live.net/v5.0/folder.a6b2a7e8f2515e5e.A6B2A7E8F2515E5E!110/files?state=MyNewFileState&redirect_uri=http%3A%2F%2Fwww.contoso.com%2Fcallback.htm&access_token=ACCESS_TOKEN

Content-Type: multipart/form-data; boundary=AaB03x

--AaB03x
Content-Disposition: form-data; name="file"; filename="MyNewFile.txt"
Content-Type: text/plain

These are the contents of my new file.
--AaB03x--

In this example, replace the folder ID with your target folder ID; replace the state query-string parameter value with your unique identifier; and replace the redirect_uri parameter with the path to your callback page. Note that the domain portion of the path must match the redirect domain that you specified in the Live Connect app management site for the corresponding client ID.

SkyDrive returns HTML-formatted code similar to the following.

<html>
    <head>
        <script type="text/javascript">
            window.location = "http://www.contoso.com/callback.htm#state=MyNewFileState&result=%7B%22id%22%3A%22file.a6b2a7e8f2515e5e.A6B2A7E8F2515E5E!184%22%2C%22source%22%3A%22http%3A%2F%2Fstorage.live.com%2Fs1pasGKzgXFvuEQCbxGtOyIpboUVH1OCHoRzUJNDDwL0zVoidb0RRrNVk88hUrOEve5OMT7eCkuxPbop7dV9tMJQ-eE8SCQ28vFv9ZgPnDGwQMRm-0FeG3-KEY4HL9dQSw9%2FMyNewFile.txt%3ABinary%2CDefault%2FMyNewFile.txt%22%7D";
        </script>
    </head>
</html>

When decoded, the result response parameter is similar to this.

{
    "id": "file.a6b2a7e8f2515e5e.A6B2A7E8F2515E5E!184",
    "source": "http://storage.live.com/s1pasGKzgXFvuEQCbxGtOyIpboUVH1OCHoRzUJNDDwL0zVoidb0RRrNVk88hUrOEve5OMT7eCkuxPbop7dV9tMJQ-eE8SCQ28vFv9ZgPnDGwQMRm-0FeG3-KEY4HL9dQSw9/MyNewFile.txt:Binary,Default/MyNewFile.txt"
}

Note By default, the file, photo, video, or audio with the same name will be overwritten, if it already exists. You can add an overwrite query-string parameter with a value of false to not overwrite the existing file, photo, video, or audio. Or you can add an overwrite query-string parameter of ChooseNewName if you want to upload a duplicate copy of the file but let SkyDrive choose a new file name for the uploaded file.

Tip Before uploading a file, have your app check to make sure that there is enough available SkyDrive storage space by making a GET call to USER_ID/skydrive/quota. For example, your app could get the size of the file in bytes and then compare it to the number of available storage bytes returned in the SkyDrive quota call. For more info, see the "Get a user's total and remaining SkyDrive storage quota" section in SkyDrive core concepts.

Top

Updating uploaded files

To change contents for an existing file, photo, video, or audio, use the code in the preceding Uploading files section, plus one of the following methods:

  • For JavaScript, use WL.upload.
  • For C# for Windows Store apps, use LiveConnectClient.BackgroundUploadAsync.
  • For C# for Windows Phone, use LiveConnectClient.UploadAsync or LiveConnectClient.BackgroundUpload.
  • For Objective-C, use LiveConnectClient uploadToPath:fileName:data:delegate:userState.
  • For Java, use LiveConnectClient.uploadAsync.
  • For REST, use POST or PUT.

Top

Deleting uploaded files

To remove a file, photo, video, or audio, use code like this. The wl.skydrive_update scope is required.

[JavaScript for Windows Store apps and HTML]

JavaScript
function deleteFile_onClick() {
    WL.login({
        scope: "wl.skydrive_update"
    }).then(
        function (response) {
            WL.api({
                path: "file.a6b2a7e8f2515e5e.A6B2A7E8F2515E5E!152",
                method: "DELETE"
            }).then(
                function (response) {
                    document.getElementById("infoArea").innerText = "Deleted file.";
                },
                function (responseFailed) {
                    document.getElementById("infoArea").innerText =
                        "Error calling API: " + responseFailed.error.message;
                }
            );
        },
        function (responseFailed) {
            document.getElementById("infoArea").innerText =
                "Error signing in: " + responseFailed.error_description;
        }
    );
}

[C# for Windows Store apps and Windows Phone apps]

C#
private async void btnDeleteFolder_Click(object sender, RoutedEventArgs e)
{
    try
    {
        LiveConnectClient liveClient = new LiveConnectClient(this.session);
        LiveOperationResult operationResult =
            await liveClient.DeleteAsync("folder.a6b2a7e8f2515e5e.A6B2A7E8F2515E5E!147");
        this.infoTextBlock.Text = "Folder deleted.";
    }
    catch (LiveConnectException exception)
    {
        this.infoTextBlock.Text = "Error deleting folder: " + exception.Message;
    }
}

[Objective-C for iOS]

ObjectiveC
-(void) deleteFile
{
    [self.liveClient deleteWithPath:@"file.95d463b9efcca0e1.95D463B9EFCCA0E1!113"
                           delegate:self];
}

- (void) liveOperationSucceeded:(LiveOperation *)operation
{
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"API call successful!"
                                                    message:@"File deleted successfully"
                                                   delegate:self
                                          cancelButtonTitle:@"Ok"
                                          otherButtonTitles:nil,
                          nil];
    [alert show];
    [alert release];
}

[Java for Android]

Java
public void deleteFile() {
    final String fileId = "file.a6b2a7e8f2515e5e.A6B2A7E8F2515E5E!125";
    client.deleteAsync(fileId, new LiveOperationListener() {
        public void onError(LiveOperationException exception, LiveOperation operation) {
               resultTextView.setText("Error deleting file: " + exception.getMessage());
           }
           public void onComplete(LiveOperation operation) {
            resultTextView.setText("File deleted.");
           }
       });

}

[REST]

DELETE https://apis.live.netv5.0/file.b7c3b8f9g3616f6f.B7CB8F9G3626F6!225?access_token=ACCESS_TOKEN

In the preceding code, change the file ID to a different file ID, photo ID, video ID, or audio ID to remove a different file, photo, video, or audio.

Top

Getting links to folders and files

Your apps can get the following types of links to SkyDrive folders and files.

  • An embedded link, which is an HTML code snippet that you can insert into a webpage to provide an interactive view of the corresponding file.

    Note Currently, embedded links are supported only for files owned by the user. To determine whether a given file can be embedded, check to see if the corresponding File object's is_embeddable structure is set to true. Also, some embedded links provide a rich embedding experience, while others provide only an icon and a file name. Rich embedding is supported for the following types of Microsoft PowerPoint and Microsoft Excel files: .pot, .potm, .potx, .pps, .ppsm, .ppsx, .ppt, .pptm, .pptx, .xlsb, .xlsm, and .xlsx.

  • A read-only link, which is a link to a read-only version of the folder or file.
  • A read-write link, which is a link to a read-write version of the folder or file.

Important When your apps request a read-only or read-write link to a file, the URL to that file is the same for either request. When your apps request a read-only link for a file and then later request a read-write link for that same file, read-only permission for that link is revoked. Similarly, when your apps request a read-write link for a file and then later request a read-only link for that same file, read-write permission for that link is revoked.

To get a link to a folder or file, use code like this.

[JavaScript for Windows Store apps and HTML]

JavaScript
function getSharedLink_onClick() {
    WL.login({
        scope: "wl.skydrive"
    }).then(
        function (response) {
            WL.api({
                path: "file.a6b2a7e8f2515e5e.A6B2A7E8F2515E5E!152/shared_read_link",
                method: "GET"
            }).then(
                function (response) {
                    document.getElementById("infoArea").innerText =
                        "Shared link = " + response.link;
                },
                function (responseFailed) {
                    document.getElementById("infoArea").innerText =
                        "Error calling API: " + responseFailed.error.message;
                }
            );
        },
        function (responseFailed) {
            document.getElementById("infoArea").innerText =
                "Error signing in: " + responseFailed.error_description;
        }
    );
}

[C# for Windows Store apps and Windows Phone apps]

C#
private async void btnGetLink_Click(object sender, RoutedEventArgs e)
{
    try
    {
        LiveConnectClient liveClient = new LiveConnectClient(this.session);
        LiveOperationResult operationResult =
            await liveClient.GetAsync("file.8c8ce076ca27823f.8C8CE076CA27823F!129/shared_read_link");
        dynamic result = operationResult.Result;
        this.infoTextBlock.Text = "Shared read link: " + result.link;
    }
    catch (LiveConnectException exception)
    {
        this.infoTextBlock.Text = "Error getting shared read link: " + exception.Message;
    }
}

[Objective-C for iOS]

ObjectiveC
-(void) getLinkToFile
{
    [self.liveClient getWithPath:@"file.95d463b9efcca0e1.95D463B9EFCCA0E1!113/shared_read_link"
                        delegate:self
                       userState:@"onClickGetLinkToFileButton"];
}

- (void) liveOperationSucceeded:(LiveOperation *)operation
{
    self.infoLabel.text = [NSString stringWithFormat: @"Shared read link = %@", [operation.result objectForKey:@"link"]];
}

[Java for Android]

Java
public void getLinkToFile() {
    final String path = "file.a6b2a7e8f2515e5e.A6B2A7E8F2515E5E!141/shared_read_link";
    final LiveOperationListener opListener = new LiveOperationListener() {
        public void onError(LiveOperationException exception, LiveOperation operation) {
               resultTextView.setText("Error getting link to file: " + exception.getMessage());
           }
           public void onComplete(LiveOperation operation) {
            JSONObject result = operation.getResult();
            String text =  "Shared link to file = " + result.optString("link");
               resultTextView.setText(text);
           }
       };
    auth.login(this, Arrays.asList(new String[] { "wl.skydrive" }), new LiveAuthListener() {
        public void onAuthError(LiveAuthException exception, Object userState) {
            resultTextView.setText("Error signing in: " + exception.getMessage());
        }
        public void onAuthComplete(LiveStatus status, LiveConnectSession session, Object userState) {
            client.getAsync(path, opListener);
        }
    });
}

[REST]

GET https://apis.live.netv5.0/file.a6b2a7e8f2515e5e.A6B2A7E8F2515E5E!126/shared_read_link?access_token=ACCESS_TOKEN

In the preceding code, change the file ID to the folder ID or file ID that you want a link to. Also, change shared_read_link to one of these.

  • To embed for an embedded link. You get the embed HTML code snippet from the returned JSON-formatted object's embed_html structure value.
  • To shared_read_link for a read-only link. You get the read-only link from the returned JSON-formatted object's link structure value.
  • To shared_edit_link for a read-write link. You get the read-write link from the returned JSON-formatted object's link structure value.

When your app requests a file, photo, video, or audio, the returned object includes a preauthenticated URL as the value of the source attribute. Preauthenticated URLs allow access to a file without the need for additional permissions. Preauthenticated URLs expire and should not be stored or reused later. The following example shows what a preauthenticated URL looks like.

"source": "http://storage.live.com/s1pk0Hsk4twGIbzleNLcqhVhp5yvj9aPLPMHq2GDTRFBeuicbS27Fx5xBnmyy5J4lDSEtdvYm2FxOB0-s8Heb1l6hq3A1E2bJ9qWQ3GdIUTnnG6CHLTBLdCHRPUNAunekX1dnLS49vG-fUV7O8ZvrkiLTubXXFqrT1roxZ1oJjELE/Test.txt:Binary"

Top

Moving folders and files

To move a folder, file, photo, video, or audio, use code like this. The wl.skydrive_update scope is required. For move operations, the source can be anything except the root, and the destination must be the folder to which the item will be moved.

[JavaScript for Windows Store apps and HTML]

JavaScript
function moveFile_onClick() {
    WL.login({
        scope: "wl.skydrive_update"
    }).then(
        function (response) {
            WL.api({
                path: "file.a6b2a7e8f2515e5e.A6B2A7E8F2515E5E!141",
                method: "MOVE",
                body: {
                    destination: "folder.a6b2a7e8f2515e5e.A6B2A7E8F2515E5E!125"
                }
            }).then(
                function (response) {
                    document.getElementById("infoArea").innerText = "Item moved.";
                },
                function (responseFailed) {
                    document.getElementById("infoArea").innerText =
                        "Error calling API: " + responseFailed.error.message;
                }
            );
        },
        function (responseFailed) {
            document.getElementById("infoArea").innerText =
                "Login error: " + responseFailed.error_description;
        }
    );
}

[C# for Windows Store apps and Windows Phone apps]

C#
private async void btnMoveFile_Click(object sender, RoutedEventArgs e)
{
    try
    {
        LiveConnectClient moveFileClient = new LiveConnectClient(this.session);
        LiveOperationResult operationResult =
            await moveFileClient.MoveAsync("file.9d24497f7fef8f33.9D24497F7FEF8F33!748",
                "folder.9d24497f7fef8f33.9D24497F7FEF8F33!265");
        this.infoTextBlock.Text = "File moved.";
    }
    catch (LiveConnectException exception)
    {
        this.infoTextBlock.Text = "Error moving file: " + exception.Message;
    }
}

[Objective-C for iOS]

ObjectiveC
- (void) moveFile
{
    NSString *folderId = @"folder.2e82e8a5445fe036";
    NSString *fileId = @"file.445fe0362e82e8a5";
    [self.liveClient moveFromPath:fileId
                    toDestination:folderId
                         delegate:self
                        userState:@"move a file"];
}

- (void) liveOperationSucceeded:(LiveOperation *)operation
{
    if ([operation.userState isEqual:@"get folders"]) {
        self.statusLabel.text = @"Skydrive folders are loaded.";
    }
    if ([operation.userState isEqual:@"get folder"]) {
    };
    if ([operation.userState isEqual:@"move a file"]) {
        self.statusLabel.text = [NSString stringWithFormat: @"The file (id: %@) was moved successfully.", operation.path];
    };
}

[Java for Android]

Java
public void moveFile() {
    client.moveAsync("file.a6b2a7e8f2515e5e.A6B2A7E8F2515E5E!120",
            "folder.a6b2a7e8f2515e5e.A6B2A7E8F2515E5E!145", new LiveOperationListener() {
        public void onComplete(LiveOperation operation) {
            resultTextView.setText("File moved.");
        }
        public void onError(LiveOperationException exception, LiveOperation operation) {
            resultTextView.setText("Error moving file: " + exception.getMessage());
        }
    });
}

[REST]

MOVE https://apis.live.net/v5.0/file.a6b2a7e8f2515e5e.A6B2A7E8F2515E5E!126

Authorization: Bearer ACCESS_TOKEN
Content-Type: application/json

{
    "destination": "folder.a6b2a7e8f2515e5e.A6B2A7E8F2515E5E!114"
}

Top

Copying files

To copy a file, use code as shown for move operations. The wl.skydrive_update scope is required.

  • For C#, use the LiveConnectClient.CopyAsync method.
  • For Objective-C, use the LiveConnectClient copyFromPath:toDestination:delegate:userState method.
  • For Java, use the LiveConnectClient.copy method.
  • For REST and JavaScript, change MOVE to COPY to copy the item.

Modify the code example that applies to your application as follows:

  • Change the file ID to the file ID or folder ID of the file or folder that you want to move or copy.
  • Change the folder ID to the folder ID of the target folder to which you want to move or copy the source file or folder.

Important The destination of a move or copy operation must be a folder. Folders themselves cannot be copied. Also, SkyDrive storage is structured so that move and copy operations cannot occur between the SkyDrive folder hierarchies of different users. For example, even if user A can read user B's files, user A cannot copy or move them to his or her own SkyDrive folders.

Top


Working with Microsoft SkyDrive albums, photos, videos, audio, and tags

Your apps can use the Live Connect APIs to create, read, update, and delete a Microsoft SkyDrive user's albums (a special type of folder that can store photos, videos, audio, as well as child albums and child folders), photos, videos, and audio. Your apps can also read, create, and delete tags (a type of comment) that users can add to photos, videos, and audio.

  • Reading albums
  • Deleting albums
  • Creating albums
  • Updating albums
  • Reading photo, video, and audio properties and their contents
  • Updating photo, video, and audio properties
  • Uploading, updating, and deleting photos, videos, and audios
  • Reading tags
  • Deleting tags
  • Creating tags

To make full use of the code examples in this topic, you can use them in the context of larger code reference samples that we provide in Working with the code examples. To request the required scopes, see the code patterns in Obtaining user consent.

Reading albums

To get info about an album, use code like this. The wl.photos or wl.skydrive scope is required.

[JavaScript for Windows Store apps and HTML]

JavaScript
function readAlbumProperties_onClick() {
    WL.login({
        scope: "wl.photos"
    }).then(
        function (response) {
            WL.api({
                path: "folder.a6b2a7e8f2515e5e.A6B2A7E8F2515E5E!165",
                method: "GET"
            }).then(
                function (response) {
                    document.getElementById("infoArea").innerText =
                        "Album properties: name = " + response.name + ", ID = " + response.id;
                },
                function (responseFailed) {
                    document.getElementById("infoArea").innerText =
                        "Error calling API: " + responseFailed.error.message;
                }
            );
        },
        function (responseFailed) {
            document.getElementById("infoArea").innerText =
                "Error signing in: " + responseFailed.error_description;
        }
    );
}

[C# for Windows Store apps and Windows Phone apps]

C#
private async void btnReadAlbum_Click(object sender, RoutedEventArgs e)
{
    try
    {
        LiveConnectClient liveClient = new LiveConnectClient(this.session);
        LiveOperationResult operationResult =
            await liveClient.GetAsync("folder.8c8ce076ca27823f.8C8CE076CA27823F!134");
        dynamic result = operationResult.Result;
        this.infoTextBlock.Text = string.Join(" ", "Album name:", result.name, "ID:", result.id);
    }
    catch (LiveConnectException exception)
    {
        this.infoTextBlock.Text = "Error getting album info: " + exception.Message;
    }
}

[Objective-C for iOS]

ObjectiveC
-(void) getAlbumProperties
{
    [self.liveClient getWithPath:@"folder.95d463b9efcca0e1.95D463B9EFCCA0E1!108"
                        delegate:self];
}

- (void) liveOperationSucceeded:(LiveOperation *)operation
{
    NSString *albumId = [operation.result objectForKey:@"id"];
    NSString *albumName = [operation.result objectForKey:@"name"];
    NSString *albumDescription = [operation.result objectForKey:@"description"];
    NSString *albumLink = [operation.result objectForKey:@"link"];
    NSString *albumType = [operation.result objectForKey:@"type"];
    self.displayLabel.text = [NSString stringWithFormat:
                              @"Album Properties:\n"
                              @"\tId. %@\n"
                              @"\tName. %@\n"
                              @"\tDescription. %@\n"
                              @"\tLink. %@\n"
                              @"\tType. %@\n"
                              , albumId,
                              albumName,
                              albumDescription,
                              albumLink,
                              albumType];
}

[Java for Android]

Java
public void readAlbum() {
    String albumid = "folder.a6b2a7e8f2515e5e.A6B2A7E8F2515E5E!111";
       client.getAsync(albumid , new LiveOperationListener() {
        public void onError(LiveOperationException exception, LiveOperation operation) {
               resultTextView.setText("Error reading album: " + exception.getMessage());
           }
        public void onComplete(LiveOperation operation) {
            JSONObject result = operation.getResult();
            String text = "Album info: " +
                "\nID = " + result.optString("id") +
                "\nName = " + result.optString("name");
               resultTextView.setText(text);
           }
       });
}

[REST]

GET https://apis.live.netv5.0/folder.a6b2a7e8f2515e5e.A6B2A7E8F2515E5E!111?access_token=ACCESS_TOKEN

In the preceding code, change the album ID to this.

  • A different album ID to get info about another album.
  • me/albums to get info about all of the signed-in user's albums.
  • /me/skydrive/shared/albums to get info about all of the signed-in user's shared albums.
  • USER_ID/albums to get info about all of a user's albums that correspond to a valid USER_ID.

You can also do this.

  • Use ALBUM_ID/photos or ALBUM_ID/videos, to get a list of all photos or videos in an album. Then your code can make another call that uses a specific photo ID or video ID to get the info for that photo or video.
  • Use ALBUM_ID/files to get a list of all photos, videos, audio, child albums, and child folders in an album. Then your code can make another call that uses a specific photo ID, video ID, album ID, audio ID, or folder ID to get the info for that photo, video, album, audio, or folder.

    Note You can get info about an album's photos, videos, audio, child albums, and child folders only.

  • Use ALBUM_ID/picture to get a picture of an album's cover.
  • Get a limited number of items by using the limit parameter in the preceding code to specify the number of items to get. For example, to get the first two items, use ALBUM_ID/files?limit=2.
  • Set the first item to start getting by using the offset parameter in the preceding code to specify the index of the first item to get. For example, to get two items starting at the third item, use ALBUM_ID/files?limit=2&offset=3.

    Note In the JavaScript Object Notation (JSON)-formatted object that's returned, you can look in the paging object for the previous and next structures to get the offset and limit parameter values of the previous and next entries.

  • Set the items' sort criteria by using the sort_by parameter in the preceding code to specify the criteria: created, updated, name, size, or default. For example, to sort the items by name, use ALBUM_ID/files?sort_by=name.
  • Set the items' sort order by using the sort_order parameter in the preceding code to specify the order: ascending or descending. For example, to sort the items in descending order, use ALBUM_ID/files?sort_by=descending.

Top

Deleting albums

To remove an album, use code like this. The wl.skydrive_update scope is required.

[JavaScript for Windows Store apps and HTML]

JavaScript
function deleteAlbum_onClick() {
    WL.login({
        scope: "wl.skydrive_update"
    }).then(
        function (response) {
            WL.api({
                path: "folder.a6b2a7e8f2515e5e.A6B2A7E8F2515E5E!165",
                method: "DELETE"
            }).then(
                function (response) {
                    document.getElementById("infoArea").innerText = "Deleted album.";
                },
                function (responseFailed) {
                    document.getElementById("infoArea").innerText =
                        "Error calling API: " + responseFailed.error.message;
                }
            );
        },
        function (responseFailed) {
            document.getElementById("infoArea").innerText =
                "Error signing in: " + responseFailed.error_description;
        }
    );
 }

[C# for Windows Store apps and Windows Phone apps]

C#
private async void btnDeleteAlbum_Click(object sender, RoutedEventArgs e)
{
    try
    {
        LiveConnectClient liveClient = new LiveConnectClient(this.session);
        LiveOperationResult operationResult =
            await liveClient.DeleteAsync("folder.a6b2a7e8f2515e5e.A6B2A7E8F2515E5E!148");
        this.infoTextBlock.Text = "Album deleted.";
    }
    catch (LiveConnectException exception)
    {
        this.infoTextBlock.Text = "Error deleting album: " + exception.Message;
    }
}

[Objective-C for iOS]

ObjectiveC
-(void) deleteAlbum
{
    [self.liveClient deleteWithPath:@"folder.95d463b9efcca0e1.95D463B9EFCCA0E1!108"
                           delegate:self];
}

- (void) liveOperationSucceeded:(LiveOperation *)operation
{
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"API call successful!"
                                                    message:@"Album deleted successfully"
                                                   delegate:self
                                          cancelButtonTitle:@"Ok"
                                          otherButtonTitles:nil,
                          nil];
    [alert show];
    [alert release];
}

[Java for Android]

Java
public void deleteAlbum() {
    String albumid = "folder.a6b2a7e8f2515e5e.A6B2A7E8F2515E5E!137";
    client.deleteAsync(albumid, new LiveOperationListener() {
        public void onError(LiveOperationException exception, LiveOperation operation) {
               resultTextView.setText("Error deleting album: " + exception.getMessage());
           }
        public void onComplete(LiveOperation operation) {
            resultTextView.setText("Album deleted.");
           }
       });
}

[REST]

DELETE https://apis.live.netv5.0/folder.a6b2a7e8f2515e5e.A6B2A7E8F2515E5E!111?access_token=ACCESS_TOKEN

In the preceding code, change the album ID to the album ID of the album that you want to remove.

Top

Creating albums

To add a new album, use code like this. The wl.skydrive_update scope is required.

[JavaScript for Windows Store apps and HTML]

JavaScript
function createAlbum_onClick() {
    WL.login({
        scope: "wl.skydrive_update"
    }).then(
        function (response) {
            WL.api({
                path: "/me/albums",
                method: "POST",
                body: {
                    "name": "My new album",
                    "description": "A new photo album"
                }
            }).then(
                function (response) {
                    document.getElementById("infoArea").innerText =
                        "Created album. Name: " + response.name + ", ID: " + response.id;
                },
                function (responseFailed) {
                    document.getElementById("infoArea").innerText =
                        "Error calling API: " + responseFailed.error.message;
                }
            );
        },
        function (responseFailed) {
            document.getElementById("infoArea").innerText =
                "Error signing in: " + responseFailed.error_description;
        }
    );
}

You can also add a new album by using POST to me/skydrive, and passing the type attribute with a value of "album", as shown here.

JavaScript
...
WL.api({
    path: "/me/skydrive",
    method: "POST",
    body: {
        "name": "My new album",
        "description": "A new photo album"
    }
    type: "album" },
onCreateAlbumComplete);
...

[C# for Windows Store apps and Windows Phone apps]

C#
private async void btnCreateAlbum_Click(object sender, RoutedEventArgs e)
{
    try
    {
        var albumData = new Dictionary<string, object>();
        albumData.Add("name", "A brand new album");
        LiveConnectClient liveClient = new LiveConnectClient(this.session);
        LiveOperationResult operationResult =
            await liveClient.PostAsync("me/albums", albumData);
        dynamic result = operationResult.Result;
        this.infoTextBlock.Text = string.Join(" ", "Created album:", result.name, "ID:", result.id);
    }
    catch (LiveConnectException exception)
    {
        this.infoTextBlock.Text = "Error creating album: " + exception.Message;
    }
}

[Objective-C for iOS]

ObjectiveC
-(void) createAlbum
{
    NSDictionary * newAlbum = [[NSDictionary dictionaryWithObjectsAndKeys:
                                @"Vacation Pics",@"name",
                                @"Family vacation",@"description",
                                @"album",@"type",
                                nil] retain];

    [self.liveClient postWithPath:@"me/skydrive"
                         dictBody:newAlbum
                         delegate:self];
    [newAlbum release];
}

- (void) liveOperationSucceeded:(LiveOperation *)operation
{
    NSString *albumId = [operation.result objectForKey:@"id"];
    NSString *albumName = [operation.result objectForKey:@"name"];
    NSString *albumDescription = [operation.result objectForKey:@"description"];
    NSString *albumLink = [operation.result objectForKey:@"link"];
    NSString *albumType = [operation.result objectForKey:@"type"];
    self.displayLabel.text = [NSString stringWithFormat:
                              @"Album Properties:\n"
                              @"\tId. %@\n"
                              @"\tName. %@\n"
                              @"\tDescription. %@\n"
                              @"\tLink. %@\n"
                              @"\tType. %@\n"
                              , albumId,
                              albumName,
                              albumDescription,
                              albumLink,
                              albumType];
}

[Java for Android]

Java
public void createAlbum() {
    final LiveOperationListener opListener = new LiveOperationListener() {
        public void onError(LiveOperationException exception, LiveOperation operation) {
               resultTextView.setText("Error creating album: " + exception.getMessage());
           }
        public void onComplete(LiveOperation operation) {
            JSONObject result = operation.getResult();
            String text = "Album created:" +
                "\nID = " + result.optString("id") +
                "\nName = " + result.optString("name");
               resultTextView.setText(text);
           }
       };
    auth.login(this, Arrays.asList(new String[] { "wl.skydrive_update" }), new LiveAuthListener() {
        public void onAuthError(LiveAuthException exception, Object userState) {
            resultTextView.setText("Error signing in: " + exception.getMessage());
        }
        public void onAuthComplete(LiveStatus status, LiveConnectSession session, Object userState) {
            try {
                JSONObject body = new JSONObject();
                body.put("name", "MyNewAlbum");
                body.put("description", "My new album");
            client.postAsync("me/albums", body, opListener);
            }
            catch(JSONException ex) {
                resultTextView.setText("Error signing in: " + ex.getMessage());
            }
        }
    });
}

[REST]

POST https://apis.live.net/v5.0/me/albums

Authorization: Bearer ACCESS_TOKEN
Content-Type: application/json

{
    "name": "My example album"
}

Note You can only create albums in the user's top-level SkyDrive folder, represented here as me/albums.

For details about the minimum required and optional structures that your app must provide when using POST, see the "Album object" section in REST reference.

Top

Updating albums

To change info for an existing album, use code like this. The wl.skydrive_update scope is required.

[JavaScript for Windows Store apps and HTML]

JavaScript
function updateAlbumProperties_onClick() {
    WL.login({
        scope: "wl.skydrive_update"
    }).then(
        function (response) {
            WL.api({
                path: "folder.a6b2a7e8f2515e5e.A6B2A7E8F2515E5E!165",
                method: "PUT",
                body: {
                    name: "My new sample album name"
                }
            }).then(
                function (response) {
                    document.getElementById("infoArea").innerText =
                        "Updated album. Name: " + response.name + ", ID: " + response.id;
                },
                function (responseFailed) {
                    document.getElementById("infoArea").innerText =
                        "Error calling API: " + responseFailed.error.message;
                }
            );
        },
        function (responseFailed) {
            document.getElementById("infoArea").innerText =
                "Error signing in: " + responseFailed.error_description;
        }
    );
}

[C# for Windows Store apps and Windows Phone apps]

C#
private async void btnUpdateAlbum_Click(object sender, RoutedEventArgs e)
{
    try
    {
        var albumData = new Dictionary<string, object>();
        albumData.Add("name", "Nature Photography 2");
        LiveConnectClient liveClient = new LiveConnectClient(this.session);
        LiveOperationResult operationResult =
            await liveClient.PostAsync("folder.8c8ce076ca27823f.8C8CE076CA27823F!134", albumData);
        dynamic result = operationResult.Result;
        this.infoTextBlock.Text = "Album updated:" + result.name;
    }
    catch (LiveConnectException exception)
    {
        this.infoTextBlock.Text = "Error updating album: " + exception.Message;
    }
}

[Objective-C for iOS]

ObjectiveC
-(void) updateAlbum
{
    NSDictionary * updatedAlbum = [[NSDictionary dictionaryWithObjectsAndKeys:
                                    @"2011 photo album",@"description",
                                    nil] retain];
    [self.liveClient putWithPath:@"folder.95d463b9efcca0e1.95D463B9EFCCA0E1!108"
                        dictBody:updatedAlbum
                        delegate:self];
    [updatedAlbum release];
}

- (void) liveOperationSucceeded:(LiveOperation *)operation
{
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"API call successful!"
                                                    message:@"Album updated successfully"
                                                   delegate:self
                                          cancelButtonTitle:@"Ok"
                                          otherButtonTitles:nil,
                          nil];
    [alert show];
    [alert release];
}

[Java for Android]

Java
public void updateAlbum() {
    final String albumId = "folder.a6b2a7e8f2515e5e.A6B2A7E8F2515E5E!111";
    final LiveOperationListener opListener = new LiveOperationListener() {
        public void onError(LiveOperationException exception, LiveOperation operation) {
               resultTextView.setText("Error updating album: " + exception.getMessage());
           }
        public void onComplete(LiveOperation operation) {
            JSONObject result = operation.getResult();
            String text = "Album updated:" +
                "\nID = " + result.optString("id") +
                "\nName = " + result.optString("name");
               resultTextView.setText(text);
           }
       };
    auth.login(this, Arrays.asList(new String[] { "wl.skydrive_update" }),
        new LiveAuthListener() {
               public void onAuthError(LiveAuthException exception, Object userState) {
                   resultTextView.setText("Error signing in: " + exception.getMessage());
               }
            public void onAuthComplete(LiveStatus status, LiveConnectSession session, Object userState) {
                try {
                    JSONObject body = new JSONObject();
                    body.put("name", "MyChangedAlbum");
                    body.put("description", "My changed album");
                       client.putAsync(albumId, body, opListener);
                }
                catch(JSONException ex) {
                    resultTextView.setText("Error updating album: " + ex.getMessage());
                }
               }
        }
    );
}

[REST]

PUT https://apis.live.net/v5.0/folder.a6b2a7e8f2515e5e.A6B2A7E8F2515E5E!111

Authorization: Bearer ACCESS_TOKEN
Content-Type: application/json

{
    "name": "My example album has changed"
}

For details about the minimum required and optional structures that your app must provide when using PUT, see the "Album object" section in REST reference.

Top

Reading photo, video, and audio properties and their contents

To get info about a photo, video, or audio, use code like this. The wl.skydrive scope is required.

[JavaScript for Windows Store apps and HTML]

JavaScript
function readPhotoProperties_onClick() {
    WL.login({
        scope: "wl.skydrive"
    }).then(
        function (response) {
            WL.api({
                path: "file.a6b2a7e8f2515e5e.A6B2A7E8F2515E5E!131",
                method: "GET"
            }).then(
                function (response) {
                    document.getElementById("infoArea").innerText =
                        "Photo properties: name = " + response.name + ", ID = " + response.id;
                },
                function (responseFailed) {
                    document.getElementById("infoArea").innerText =
                        "Error calling API: " + responseFailed.error.message;
                }
            );
        },
        function (responseFailed) {
            document.getElementById("infoArea").innerText =
                "Error signing in: " + responseFailed.error_description;
        }
    );
 }

[C# for Windows Store apps and Windows Phone apps]

C#
private async void btnReadPhoto_Click(object sender, RoutedEventArgs e)
{
    try
    {
        LiveConnectClient liveClient = new LiveConnectClient(this.session);
        StorageFile pngFile = await ApplicationData.Current.LocalFolder.GetFileAsync("photo.png");
        await liveClient.BackgroundDownloadAsync("file.8c8ce076ca27823f.8C8CE076CA27823F!129/picture?type=thumbnail", pngFile);
        var imgSource = new BitmapImage();
        imgSource.SetSource(await pngFile.OpenReadAsync());
        imgResult.Source = imgSource;
        this.infoTextBlock.Text = "Photo downloaded.";
    }
    catch (LiveConnectException exception)
    {
        this.infoTextBlock.Text = "Error downloading photo: " + exception.Message;
    }
}

[Objective-C for iOS]

ObjectiveC
-(void) getFileProperties
{
    [self.liveClient getWithPath:@"file.95d463b9efcca0e1.95D463B9EFCCA0E1!113"
                        delegate:self];
}

- (void) liveOperationSucceeded:(LiveOperation *)operation
{
    NSString *fileId = [operation.result objectForKey:@"id"];
    NSString *fileName = [operation.result objectForKey:@"name"];
    NSString *fileDescription = [operation.result objectForKey:@"description"];
    NSString *fileSize = [operation.result objectForKey:@"size"];
    self.displayLabel.text = [NSString stringWithFormat:
                              @"File Properties:\n"
                              @"\tId. %@\n"
                              @"\tName. %@\n"
                              @"\tDescription. %@\n"
                              @"\tSize. %@\n"
                              , fileId,
                              fileName,
                              fileDescription,
                              fileSize];
}

[Java for Android]

Java
public void readPhoto() {
    String photoId = "file.a6b2a7e8f2515e5e.A6B2A7E8F2515E5E!131";
       client.getAsync(photoId , new LiveOperationListener() {
        public void onError(LiveOperationException exception, LiveOperation operation) {
               resultTextView.setText("Error reading photo: " + exception.getMessage());
           }
        public void onComplete(LiveOperation operation) {
            JSONObject result = operation.getResult();
            String text = "Photo info: " +
                "\nID = " + result.optString("id") +
                "\nName = " + result.optString("name");
               resultTextView.setText(text);
           }
       });
}

Note Secure Hypertext Transfer Protocol (HTTPS) is not supported for audio and video playback in Android versions earlier than 3.1. SkyDrive uses HTTPS by default, so to return an HTTP URL that will work with Android versions earlier than 3.1, add the return_https_resource=false query parameter to the file ID for audio or video files.

For example, to use the preceding code example with a video or audio file on an Android OS earlier than 3.1, the file ID string would look like this with the query string added to the file ID.

file.a6b2a7e8f2515e5e.A6B2A7E8F2515E5E!131?return_https_resource=false

For more info about media format support in Android, see Android Supported Media Formats.

[REST]

GET https://apis.live.netv5.0/photo.a6b2a7e8f2515e5e.A6B2A7E8F2515E5E!112?access_token=ACCESS_TOKEN

In the preceding code, change the photo ID to a different photo ID, video ID, or audio ID to get info about another photo, video, or audio.

You can also do this.

  • Get a picture of a photo or video by using /picture with the optional type parameter in the preceding code and one of these values: small, normal (default if the type parameter is not specified), album, thumbnail, or full. For example, to get a photo's thumbnail picture, use PHOTO_ID/picture?type=thumbnail.
  • Get a video's contents by using VIDEO_ID/video.

Top

Updating photo, video, and audio properties

To change info about a photo, video, or audio, use code like this. The wl.skydrive_update scope is required.

[JavaScript for Windows Store apps and HTML]

JavaScript
function updatePhotoProperties_onClick() {
    WL.login({
        scope: "wl.skydrive_update"
    }).then(
        function (response) {
            WL.api({
                path: "file.a6b2a7e8f2515e5e.A6B2A7E8F2515E5E!131",
                method: "PUT",
                body: {
                    name: "Hydrangeas2.jpg"
                }
            }).then(
                function (response) {
                    document.getElementById("infoArea").innerText =
                        "Updated photo properties. Name: " + response.name + ", ID: " + response.id;
                },
                function (responseFailed) {
                    document.getElementById("infoArea").innerText =
                        "Error calling API: " + responseFailed.error.message;
                }
            );
        },
        function (responseFailed) {
            document.getElementById("infoArea").innerText =
                "Error signing in: " + responseFailed.error_description;
        }
    );
}

[C# for Windows Store apps and Windows Phone apps]

C#
private async void btnUpdatePhoto_Click(object sender, RoutedEventArgs e)
{
    try
    {
        var photoData = new Dictionary<string, object>();
        photoData.Add("name", "Tulips21.jpg");
        LiveConnectClient liveClient = new LiveConnectClient(this.session);
        LiveOperationResult operationResult =
            await liveClient.PutAsync("file.8c8ce076ca27823f.8C8CE076CA27823F!129", photoData);
        this.infoTextBlock.Text = "Photo renamed.";
    }
    catch (LiveConnectException exception)
    {
        this.infoTextBlock.Text = "Error renaming photo: " + exception.Message;
    }
}

[Objective-C for iOS]

ObjectiveC
-(void) updateFileProperty
{
    NSDictionary * updatedFile = [[NSDictionary dictionaryWithObjectsAndKeys:
                                   @"Having fun at the beach",@"description",
                                   nil] retain];
    [self.liveClient putWithPath:@"file.95d463b9efcca0e1.95D463B9EFCCA0E1!113"
                        dictBody:updatedFile
                        delegate:self];
    [updatedFile release];
}

- (void) liveOperationSucceeded:(LiveOperation *)operation
{
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"API call successful!"
                                                    message:@"File updated successfully"
                                                   delegate:self
                                          cancelButtonTitle:@"Ok"
                                          otherButtonTitles:nil,
                          nil];
    [alert show];
    [alert release];
}

[Java for Android]

Java
public void updatePhoto() {
    final String fileId = "file.a6b2a7e8f2515e5e.A6B2A7E8F2515E5E!131";
    final LiveOperationListener opListener = new LiveOperationListener() {
        public void onError(LiveOperationException exception, LiveOperation operation) {
               resultTextView.setText("Error updating photo: " + exception.getMessage());
           }
        public void onComplete(LiveOperation operation) {
            JSONObject result = operation.getResult();
            String text = "Photo updated:" +
                "\nID = " + result.optString("id") +
                "\nName = " + result.optString("name");
               resultTextView.setText(text);
           }
       };
    auth.login(this, Arrays.asList(new String[] { "wl.skydrive_update" }),
        new LiveAuthListener() {
               public void onAuthError(LiveAuthException exception, Object userState) {
                   resultTextView.setText("Error signing in: " + exception.getMessage());
               }
            public void onAuthComplete(LiveStatus status, LiveConnectSession session, Object userState) {
                try {
                    JSONObject body = new JSONObject();
                    body.put("name", "Hydrangeas3.jpg");
                    body.put("description", "Pretty flowers");
                       client.putAsync(fileId, body, opListener);
                }
                catch(JSONException ex) {
                    resultTextView.setText("Error updating photo: " + ex.getMessage());
                }
               }
        }
    );
}

[REST]

PUT https://apis.live.net/v5.0/photo.a6b2a7e8f2515e5e.A6B2A7E8F2515E5E!112

Authorization: Bearer ACCESS_TOKEN
Content-Type: application/json

{
    "name": "My example photo has changed"
}

In the preceding code, change the photo ID to the photo ID, video ID, or audio ID of the photo, video, or audio for which you want to update the properties.

For details about the minimum required and optional structures that your app must provide when using PUT, see the "Photo object", "Video object", or "Audio object" section in REST reference.

Top

Uploading, updating, and deleting photos, videos, and audios

The Live Connect APIs consider a photo, video, or audio to be the same as a file when uploading, updating, and deleting the contents of a photo, video, or audio.

To add the contents of a photo, video, or audio, see the "Uploading files" section in Folders and files.

To update the contents of a photo, video, or audio, see the "Updating uploaded files" section in Folders and files.

To delete the contents of a photo, video, or audio contents, see the "Deleting uploaded files" section in Folders and files.

Top

Reading tags

To get info about tags, use code like this. The wl.skydrive scope is required.

[JavaScript for Windows Store apps and HTML]

JavaScript
function enumeratePhotoTags_onClick() {
    WL.login({
        scope: "wl.skydrive"
    }).then(
        function (response) {
            WL.api({
                path: "file.a6b2a7e8f2515e5e.A6B2A7E8F2515E5E!131/tags",
                method: "GET"
            }).then(
                function (response) {
                    msg = "People tagged in the photo: ";
                    items = response.data;
                    for (index in items) {
                        if (index != 0)
                            msg += ", "
                        msg += items[index].user.name;
                    }
                    document.getElementById("infoArea").innerText = msg;
                },
                function (responseFailed) {
                    document.getElementById("infoArea").innerText =
                        "Error calling API: " + responseFailed.error.message;
                }
            );
        },
        function (responseFailed) {
            document.getElementById("infoArea").innerText =
                "Error signing in: " + responseFailed.error_description;
        }
    );
}

[C# for Windows Store apps and Windows Phone apps]

C#
private async void btnReadTag_Click(object sender, RoutedEventArgs e)
{
    try
    {
        LiveConnectClient liveClient = new LiveConnectClient(this.session);
        LiveOperationResult operationResult =
            await liveClient.GetAsync("file.8c8ce076ca27823f.8C8CE076CA27823F!129/tags");
        StringBuilder tags = new StringBuilder("People tagged:\n");
        dynamic result = operationResult.Result;
        dynamic data = result.data;
        if (data.Count > 0)
        {
            foreach (dynamic userData in data)
            {
                dynamic user = userData.user;
                if (user != null)
                {
                    if (user.name != null)
                    {
                        if (tags.Length != 0)
                        {
                            tags.Append("\n");
                        }
                        tags.Append("\t");
                        tags.Append(user.name);
                        tags.Append("\n");
                        tags += "\t" + user["name"].ToString() + "\n";
                    }
                }
            }
            this.infoTextBlock.Text = tags.ToString();
        }
        else
        {
            this.infoTextBlock.Text = "No tags.";
        }
    }
    catch (LiveConnectException exception)
    {
        this.infoTextBlock.Text = "Error getting tag(s) info: " + exception.Message;
    }
}

[Objective-C for iOS]

ObjectiveC
-(void) getPhotoTags
{
    [self.liveClient getWithPath:@"file.95d463b9efcca0e1.95D463B9EFCCA0E1!116/tags"
                        delegate:self];
}

- (void) liveOperationSucceeded:(LiveOperation *)operation
{
    NSArray *tags = [operation.result objectForKey:@"data"];
    for (NSDictionary *tag in tags)
    {
        NSDictionary *userInfo = [tag objectForKey:@"user"];
        NSString *positionX = [tag objectForKey:@"x"];
        NSString *positionY = [tag objectForKey:@"y"];
        NSString *tagId = [tag objectForKey:@"id"];
        NSString *userId = [userInfo objectForKey:@"id"];
        NSString *userName = [userInfo objectForKey:@"name"];
        self.displayLabel.text = [NSString stringWithFormat:
                                  @"Tag Properties:\n"
                                  @"\tId. %@\n"
                                  @"\tUser Id. %@\n"
                                  @"\tUser Name. %@\n"
                                  @"\tPosition X. %@\n"
                                  @"\tPosition Y. %@\n"
                                  , tagId,
                                  userId,
                                  userName,
                                  positionX,
                                  positionY];
    }
}

[Java for Android]

Java
public void readTags() {
    String photoId = "file.a6b2a7e8f2515e5e.A6B2A7E8F2515E5E!131/tags";
       client.getAsync(photoId , new LiveOperationListener() {
        public void onError(LiveOperationException exception, LiveOperation operation) {
               resultTextView.setText("Error reading tags: " + exception.getMessage());
           }
        public void onComplete(LiveOperation operation) {
            JSONObject result = operation.getResult();
            String msg = "Tag info:\n";
            JSONArray  items = result.optJSONArray("data");
            for (int i = 0; i < items.length(); i++) {
                JSONObject tag = items.optJSONObject(i);
                JSONObject user = tag.optJSONObject("user");
                msg += user.optString("name") + "\n";
            }
               resultTextView.setText(msg);
           }
       });
}

[REST]

GET https://apis.live.netv5.0/file.a6b2a7e8f2515e5e.A6B2A7E8F2515E5E!131/tags?access_token=ACCESS_TOKEN

In the preceding code, change the photo ID to a different photo ID, video ID, or audio ID, to get info about the tags for another photo, video, or audio. You can also specify a tag's ID to get info about that individual tag.

You can also do this:

  • Get a limited number of tags by using the limit parameter in the preceding code to specify the number of items to get. For example, to get the first two tags, use PHOTO_ID/tags?limit=2.
  • Set the first tag to start getting by using the offset parameter in the preceding code to specify the index of the first item to get. For example, to get two items starting at the third item, use PHOTO_ID/tags?limit=2&offset=3.

    Note In the JSON-formatted object that's returned, you can look in the paging object for the previous and next structures to get the offset and limit parameter values of the previous and next entries.

Top

Deleting tags

To delete a tag, use code like the following. The wl.skydrive_update scope is required.

Note Only the owner of an item can delete that item's tags.

[JavaScript for Windows Store apps and HTML]

JavaScript
function deleteTag_onClick() {
    WL.login({
        scope: "wl.skydrive_update"
    }).then(
        function (response) {
            WL.api({
                path: "tag.a6b2a7e8f2515e5e.A6B2A7E8F2515E5E!131.OnqQnWO_Ye9L3fTKW154K7jHQvM",
                method: "DELETE"
            }).then(
                function (response) {
                    document.getElementById("infoArea").innerText = "Tag deleted.";
                },
                function (responseFailed) {
                    document.getElementById("infoArea").innerText =
                        "Error calling API: " + responseFailed.error.message;
                }
            );
        },
        function (responseFailed) {
            document.getElementById("infoArea").innerText =
                "Error signing in: " + responseFailed.error_description;
        }
    );
}

[C# for Windows Store apps and Windows Phone apps]

C#
private async void btnDeleteTag_Click(object sender, RoutedEventArgs e)
{
    try
    {
        LiveConnectClient liveClient = new LiveConnectClient(this.session);
        LiveOperationResult operationResult =
            await liveClient.DeleteAsync("tag.22688711f5410e6c.22688711f5410e6c!767.PRaXZrdHI1uYGQYi9CU0StrzHak");
        this.infoTextBlock.Text = "Tag deleted.";
    }
    catch (LiveConnectException exception)
    {
        this.infoTextBlock.Text = "Error deleting tag: " + exception.Message;
    }
}

[Objective-C for iOS]

ObjectiveC
-(void) deleteTags
{
    [self.liveClient deleteWithPath:@"tag.95d463b9efcca0e1.95d463b9efcca0e1!116.0c6Cdgik364WTnvMuzvSGOqadrc"
                           delegate:self];
}

- (void) liveOperationSucceeded:(LiveOperation *)operation
{
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"API call successful!"
                                                    message:@"Tag deleted successfully"
                                                   delegate:self
                                          cancelButtonTitle:@"Ok"
                                          otherButtonTitles:nil,
                          nil];
    [alert show];
    [alert release];
}

[Java for Android]

Java
public void deleteTag() {
    String tagId = "tag.2e82e8a5445fe036.2e82e8a5445fe036!1111.47CinUEOE1qvXn3UqNHvV2EkAKg";
    client.deleteAsync(tagId , new LiveOperationListener() {
        public void onError(LiveOperationException exception, LiveOperation operation) {
               resultTextView.setText("Error deleting tag: " + exception.getMessage());
           }
        public void onComplete(LiveOperation operation) {
            resultTextView.setText("Tag deleted.");
           }
       });
}

[REST]

DELETE https://apis.live.net/v5.0/tag.a6b2a7e8f2515e5e.A6B2A7E8F2515E5E!131.PlP_Zr6OeZfqtMa%3DJVLP11mNcD0?access_token=ACCESS_TOKEN

In the preceding code, change the tag ID to the tag ID of the tag that you want to remove.

Top

Creating tags

To create a tag, use code like the following. The wl.skydrive_update scope is required.

Tip You can create tags for items that are owned by, or shared with, the signed-in user.

  • To create a tag for an item that is owned by the signed-in user, replace the photo ID with the item's ID in the code that follows.
  • To create a tag for an item that is shared with the signed-in user, first use the wl.contacts_skydrive scope to make a GET request to /USER_ID/skydrive/shared, where USER_ID is either me or the user ID of the consenting user. Then, if the item is included in the response, replace the photo ID with the item's ID in the code that follows.

[JavaScript for Windows Store apps and HTML]

JavaScript
function createTag_onClick() {
    WL.login({
        scope: "wl.skydrive_update"
    }).then(
        function (response) {
            WL.api({
                path: "file.a6b2a7e8f2515e5e.A6B2A7E8F2515E5E!131/tags",
                method: "POST",
                body: {
                    "user": {
                        "name": "Stig Struve-Christensen",
                        "id": "a6b2a7e8f2515e5e"
                    },
                    "x": 0.5,
                    "y": 0.5
                }
            }).then(
                function (response) {
                    document.getElementById("infoArea").innerText = "Tag created.";
                },
                function (responseFailed) {
                    document.getElementById("infoArea").innerText =
                        "Error calling API: " + responseFailed.error.message;
                }
            );
        },
        function (responseFailed) {
            document.getElementById("infoArea").innerText =
                "Error signing in: " + responseFailed.error_description;
        }
    );
}

[C# for Windows Store apps and Windows Phone apps]

C#
private async void btnCreateTag_Click(object sender, RoutedEventArgs e)
{
    try
    {
        var userData = new Dictionary<string, object>();
        userData.Add("name", "Roberto Tamburello");
        userData.Add("id", "8c8ce076ca27823f");
        var tagData = new Dictionary<string, object>();
        tagData.Add("user", userData);
        tagData.Add("x", 43.8986);
        tagData.Add("y", 54.4138);
        LiveConnectClient liveClient = new LiveConnectClient(this.session);
        LiveOperationResult operationResult =
            await liveClient.PostAsync("file.8c8ce076ca27823f.8C8CE076CA27823F!129/tags", tagData);
        dynamic result = operationResult.Result;
        this.infoTextBlock.Text = string.Join(" ", "Tag created, ID:", result.id);
    }
    catch (LiveConnectException exception)
    {
        this.infoTextBlock.Text = "Error creating tag: " + exception.Message;
    }
}

[Objective-C for iOS]

ObjectiveC
-(void) createTag
{
    NSDictionary * user = [[NSDictionary dictionaryWithObjectsAndKeys:
                            @"John Smith", @"name",
                            nil] retain];
    NSDictionary * newTag = [[NSDictionary dictionaryWithObjectsAndKeys:
                              @"50",@"x",
                              @"70",@"y",
                              user,@"user",
                              nil] retain];
    [self.liveConnectClient postWithPath:@"file.1cfa02017372544c.1CFA02017372544C!209/tags"
                                dictBody:newTag
                                delegate:self];
}

- (void) liveOperationSucceeded:(LiveOperation *)operation
{
    NSDictionary *userInfo = [operation.result objectForKey:@"user"];
    NSString *positionX = [operation.result objectForKey:@"x"];
    NSString *positionY = [operation.result objectForKey:@"y"];
    NSString *tagId = [operation.result objectForKey:@"id"];
    NSString *userId = [userInfo objectForKey:@"id"];
    NSString *userName = [userInfo objectForKey:@"name"];
    self.displayLabel.text = [NSString stringWithFormat:
                              @"Tag Properties:\n"
                              @"\tId. %@\n"
                              @"\tUser Id. %@\n"
                              @"\tUser Name. %@\n"
                              @"\tPosition X. %@\n"
                              @"\tPosition Y. %@\n"
                              , tagId,
                              userId,
                              userName,
                              positionX,
                              positionY];
}

[Java for Android]

Java
public void createTag() {
    final String tagsPath = "file.a6b2a7e8f2515e5e.A6B2A7E8F2515E5E!131/tags";
    final LiveOperationListener opListener = new LiveOperationListener() {
        public void onError(LiveOperationException exception, LiveOperation operation) {
               resultTextView.setText("Error creating tag: " + exception.getMessage());
           }
        public void onComplete(LiveOperation operation) {
            JSONObject result = operation.getResult();
            String text = "Photo tagged:\nID = " + result.optString("id");
               resultTextView.setText(text);
           }
       };
    auth.login(this, Arrays.asList(new String[] { "wl.skydrive_update" }),
        new LiveAuthListener() {
               public void onAuthError(LiveAuthException exception, Object userState) {
                   resultTextView.setText("Error signing in: " + exception.getMessage());
               }
            public void onAuthComplete(LiveStatus status, LiveConnectSession session, Object userState) {
                try {
                    JSONObject body = new JSONObject();
                    body.put("x", 0.5);
                    body.put("y", 0.5);
                    JSONObject user = new JSONObject();
                    user.put("name", "Stig Struve-Christensen");
                    user.put("id", "a6b2a7e8f2515e5e");
                    body.put("user", user);
                       client.postAsync(tagsPath, body, opListener);
                }
                catch(JSONException ex){
                    resultTextView.setText("Error creating tag: " + ex.getMessage());
                }
               }
        }
    );
}

[REST]

POST https://apis.live.netv5.0/file.a6b2a7e8f2515e5e.A6B2A7E8F2515E5E!131/tags

Authorization: Bearer ACCESS_TOKEN
Content-Type: application/json

{
    "user": {
            "name": "Stig Struve-Christensen",
            "id": "a6b2a7e8f2515e5f"
    },
    "x": 0.5,
    "y": 0.5
}

In the preceding code, change the photo ID to a different photo ID, video ID, or audio ID, to add a tag to another photo or video.

For details about the required and optional structures that your app must provide to use POST, see the "Tag object" section in REST reference.

Top


Working with Microsoft SkyDrive comments

Your apps can use the Live Connect APIs to read, delete, and create comments that Microsoft SkyDrive users can add to folders, files, albums, photos, and videos.

  • Reading comments
  • Deleting comments
  • Creating comments

To make full use of the code examples in this topic, you can use them in the context of larger code reference samples that we provide in Working with the code examples. To request the required scopes, see the code patterns in Obtaining user consent.

Reading comments

To get info about comments, use code like this. The wl.photos or wl.skydrive scopes are required.

[JavaScript for Windows Store apps and HTML]

JavaScript
function enumerateItemComments_onClick() {
    WL.login({
        scope: "wl.skydrive"
    }).then(
        function (response) {
            WL.api({
                path: "file.a6b2a7e8f2515e5e.A6B2A7E8F2515E5E!131/comments",
                method: "GET"
            }).then(
                function (response) {
                    msg = "Comments: ";
                    items = response.data;
                        for (index in items) {
                            msg += "\n" + items[index].message +
                                " (" + items[index].from.name + ")"
                        }
                    document.getElementById("infoArea").innerText = msg;
                },
                function (responseFailed) {
                    document.getElementById("infoArea").innerText =
                        "Error calling API: " + responseFailed.error.message;
                }
            );
        },
        function (responseFailed) {
            document.getElementById("infoArea").innerText =
                "Error signing in: " + responseFailed.error_description;
        }
    );
}

[C# for Windows Store apps and Windows Phone apps]

C#
private async void btnReadComment_Click(object sender, RoutedEventArgs e)
{
    try
    {
        LiveConnectClient liveClient = new LiveConnectClient(this.session);
        LiveOperationResult operationResult =
            await liveClient.GetAsync("file.8c8ce076ca27823f.8C8CE076CA27823F!129/comments");
        dynamic result = operationResult.Result;
        dynamic data = result.data;
        StringBuilder comments = new StringBuilder("Comments:\n");
        if (data.Count > 0)
        {
            foreach (dynamic datum in data)
            {
                if (comments.Length != 0)
                {
                    comments.Append("\n");
                }

                comments.Append("\t");
                comments.Append(datum.message);
                comments.Append("\n");
            }

            this.infoTextBlock.Text = comments.ToString();
        }
        else
        {
            this.infoTextBlock.Text = "No comments.";
        }
    }
    catch (LiveConnectException exception)
    {
        this.infoTextBlock.Text = "Error getting comment(s) info: " + exception.Message;
    }
}

[Objective-C for iOS]

ObjectiveC
-(void) readComment
{
    [self.liveConnectClient getWithPath:@"comment.1cfa02017372544c.1CFA02017372544C!209.1CFA02017372544C!222"
                               delegate:self];
}

- (void) liveOperationSucceeded:(LiveOperation *)operation
{
    NSDictionary *from = [operation.result objectForKey:@"from"];
    NSString *commentId = [operation.result objectForKey:@"id"];
    NSString *commentMessage = [operation.result objectForKey:@"message"];
    NSString *commentDate = [operation.result objectForKey:@"created_time"];
    NSString *userId = [from objectForKey:@"id"];
    NSString *userName = [from objectForKey:@"name"];
    self.displayLabel.text = [NSString stringWithFormat:
                              @"Comment Properties:\n"
                              @"\tId. %@\n"
                              @"\tUser Id. %@\n"
                              @"\tUser Name. %@\n"
                              @"\tMessage. %@\n"
                              @"\tCreated Time. %@\n"
                              , commentId,
                              userId,
                              userName,
                              commentMessage,
                              commentDate];
}

[Java for Android]

Java
public void readComments() {
    final String commentspath = "file.a6b2a7e8f2515e5e.A6B2A7E8F2515E5E!131/comments";
    client.getAsync(commentspath , new LiveOperationListener() {
        public void onError(LiveOperationException exception, LiveOperation operation) {
               resultTextView.setText("Error reading comments: " + exception.getMessage());
           }
        public void onComplete(LiveOperation operation) {
            JSONObject result = operation.getResult();
            String msg = "Comment info:";
            JSONArray  items = result.optJSONArray("data");
            for (int i = 0; i < items.length(); i++) {

                JSONObject comment = items.optJSONObject(i);
                msg += "\n" + comment.optString("message") + "-- " + comment.optJSONObject("from").optString("name");
            }
               resultTextView.setText(msg);
           }
       });
}

[REST]

GET https://apis.live.netv5.0/file.a6b2a7e8f2515e5e.A6B2A7E8F2515E5E!131/comments?access_token=ACCESS_TOKEN

In the preceding code, change the photo ID to a different folder ID, file ID, album ID, photo ID, or video ID to get info about comments on another folder, file, album, photo, audio, or video. You can also specify a comment's ID to get info about that individual comment.

You can also do this.

  • Get a limited number of comments by using the limit parameter in the preceding code to specify the number of items to get. For example, to get the first two comments, use PHOTO_ID/comments?limit=2.
  • Set the first comments to start getting by using the offset parameter in the preceding code to specify the index of the first item to get. For example, to get two items starting at the third item, use PHOTO_ID/comments?limit=2&offset=3.

    Note In the JavaScript Object Notation (JSON)-formatted object that's returned, you can look in the paging object for the previous and next structures, if they apply, to get the offset and limit parameter values of the previous and next entries, if they exist.

Top

Deleting comments

To delete a comment, use code like the following. The wl.skydrive_update scope is required.

Note Only the owner of an item can delete that item's comments.

[JavaScript for Windows Store apps and HTML]

JavaScript
function deleteComment_onClick() {
    WL.login({
        scope: "wl.skydrive_update"
    }).then(
        function (response) {
            WL.api({
                path: "comment.a6b2a7e8f2515e5e.A6B2A7E8F2515E5E!131.A6B2A7E8F2515E5E!166",
                method: "DELETE"
            }).then(
                function (response) {
                    document.getElementById("infoArea").innerText = "Comment deleted.";
                },
                function (responseFailed) {
                    document.getElementById("infoArea").innerText =
                        "Error calling API: " + responseFailed.error.message;
                }
            );
        },
        function (responseFailed) {
            document.getElementById("infoArea").innerText =
                "Error signing in: " + responseFailed.error_description;
        }
    );
}

[C# for Windows Store apps and Windows Phone apps]

C#
private async void btnDeleteComment_Click(object sender, RoutedEventArgs e)
{
    try
    {
        LiveConnectClient liveClient = new LiveConnectClient(this.session);
        LiveOperationResult operationResult =
            await liveClient.DeleteAsync("comment.22688711f5410e6c.22688711f0410e6c!818.22688711F5410E6C!979");
        this.infoTextBlock.Text = "Comment deleted.";
    }
    catch (LiveConnectException exception)
    {
        this.infoTextBlock.Text = "Error deleting comment: " + exception.Message;
    }
}

[Objective-C for iOS]

ObjectiveC
-(void) deleteComment
{
    [self.liveConnectClient deleteWithPath:@"comment.1cfa02017372544c.1CFA02017372544C!209.1CFA02017372544C!222"
                                  delegate:self];
}

- (void) liveOperationSucceeded:(LiveOperation *)operation
{
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"API call successful!"
                                                    message:@"Comment deleted successfully"
                                                   delegate:self
                                          cancelButtonTitle:@"Ok"
                                          otherButtonTitles:nil,
                          nil];
    [alert show];
    [alert release];
}

[Java for Android]

Java
public void deleteComment() {
    String commentId = "comment.2e82e8a5445fe036.2e82e8a5445fe036!571.2E82E8A5445FE036!578";
    client.deleteAsync(commentId , new LiveOperationListener() {
        public void onError(LiveOperationException exception, LiveOperation operation) {
            resultTextView.setText("Error deleting comment: " + exception.getMessage());
        }
        public void onComplete(LiveOperation operation) {
            resultTextView.setText("Comment deleted.");
        }
       });
}

[REST]

DELETE https://apis.live.net/v5.0/comment.a6b2a7e8f2515e5e.A6B2A7E8F2515E5E!131.A6B2A7E8F2515E5E!160?access_token=ACCESS_TOKEN

In the preceding code, change the comment ID to the comment ID of the comment that you want to remove.

Top

Creating comments

To create a comment, use code like the following. The wl.skydrive_update scope is required.

Tip You can create comments for items that are owned by, or shared with, the signed-in user:

  • To create a comment for an item that is owned by the signed-in user, replace the photo ID with the item's ID in the code that follows.
  • To create a comment for an item that is shared with the signed-in user, first use the wl.contacts_skydrive scope to make a GET request to /USER_ID/skydrive/shared, where USER_ID is either me or the user ID of the consenting user. Then, if the item is included in the response, replace the photo ID with the item's ID in the code that follows.

[JavaScript for Windows Store apps and HTML]

JavaScript
function createComment_onClick() {
    WL.login({
        scope: "wl.skydrive_update"
    }).then(
        function (response) {
            WL.api({
                path: "file.a6b2a7e8f2515e5e.A6B2A7E8F2515E5E!131/comments",
                method: "POST",
                body: {
                    "message": "Nice picture!"
                }
            }).then(
                function (response) {
                    document.getElementById("infoArea").innerText =
                        "Comment created. ID = " + response.id;
                },
                function (responseFailed) {
                    document.getElementById("infoArea").innerText =
                        "Error calling API: " + responseFailed.error.message;
                }
            );
        },
        function (responseFailed) {
            document.getElementById("infoArea").innerText =
                "Error signing in: " + responseFailed.error_description;
        }
    );
}

[C# for Windows Store apps and Windows Phone apps]

C#
private async void btnCreateComment_Click(object sender, RoutedEventArgs e)
{
    try
    {
        var commentData = new Dictionary<string, object>();
        commentData.Add("message", "Tulips for Springtime.");
        LiveConnectClient liveClient = new LiveConnectClient(this.session);
        LiveOperationResult operationResult =
            await liveClient.PostAsync("file.8c8ce076ca27823f.8C8CE076CA27823F!129/comments", commentData);
        dynamic result = operationResult.Result;
        this.infoTextBlock.Text = "Comment created, ID: " + result.id;
    }
    catch (LiveConnectException exception)
    {
        this.infoTextBlock.Text = "Error creating comment: " + exception.Message;
    }
}

[Objective-C for iOS]

ObjectiveC
-(void) createComment
{
    NSDictionary * newComment = [[NSDictionary dictionaryWithObjectsAndKeys:
                                  @"nice pic!!", @"message",
                                  nil] retain];
        [self.liveConnectClient postWithPath:@"file.1cfa02017372544c.1CFA02017372544C!209/comments"
                                    dictBody:newComment
                                    delegate:self];
}

- (void) liveOperationSucceeded:(LiveOperation *)operation
{
    NSDictionary *from = [operation.result objectForKey:@"from"];
    NSString *commentId = [operation.result objectForKey:@"id"];
    NSString *commentMessage = [operation.result objectForKey:@"message"];
    NSString *commentDate = [operation.result objectForKey:@"created_time"];
    NSString *userId = [from objectForKey:@"id"];
    NSString *userName = [from objectForKey:@"name"];
    self.displayLabel.text = [NSString stringWithFormat:
                              @"Comment Properties:\n"
                              @"\tId. %@\n"
                              @"\tUser Id. %@\n"
                              @"\tUser Name. %@\n"
                              @"\tMessage. %@\n"
                              @"\tCreated Time. %@\n"
                              , commentId,
                              userId,
                              userName,
                              commentMessage,
                              commentDate];
}

[Java for Android]

Java
public void createComment() {
    final String commentsPath = "file.a6b2a7e8f2515e5e.A6B2A7E8F2515E5E!131/comments";
    final LiveOperationListener opListener = new LiveOperationListener() {
        public void onError(LiveOperationException exception, LiveOperation operation) {
               resultTextView.setText("Error creating comment: " + exception.getMessage());
           }
        public void onComplete(LiveOperation operation) {
            JSONObject result = operation.getResult();
            String text = "Comment created:\nID = " + result.optString("id");
               resultTextView.setText(text);
           }
       };
    auth.login(this, Arrays.asList(new String[] { "wl.skydrive_update" }),
        new LiveAuthListener() {
               public void onAuthError(
                   LiveAuthException exception,
                   Object userState) {
                   resultTextView.setText("Error signing in: " + exception.getMessage());
               }
            public void onAuthComplete(LiveStatus status, LiveConnectSession session, Object userState) {
                try {
                    JSONObject body = new JSONObject();
                    body.put("message", "Nice picture!");
                       client.postAsync(commentsPath, body, opListener);
                }
                catch(JSONException ex){
                    resultTextView.setText("Error creating comment: " + ex.getMessage());
                }
               }
        }
    );
}

[REST]

POST https://apis.live.netv5.0/file.a6b2a7e8f2515e5e.A6B2A7E8F2515E5E!131/comments

Authorization: Bearer ACCESS_TOKEN
Content-Type: application/json

{
    "message": "Nice picture!"
}

In the preceding code, change the photo ID to a different folder ID, file ID, album ID, photo ID, or video ID, to add a comment to another folder, file, album, photo, or video.

Note You cannot create a comment unless the associated resource (for example, the file or photo) is already shared.

For details about the required and optional structures that your app must provide to use POST, see the "Comment object" section in REST reference.

Top


Microsoft SkyDrive file picker for web apps

Live Connect provides the Microsoft SkyDrive file picker, a pre-built, consistent user interface that enables your JavaScript-based web apps to get either a folder location or a list of files from your user. Your web app can then use this info to upload or download files to and from the user's SkyDrive storage location.

Note The SkyDrive file picker is provided as part of the Live Connect JavaScript API (web) and therefore is available only for JavaScript-based web apps. For Windows Store apps, use a comparable user experience that Windows 8 already provides—for example, the various classes in the Windows.Storage.Pickers namespace. For all other app types, you'll have to provide your own user experience.

  • Supported web browsers
  • Scenarios
  • Coding techniques
  • JSON format for folder and file lists
  • Related info

Supported web browsers

The following web browsers support the SkyDrive file picker:

  • Microsoft Internet Explorer, starting with version 8
  • Mozilla Firefox, starting with version 10
  • Apple Safari, starting with version 5.1
  • Google Chrome, starting with version 17

Top

Scenarios

There are two primary scenarios for using the SkyDrive file picker. In both scenarios, your web app needs to get from the user a list of files to upload to or download from SkyDrive. The file picker provides a user interface that's presented and branded in a familiar way and saves you coding time.

In the first scenario, your web app displays a pre-built button with the SkyDrive logo to upload or download files to or from SkyDrive. After the user clicks this button, the SkyDrive file picker appears.

In the second scenario, your web app displays the SkyDrive file picker in response to the user interacting with your web app's UI (other than clicking the SkyDrive button), or your app displays the SkyDrive file picker proactively, without prior user interaction.

After the SkyDrive file picker appears, to upload a file, the user clicks the SkyDrive folder to upload the file to, and then clicks Save. To download files by using the file picker, the user clicks the combination of folders or files or both to download, and then clicks Open. After the user clicks Save or Open, the file picker returns the user-selected list of folders or files, or both, to your web app. Your web app then uses this list to upload or download the files to or from SkyDrive.

Top

Coding techniques

After you determine which SkyDrive file picker scenario you want to use, you can use the following coding techniques in your web app.

Display the SkyDrive button by calling the WL.ui method

To display the SkyDrive button, create a <div> tag and then call the WL.ui method. If your web app is uploading a file, you also create a <form> tag and an <input> tag to get info about the file to upload. (You can upload only one file at a time.)

The <div> tag must include an id attribute set to a unique value.

The <form> tag must contain one and only one <input> tag. This <input> tag must include name, type, and id attributes. The value of the name and type attributes must be "file". (The id attribute can be set to any value, which is referred to by the WL.upload function's element parameter.) The user must provide info about the file to this <input> tag—typically by clicking the <input> tag's accompanying Browse button and following the on-screen directions—before clicking the SkyDrive button; otherwise the call to the WL.upload method later will fail.

The WL.ui method accepts these parameters:

  • The required name parameter specifies the type of user interface control to display. The value of this parameter is always skydrivepicker.
  • The required mode parameter specifies the text to display on the SkyDrive button. Specify save to display the text "Save to my SkyDrive" to upload a file. Specify open to display the text "Choose from my SkyDrive" to download files.
  • The optional lightbox_color parameter specifies the color theme for the SkyDrive button. Specify white (default), grey, or transparent.
  • The theme parameter specifies the color of the picker button. The parameter is optional and the default value is white, if it is not specified. The other legal value is blue.
  • The required select parameter specifies whether the user can select a single file or folder (specify single) or multiple files and folders (specify multi).
  • The required element parameter specifies the id attribute of the <div> tag that displays the SkyDrive button.
  • The required callback parameter specifies the name of the app-defined function that the WL.ui method will call after the user clicks the file picker's Save or Open button.

When the user clicks the SkyDrive button, the file picker appears. After the user clicks Save or Open, the WL.ui method calls the function that's specified in its callback parameter. In the callback function, get the SkyDrive upload location (to upload the user-selected file to) or the list of SkyDrive download locations (to download the user-selected files from). Then either call the WL.upload method and supply the SkyDrive upload location and info about the user-selected file, or call the WL.download method and supply the list of SkyDrive download locations.

You can get the SkyDrive upload location from the JavaScript Object Notation (JSON)-formatted data that's returned from the WL.ui method call. From that data, get the value of response.data.folders[0].id, where response is the name of the parameter that's specified in the WL.ui method's onSuccess parameter. For more info, see "JSON format for folder and file lists" later in this topic.

You can also get the list of SkyDrive download locations from the JSON-formatted data that's returned from the WL.ui method call. Loop through the response.data.folders and response.data.files arrays, where response is the name of the parameter that's specified in the WL.ui method's onSuccess parameter. For more info, see "JSON format for folder and file lists" later in this topic.

The WL.upload method accepts these parameters:

  • The required path parameter specifies the unique SkyDrive folder ID to upload the file to. (You can upload only one file at a time.)
  • The required file_name parameter specifies the user-defined or app-defined name of the file to upload. (Do not include the file name extension.)
  • The required element parameter specifies the id attribute of the <input> tag.
  • For the optional overwrite parameter, you can specify true to overwrite any existing file in SkyDrive with the same name in the specified folder. Or you can specify false (the default) to prevent overwriting; if any file with the same name in the specified SkyDrive folder exists, the WL.upload method call will fail. Finally, you can specify rename to upload the file to the specified folder even if a file in SkyDrive exists with the same name in the specified folder; in this case, SkyDrive chooses the uploaded file's name and ignores the value of the file_name parameter. (In this case, the renamed file will start with the name of the existing file and will end with a sequential number.)

If the WL.upload method call is successful, you can use its then method's onSuccess parameter to report the success. Otherwise, you can use its then method's onError parameter to report an unsuccessful call. To check the progress of the WL.upload method call, you can use its then method's onProgress parameter; however, checking progress applies to newer web browsers such as Internet Explorer 10 only.

The WL.download method accepts only one parameter:

  • The required path parameter specifies the unique SkyDrive file ID of the file to download.

If the WL.download method call is unsuccessful, you can use its then method's onError parameter to report the error. (In this case, the WL.download doesn't support the onSuccess and onProgress parameters.) If the WL.download method call is successful, the user experience for actually downloading the files will differ based on the type of web browser in use.

Here's a code example that shows how to upload a file by using a <form> tag, an <input> tag, a <div> tag, the WL.ui method, an app-defined callback function, and the WL.upload method.

HTML
<form>
    <input id="file" name="file" type="file" />
</form>
HTML
<div id="uploadFile_div">SkyDrive save button to appear here</div>
HTML
WL.ui({
    name: "skydrivepicker",
    element: "uploadFile_div",
    mode: "save",
    onselected: onUploadFileCompleted,
    onerror: onUploadFileError
});

function onUploadFileCompleted(response) {
    WL.upload({
        path: response.data.folders[0].id,
        element: "file",
        overwrite: "rename"
    }).then(
        function (response) {
            document.getElementById("info").innerText =
                "File uploaded.";
        },
        function (responseFailed) {
            document.getElementById("info").innerText =
                "Error uploading file: " + responseFailed.error.message;
        }
    );
};

function onUploadFileError(response) {
    document.getElementById("info").innerText =
        "Error getting folder info: " + response.error.message;
}

Here's a code example that shows how to use a <div> tag and the WL.ui method to display a list of files that the user wants to download.

HTML
<div id="downloadFile_div">SkyDrive open button to appear here</div>
HTML
WL.ui({
    name: "skydrivepicker",
    element: "downloadFile_div",
    mode: "open",
    select: "multi",
    onselected: onDownloadFileCompleted,
    onerror: onDownloadFileError
});

function onDownloadFileCompleted(response) {
    var msg = "";
    // For each folder selected...
    if (response.data.folders.length > 0) {
        for (folder = 0; folder < response.data.folders.length; folder++) {
            // Use folder IDs to iterate through child folders and files as needed.
            msg += "\n" + response.data.folders[folder].id;
        }
    }
    // For each file selected...
    if (response.data.files.length > 0) {
        for (file = 0; file < response.data.files.length; file++) {
            // Use file IDs to iterate through files as needed.
            msg += "\n" + response.data.files[file].id;
        }
    }
    document.getElementById("info").innerText =
        "Selected folders/files:" + msg;
};

function onDownloadFileError(responseFailed) {
    document.getElementById("info").innerText =
        "Error getting folder/file info: " + responseFailed.error.message;
}

Display the file picker directly by calling the WL.fileDialog method

You can display the SkyDrive file picker directly—for example, in response to a button that is clicked (other than the SkyDrive button). To do this, if your web app is uploading a file, you must create a <form> tag and an <input> tag to get info about the file to upload. (You can only upload one file at a time.) Then, whether your web app is uploading or downloading files, call the WL.fileDialog method.

For details about the <input> tag, see the previous section.

The WL.fileDialog method accepts the following parameters:

  • The required mode parameter specifies the type of controls that the file picker displays. Specify save for upload controls or open for download controls.
  • The optional lightbox_color parameter specifies the color theme for the file picker's controls. Specify white (default), grey, or transparent.
  • The required select parameter specifies how many files or folders the user can select. Specify single to enable the user to select a single file or folder only, or multi to enable the user to select multiple files and folders.

After the user clicks Save or Open, the WL.filedialog method calls its then method. In the then method's onSuccess parameter, get the SkyDrive upload location (to upload the user-selected file to) or the list of SkyDrive download locations (to download the user-selected files from). Then either call the WL.upload method and supply the SkyDrive upload location and info about the user-selected file, or call the WL.download method and supply the list of SkyDrive download locations.

For details about getting either the SkyDrive upload location or the list of SkyDrive download locations, see the previous section.

For details about the WL.upload and WL.download methods, see the previous section.

Here's a code example that shows how to upload a file by using a <form> tag, an <input> tag, a <button> tag, the WL.fileDialog method, and the WL.upload method.

HTML
<form>
    <input id="file" name="file" type="file" />
</form>
HTML
<button onclick="uploadFile_fileDialog()">Save file with SkyDrive file picker (calling WL.filedialog)</button>
HTML
function uploadFile_fileDialog() {
    WL.fileDialog({
        mode: "save"
    }).then(
        function (response) {
            WL.upload({
                path: response.data.folders[0].id,
                element: "file",
                overwrite: "rename"
            }).then(
                function (response) {
                    document.getElementById("info").innerText =
                        "File uploaded.";
                },
                function (responseFailed) {
                    document.getElementById("info").innerText =
                        "Error uploading file: " + responseFailed.error.message;
                }
            );
        },
        function (responseFailed) {
            document.getElementById("info").innerText =
                "Error getting folder info: " + responseFailed.error.message;
        }
    );
}

Here's a code example that shows how to use a <button> tag and the WL.fileDialog method to display a list of files that the user wants to download.

HTML
<button onclick="downloadFile_fileDialog()">Open file with SkyDrive file picker (calling WL.filedialog)</button>
HTML
function downloadFile_fileDialog() {
    WL.fileDialog({
        mode: "open",
        select: "multi"
    }).then(
        function (response) {
            var msg = "";
            // For each folder selected...
            if (response.data.folders.length > 0) {
                for (folder = 0; folder < response.data.folders.length; folder++) {
                    // Use folder IDs to iterate through child folders and files as needed.
                    msg += "\n" + response.data.folders[folder].id;
                }
            }
            // For each file selected...
            if (response.data.files.length > 0) {
                for (file = 0; file < response.data.files.length; file++) {
                    // Use file IDs to iterate through files as needed.
                    msg += "\n" + response.data.files[file].id;
                }
            }
            document.getElementById("info").innerText =
                "Selected folders/files:" + msg;
        },
        function (responseFailed) {
            document.getElementById("info").innerText =
                "Error getting folder/file info: " + responseFailed.error.message;
        }
    );
}

Top

JSON format for folder and file lists

If the WL.ui or WL.fileDialog method call is successful, the method returns the resulting folder info (for upload or download requests) or file info (for download requests) to your app's code. The folder and file info is returned as a JSON-formatted object. Your app's code can then extract the folder ID and use it to call the WL.upload method (for upload requests), or to extract the folder IDs or file IDs, or both, and use them to call the WL.download method (for download requests).

For upload requests, the JSON-formatted object looks similar to this.

{
    "data": {
        "folders": [
            {
                "id": "folder.a6b2a7e8f2515e5e.A6B2A7E8F2515E5E!110",
                ... Additional info about this folder ...
            }
        ]
    }
}

Note Because only one folder can be selected for an upload request, there is only one object in the returned folders array. Also, no files array is returned.

Your app can then call the WL.upload method, specifying response.data.folders[0].id for the WL.upload method's path parameter. In the example just given, response is the name of the parameter that's specified in the WL.ui or WL.fileDialog method's onSuccess parameter.

For download requests, the JSON-formatted object looks similar to this, depending on the number of folders or files, or both, that are selected.

{
    "data": {
        "folders": [
            {
                "id": "folder.a6b2a7e8f2515e5e.A6B2A7E8F2515E5E!110",
                ... If this folder was selected, additional info about this folder ...
            },
            {
                "id": "folder.a6b2a7e8f2515e5e.A6B2A7E8F2515E5E!145",
                ... If this folder was selected, additional info about this folder ...
            },
            ... Info about additional folders that were selected, if any ...
        ],
        "files": [
            {
                "id": "file.a6b2a7e8f2515e5e.A6B2A7E8F2515E5E!131",
                ... If this file was selected, additional info about this file ...
            },
            {
                "id": "file.a6b2a7e8f2515e5e.A6B2A7E8F2515E5E!144",
                ... If this file was selected, additional info about this file ...
            },
            {
                "id": "file.a6b2a7e8f2515e5e.A6B2A7E8F2515E5E!152",
                ... If this file was selected, additional info about this file ...
            },
            ... Info about additional files that were selected, if any ...
        ]
    }
}

Note If no folders were selected, the folders array is still returned but is empty—for example, "folders": []. Likewise, if no files were selected, the files array is still returned but is empty—for example, "files": [].

Your app can then call the WL.download method to download the files one at a time, specifying response.data.files[i].id for the WL.download method's path parameter. In the example just given, response is the name of the parameter that's specified in the WL.ui or WL.fileDialog method's onSuccess parameter, and i is the name of the variable that's used to iterate through the lists of files. For code examples, see the previous sections.

To download files that are inside a folder, you first need to get the folder ID by specifying response.data.folders[i].id for the WL.api method's path parameter. In this example also, response is the name of the parameter that's specified in the WL.ui or WL.fileDialog method's onSuccess parameter, and i is the name of the variable that's used to iterate through the list of folders. Your app can then use the response to iterate through the list of files in the folder and call the WL.download method on each file. For code examples, see the previous sections.

Tip Of course, you could also specify response.data[j].folders[i].id, where j is the name of the variable that's used to iterate through either the folders array (data[0]) or the files array (data[1]).

Related info

For more info, see:

  • The Live Interactive SDK, where you can experiment with the SkyDrive file picker without writing any code
  • Folders and files, "Downloading files" and "Uploading files" sections
  • WL.download
  • WL.fileDialog
  • WL.ui
  • WL.upload

Top


SkyDrive core concepts

In this article

  • File concepts in SkyDrive
  • Object permissions in SkyDrive

This topic describes the concepts and guidelines that apply whenever you access a user's Microsoft SkyDrive contents from your app.

File concepts in SkyDrive

To upload a file to SkyDrive, your code can use HTTP operations such as POST or PUT. You can also use MOVE and COPY to avoid downloading, and then uploading files that you want to move or copy.

When your code uploads a file, and a file with the same name already exists in the same location in SkyDrive, the default behavior is for SkyDrive to overwrite the existing file. You can add an Overwrite header with a value of false to prevent the existing file from being overwritten. Or you can add an overwrite query-string parameter with a value of ChooseNewName if you want to upload a duplicate copy of the file but let SkyDrive choose the uploaded file's new file name.

Top

Object permissions in SkyDrive

Users can control who can access certain objects in their SkyDrive storage location. This includes objects like folders, files, albums, photos, videos, and audio.

Object permissions in SkyDrive are inherited from their parent objects all the way up to a user's top-level folder in the SkyDrive directory.

When your code creates or updates an object in SkyDrive, your code can't set or change the object's permissions programmatically. Its permissions are inherited automatically. However, an app can allow sharing with a link to grant users read or read/write access to a file or folder. Of course, the user can change an object's permissions through the SkyDrive UI.

Your code can't change an object's permissions in a way that would restrict permissions all the way up to a user's top-level folder in the SkyDrive directory. For example, if a certain folder allows anyone to access its contents, you can't change the permissions on any of the folder's contained objects to restrict who can access them.

Your code can get a link to a folder or a file, and then you can share that link with other users so that they can access the folder or file directly. We provide several link types, including embedded, read-only, and read-write links, for publicly shared folders and files. These links will work only for users who have permission to view the file.

We also provide preauthenticated links to files; these links work regardless of file permissions. These links should be created only when the user wants to share a folder or file with specific people, because file permissions are not evaluated for these links, and anyone who clicks on the links can view the content. For more info, see the "Getting links to folders and files" section in the Folders and files topic.

Top


Messenger API

Try out code samples Download XMPP code samples

You can use Extensible Messaging and Presence Protocol (XMPP), an open standard for real-time communication, to enable your apps to interact with a Windows Live Messenger user and his or her buddies.

  • Getting started using Messenger with XMPP

    Get a user's okay for your app to act on his or her behalf, and then sign in to the Messenger XMPP service.

  • XMPP code examples

    Exchange instant messages and get a user's info and his or her buddies' info, including their friendly names, display tiles, presence info, and status messages. Also, update a user's status message for the duration of a session.

  • Messenger XMPP reference

    Find a list of supported extensions, as defined by the XMPP Standards Foundation.

  • Sharing a user's status

    Update a user's status message between sessions by using the Live Connect APIs.

  • Sharing badge

    Enable users who have a Microsoft account to share info with their friends about content on your website.


Getting started using Messenger with XMPP

Before your client app can start using Extensible Messaging and Presence Protocol (XMPP) to sign in to the Windows Live Messenger XMPP service and interact with a Messenger user and his or her buddies, there are several things you must do.

  • Prerequisites
  • Prepare to sign in
  • Get a client ID
  • Get an access token
  • Sign in
  • Next steps

Prerequisites

Before you prepare to sign in your app to the Messenger XMPP service, you need to know this:

  • Live Connect doesn't provide any XMPP libraries. If you don't have a preferred XMPP library to use, you may want to explore the list of available XMPP libraries at XMPP Standards Foundation - Libraries. You will have to write some code to get any of these libraries to work with the Messenger XMPP service. For details, continue reading this topic.
  • For the XMPP extensions and features that we support, see Messenger XMPP reference. Your app must support XMPP: Core functionality and, optionally, may implement the XMPP extensions we support.

Top

Prepare to sign in

Before your app can sign in to the Messenger XMPP service, you need this info:

  • To connect to the Messenger XMPP service, either use Domain Name System (DNS) SRV records for messenger.live.com or connect directly to xmpp.messenger.live.com on port 5222.
  • Secure Sockets Layer (SSL) is required.
  • Your app must implement see-other-host. For details, see the "see-other-host" section in RFC6120: XMPP: Core.

    Note The see-other-host requirement is a breaking change beginning with the April 2012 release. All apps, including those that work with the December 2011 release, must implement see-other-host. Any app that implements Messenger XMPP but doesn't also implement see-other-host will no longer work.

  • We use X-MESSENGER-OAUTH2 Simple Authentication and Security Layer (SASL) authentication to get a user's okay, or consent, for your app to represent the user when signing in to the Messenger XMPP service. To do this, we use the OAuth 2.0 standard. To use our implementation, your app needs a client ID and an access token (and possibly other info, depending on your app type). To get these, see the Get a client ID and Get an access token sections later in this topic.

Top

Get a client ID

Before your app can sign in to the Messenger XMPP service, you need a client ID. A client ID is a unique code that identifies your app to the Live Connect authentication service and is exchanged for an access token, which is explained in the next section. To get a client ID (and, depending on your app type, to get a client secret and specify a redirect domain), follow the instructions in Configuring your app.

Top

Get an access token

After you have a client ID (and other info, depending on your app type), your app needs to give this info to the Live Connect authentication service in exchange for an access token. This access token allows your app to sign in to the Messenger XMPP service for a specific user who has okayed, or consented, for your app to act on his or her behalf. (To get a client ID, see the Get a client ID section earlier in this topic.)

To get an access token, you need to use the client ID and specify a user consent level, which we call a scope. The specific scope that you need to use here is wl.messenger.

To use the wl.messenger scope and your client ID to get an access token, follow the guidance and code examples in Signing users in and Obtaining user consent. For additional guidance and more complete code samples, go to the following information and resources depending on your app type:

  • Windows Store apps: See the JavaScript and C# code in Windows Store apps and Working with the code examples. To get the access token, for JavaScript, you can call the WL.getSession method and look in the returned access_token property for the session object. For C#, in the custom event handler method that you specify for the LiveAuthClient.LoginCompleted event, look in the LoginCompletedEventArgs.Session.AccessToken property.
  • Windows Phone app: See the C# code in Windows Phone apps and Working with the code examples. To get the access token, look in the LoginCompletedEventArgs.Session.AccessToken property in the custom event handler method that you specify for the LiveAuthClient.LoginCompleted event.
  • iOS apps: See the Objective-C code in iOS apps and Working with the code examples. To get the access token, in the LiveAuthDelegate.authCompleted:session:userState method, call the session parameter's accessToken property.
  • Android apps: See the Java code in Android apps and Working with the code examples. To get the access token, in the LiveAuthListener.onAuthComplete method, call the session parameter's getAccessToken method.
  • Client-side website or script that uses JavaScript: See the code in Web apps. To get the access token, you can call the WL.getSession method and look in the returned access_token property for the session object.
  • All other app types: See the Representational State Transfer (REST) code in the "Signing a user in with REST" section in Signing users in to learn how to get the access token.

Top

Sign in

After you have an access token, your app can sign in to the Messenger XMPP service on behalf of the consenting user. (To get an access token, see the Get an access token section earlier in this topic.)

As stated in the previous section, the Messenger XMPP service uses X-MESSENGER-OAUTH2 SASL authentication. Your app sends the access token as the SASL token for authentication, as shown in the following partial exchange of protocol info, where ACCESS_TOKEN represents your access token.

...
< <stream:features xmlns:stream="http://etherx.jabber.org/streams"><mechanisms xmlns="urn:ietf:params:xml:ns:xmpp-sasl"><mechanism>X-MESSENGER-OAUTH2 </mechanism></mechanisms></stream:features>
> <auth xmlns="urn:ietf:params:xml:ns:xmpp-sasl" mechanism="X-MESSENGER-OAUTH2">ACCESS_TOKEN</auth>
< <success xmlns="urn:ietf:params:xml:ns:xmpp-sasl" />
...

Remember that your code must first connect to the Messenger XMPP service by using DNS SRV records for messenger.live.com or by connecting directly to xmpp.messenger.live.com on port 5222.

Note The Messenger XMPP service uses the user ID in the access token to sign the user in and to bind the user to the session. To do this, Jabber IDs that are assigned by the Messenger XMPP service use the format identifier@messenger.live.com instead of a Microsoft account user ID.

Top

Next steps

Now that you've learned the basics, you can use our XMPP code examples.

Top


XMPP code examples

We provide these code samples to demonstrate how to work with the Windows Live Messenger Extensible Messaging and Presence Protocol (XMPP) service from a client app for the Google Android mobile technology platform, and from a Java console-based client app.

  • Android XMPP client code sample
  • Java console-based XMPP client code sample

Android XMPP client code sample

Download the Android XMPP client code sample.

We built our Android XMPP client code sample on the Android 2.3.3 platform with the asmack open-source XMPP library, version 2010.05.07.

Download the asmack library, version 2010.05.07.

This code sample uses our implementation of the OAuth implicit grant flow for getting an access token. You need an access token to sign in to the Messenger XMPP service. To get an access token, see the "Get an access token" section in Getting started using Messenger with XMPP. For details about our OAuth implicit grant flow, see OAuth 2.0.

This code sample highlights these features.

  • WLMActivity.java—This is the app's main class. This class gets the access token and maintains the UI. We hard-coded the sample client ID and redirect domain that we use to get the access token. You must change these two constants in the code to use your own client ID and redirect domain.

    public static final String OAuthAppClientId = "YOUR_CLIENT_ID";
public static final String OAuthAppRedirectUri = "YOUR_REDIRECT_DOMAIN";
  • XmppClient.java—This is our XMPP client implementation that uses the asmack library. This class has all the logic for XMPP-specific operations like signing in to the Messenger XMPP service using an access token and handling XMPP stanzas.
  • XMessengerOAuth2.java—This class uses the asmack library to handle X-MESSENGER-OAUTH2 authentication.

Top

Java console-based XMPP client code sample

Download the Java console-based XMPP client code sample.

We built our Java console-based XMPP client code sample with JRE version 1.6 and the Smack open-source XMPP library, version 3.2.1.

Download the Smack library, version 3.2.1.

You must change the code to add your access token to sign in to the Messenger XMPP service. To get an access token, see the "Get an access token" section in Getting started using Messenger with XMPP.

This code sample highlights these features.

  • Program.java—This is the app's main entry point. You must change the TestAccessToken constant for this class to use your access token, like this.
    public static final String TestAccessToken = "YOUR_ACCESS_TOKEN"
  • XmppClient.java—This is the XMPP client implementation that uses the Smack library. The class has all the logic for XMPP-specific operations like signing in to the Messenger XMPP service using an access token and handling XMPP stanzas.
  • XMessengerOAuth2.java—This class uses the Smack library to handle X-MESSENGER-OAUTH2 authentication.

Top


Messenger XMPP reference

The Windows Live Messenger Extensible Messaging and Presence Protocol (XMPP) service supports only the following extensions, as defined by the XMPP Standards Foundation. Partial support for some extensions, as well as unique usage notes, are listed here. For more info, see XMPP Standards Foundation - XMPP Extensions.

  • RFC6120: XMPP: Core
  • RFC6121: XMPP: Instant Messaging and Presence. Adding a contact is the only supported modifying operation; no other operations that modify the roster are supported. Chat is the only supported message stanza type. Presence probes are not supported.

    Note Applications should cache most recent presence for buddies and should avoid signing out and signing in again as a way to refresh presence.

  • XEP-0054: vcard-temp. The Messenger XMPP service supports fetching vCards, but doesn't support updating vCards.
  • XEP-0136: Message Archiving. Apps that implement this extension can request a certain number of instant messages that were previously exchanged between two users. Apps can currently request up to the last 10 instant messages, but this number is subject to change. Availability of these archived instant messages depends on whether at least one of the two users has the Automatically keep a history of my conversations setting turned on in Messenger. If no archived instant messages are available, the Messenger service returns an empty response.

    Note In requests for archived instant messages, the Messenger service ignores user endpoint requests, paging requests, and any uses of the after element.

  • XEP-0172: User Nickname. Apps can implement this extension to provide an improved user experience when showing pending contact invitations to the user. By default, contact invitations in XMPP are incoming subscriptions from users who aren't in the roster; these invitations provide only the pending contact's Jabber ID (JID), which doesn't show a display name. By implementing this extension, apps can retrieve the pending contact's display name so that Messenger users have a better idea of who the corresponding pending invitation is from. Note that it isn't necessary to support this extension for existing contacts, because their display names are available through their vCards. This extension is useful for pending contacts, because vCards are not available until after both parties have become contacts.
  • XEP-0203: Delayed Delivery

Additional usage notes

  • Adding Messenger buddies: To add a new Messenger buddy to the XMPP user's contact list, your app must add the buddy by using his or her Jabber ID (JID) and not by his or her Microsoft account ID. If your app does not add a buddy by using his or her JID, your app won't be able to display the buddy's presence info.

    Here's an example of submitting a Microsoft account ID to the Messenger XMPP service and retrieving the corresponding JID.

    < <iq from='john@contoso.com' to='mary@contoso.com' type='get' id='id1'>
    <getjid xmlns='http://messenger.live.com/xmpp/jidlookup'></getjid>
</iq>

> <iq from='john@contoso.com' to='mary@contoso.com' type='result' id='id1'>
    <getjid xmlns='http://messenger.live.com/xmpp/jidlookup'>
        <jid>12345@messenger.live.com</jid>
    </getjid>
</iq>

    To find examples of how you can do this in your apps, see XMPP code examples.


Sharing a user's status

You can use code to update the status of a Live services user. When you update a user's status, it shows up in the user's status message.

To make full use of the code examples in this topic, you can use them in the context of larger code reference samples that we provide in Working with the code examples.

  • Update a user's status message in JavaScript for Windows Store apps and HTML
  • Update a user's status message in C# for Windows Store apps and Windows Phone apps
  • Update a user's status message by using Objective-C for iOS
  • Update a user's status message by using Java for Android
  • Update a user's status message using REST

Update a user's status message in JavaScript for Windows Store apps and HTML

To share text, use code similar to this.

JavaScript
function shareUserStatus_onClick() {
    WL.login({
        scope: "wl.share"
    }).then(
        function (response) {
            WL.api({
                path: "me/share",
                method: "POST",
                body: {
                    message: "Hello, Windows Live!"
                }
            }).then(
                function (response) {
                    document.getElementById("infoArea").innerText =
                        "Status: " + response.message;
                },
                function (responseFailed) {
                    document.getElementById("infoArea").innerText =
                        "Error calling API: " + responseFailed.error.message;
                }
            );
        },
        function (responseFailed) {
            document.getElementById("infoArea").innerText =
                "Error signing in: " + responseFailed.error_description;
        }
    );
}

The result looks like this.

Note The following screen shot shows an English example of the UI. The actual UI that you see may differ depending on your locale.

Shared activity with text only

To share text with a link, with all possible keys specified, use code like the following.

JavaScript
body: {
    message: "Explore Windows Live",
    link: "http://explore.live.com/home",
    description: "Stay in touch and share your world: email, photos, movies, video chat, and more!",
    picture: "http://res2.explore.live.com/resbox/en/Live%20Explore/Main/a/1/a1ce31bd-6291-42fb-9b51-b4cf2013481c/a1ce31bd-6291-42fb-9b51-b4cf2013481c.jpg",
    name: "Windows Live Home"
}

Note In the preceding code, only the message and link key-value pairs are required.

The result looks like this.

Note The following screen shot shows an English example of the UI. The actual UI that you see may differ depending on your locale.

Shared activity with text and link

To share video, with all possible keys specified, use code like the following.

JavaScript
body: {
    message: "Double Rainbow - Windows Live Photo Gallery",
    link: "http://www.youtube.com/watch?v=8jXz7NrfzsI",
    description: "Watch \"Double Rainbow Guy\" edit his pictures by using Windows Live Photo Gallery. (0:43)",
    picture: "http://res2.explore.live.com/resbox/en/Live%20Explore/Main/2/f/2f70d4d7-1640-4414-9298-9957ab5e01c3/2f70d4d7-1640-4414-9298-9957ab5e01c3.png",
    name: "Wow -- It's a Double Rainbow!",
    source: "http://www.youtube.com/v/8jXz7NrfzsI?version=3"
}

The result looks like this.

Note The following screen shot shows an English example of the UI. The actual UI that you see may differ depending on your locale.

Shared video activity

Note In the preceding code, only the message, link, and source key-value pairs are required.

Important Sharing a status message type without specifying at least its required structures will return an error.

Top

Update a user's status message in C# for Windows Store apps and Windows Phone apps

To share status, use code similar to this. For brevity, only a limited number of sharing scenarios are shown here.

[C# for Windows Store apps]

C#
private async void btnShareStatus_Click(object sender, RoutedEventArgs e)
{
    try
    {
        var message = new Dictionary<string, object>();
        message.Add("message", "Hello, Windows Live!");
        LiveConnectClient liveClient = new LiveConnectClient(this.session);
        LiveOperationResult operationResult = await liveClient.PostAsync("me/share", message);
        dynamic result = operationResult.Result;
        this.infoTextBlock.Text = string.Join(" ", "Status", result.message, "shared with your friends.");
    }
    catch (LiveConnectException exception)
    {
        this.infoTextBlock.Text = "Error sharing status: " + exception.Message;
    }
}

Top

Update a user's status message by using Objective-C for iOS

To share status, use code similar to this. For brevity, only sharing a message is shown here.

ObjectiveC
- (void) shareStatus
{
    NSDictionary *postBody = [NSDictionary dictionaryWithObjectsAndKeys:
                              messageInputTextField.text, @"message",
                              nil];
    [self.liveClient postWithPath:@"me/share"
                         dictBody:postBody
                         delegate:self
                        userState:@"share status"];
}

- (void) liveOperationSucceeded:(LiveOperation *)operation
{
    if ([operation.userState isEqual:@"share status"]) {
        self.statusLabel.text = @"The message was posted successfully.";
    }
}

- (void) liveOperationFailed:(NSError *)error
                   operation:(LiveOperation *)operation
{
    if ([operation.userState isEqual:@"share status"]) {
        self.statusLabel.text = @"The message posting request failed.";
    }
}

Update a user's status message by using Java for Android

To share status, use code similar to this. For brevity, only sharing video is shown here.

Java
public void shareUserStatus() {
    JSONObject status = new JSONObject();
    try {
        status.put("message", "Double Rainbow - Windows Live Photo Gallery");
        status.put("link", "http://www.youtube.com/watch?v=8jXz7NrfzsI");
        status.put("description", "Watch \"Double Rainbow Guy\" edit his pictures by using Windows Live Photo Gallery. (0:43)");
        status.put("picture", "http://res2.explore.live.com/resbox/en/Live%20Explore/Main/2/f/2f70d4d7-1640-4414-9298-9957ab5e01c3/2f70d4d7-1640-4414-9298-9957ab5e01c3.png");
        status.put("name", "Wow -- It's a Double Rainbow!");
        status.put("source", "http://www.youtube.com/v/8jXz7NrfzsI?version=3");
    } catch (JSONException e) {
        resultTextView.setText("Error building status message: " + e.getMessage());
        return;
    }
    client.postAsync("me/share", status, new LiveOperationListener() {
        public void onComplete(LiveOperation operation) {
            JSONObject result = operation.getResult();
            resultTextView.setText("Status shared. Message = " + result.optString("message"));
        }
        public void onError(LiveOperationException exception, LiveOperation operation) {
            resultTextView.setText("Error sharing status: " + exception.getMessage());
        }
    });
}

Update a user's status message using REST

If a Live Connect user signs in and consents to a wl.share scope request, and you have an access token that corresponds to this consented request, you can share an activity by making a call with Representational State Transfer (REST) and these parameters.

POST https://apis.live.net/v5.0/me/share

Authorization: Bearer ACCESS_TOKEN
Content-Type: application/json

{
    "message": "Explore Windows Live",
    "link": "http://explore.live.com/home",
    "description": "Stay in touch and share your world: email, photos, movies, video chat, and more!",
    "picture": "http://explore.live.com/a1ce...part of URL omitted for brevity...481c.jpg",
    "name": "Windows Live Home"
}

In the preceding code example, replace ACCESS_TOKEN with your access token string. Also, replace the JavaScript Object Notation (JSON)-formatted data with key-value pairs appropriate to sharing text or to sharing text with a link, as shown in the preceding section's code examples.

For more information about how to make server-side HTTP calls with REST, see Server-side scenarios.

Top


Sharing badge

You can enable users who have a Microsoft account to share info with their friends about content on your website. To make this possible, you add specific HTML code to your website next to the content that you want users to be able to share. This code displays a Live Connect sharing badge. A sharing badge consists of a clickable image file and a summary of the content.

When a user clicks a sharing badge, Live Connect prompts the user to sign in, if the user is not already signed in. Live Connect enables the signed-in user to annotate the content to be shared, and then update his or her status message. The user's friends can then click on any of the links in the shared content in the user's activities list and any links that are visible in the user's status message.

To add a sharing badge to your website, add the following HTML code next to the content that you want users to be able to share.

<a
    href="http://profile.live.com/badge?url=URL"
>
    <img
        style="border-style:none; vertical-align:middle; margin-right:4px"
        src="SHARING_BADGE_IMAGE_URL"
        alt="Sharing badge"
    />
</a>

In the preceding HTML code example, replace URL with the URL of the content to be shared, for example, http://www.contoso.com/LatestNews.htm. Note that any special characters in the URL, such as the colon (":") and the slash ("/"), must be escaped or otherwise encoded, for example, http%3A%2F%2Fwww.contoso.com%2FLatestNews.htm.

Note For URLs to articles and videos, you can provide optional parameters.

In the preceding code, replace SHARING_BADGE_IMAGE_URL with the URL of one of the available sharing badge images in the following list, depending on your preferences for image size and background color.

  • http://js.live.net/static/img/SharingBadge16x16White.png
  • http://js.live.net/static/img/SharingBadge22x22White.png
  • http://js.live.net/static/img/SharingBadge16x16Orange.png
  • http://js.live.net/static/img/SharingBadge22x22Orange.png


Live API Reference

This reference provides information about how to call the Live Connect APIs: the JavaScript API (Windows 8 and web), the Managed API (Windows 8 and Windows Phone), the iOS API, and the Android API.

This API reference contains these topic sets.

  • JavaScript API (Windows 8 and web)
  • Managed API (Windows 8 and Windows Phone)
  • iOS API
  • Android API


JavaScript API (Windows 8 and web)

The Live Connect JavaScript API (Windows 8 and web), together with the REST API, enables apps to read, update, and share user data by using the JavaScript programming language. The JavaScript API (Windows 8 and web) provides methods for signing users in and out, getting user status, subscribing to events, creating UI controls, and calling the Representational State Transfer (REST) API.

The WL object is a global object that encapsulates all functions of the JavaScript API (Windows 8 and web). Your app uses the WL object to call all of the JavaScript API (Windows 8 and web) functions.

Note All of the following functions apply to both Windows 8 and web apps unless otherwise noted.

This section contains the following topics.

Topic | Description
Using the JavaScript Library | Shows how to include the Live Connect JavaScript API (Windows 8 and web) in your app.
WL.api | Enables you to make calls to the Live Connect REST API.
WL.backgroundDownload (Windows 8) | Makes a call to download a file from Microsoft SkyDrive.
WL.backgroundUpload (Windows 8) | Makes a call to upload a file to SkyDrive.
WL.canLogout | Specifies whether the current user can be signed out of his or her Microsoft account.
WL.download (web) | Makes a call to download a file from SkyDrive.
WL.Event.subscribe | Subscribes to an event.
WL.Event.unsubscribe | Unsubscribes from an event.
WL.fileDialog (web) | Displays the SkyDrive file picker, which enables JavaScript-based web apps to display a pre-built, consistent user interface that enables a user to select files to upload and download to and from his or her SkyDrive storage location.
WL.getLoginStatus | Gets the user's status as he or she is signing in.
WL.getSession | Gets the session object for the user.
WL.init | Initializes the JavaScript API.
WL.login | Signs a user in or requests additional permissions.
WL.logout | Signs a user out.
WL.ui | Enables you to display UI elements, such as the Live Connect sign-in button and the SkyDrive file picker, in your app.
WL.upload (web) | Makes a call to upload a file to SkyDrive.
JSONP Scenarios | Shows how to use JavaScript Objection Notation with padding (JSONP) in client-side JavaScript webpage code to interact directly with the Live Connect REST API.


Using the JavaScript library

This topic covers the basic tasks involved in using the Live Connect JavaScript library in web apps and Windows Store apps built for Windows using JavaScript.

  • Referencing the JavaScript library in a web app
  • Referencing the JavaScript library in a Windows Store app using JavaScript
  • Enabling Microsoft IntelliSense
  • Loading the debug version
  • International support
  • Live Connect authentication cookies

Referencing the JavaScript library in a web app

To use the Live Connect JavaScript APIs with a web-based app, you must load the JavaScript library (wl.js) by adding a reference in your code to the location of the latest version of the library file. The default locale of wl.js is English. The following is an example of how to reference the JavaScript library in a standard web-based app.

HTML
<script src="//js.live.net/v5.0/wl.js"></script>

Top

Referencing the JavaScript library in a Windows Store app using JavaScript

To reference the Live Connect JavaScript APIs from a Microsoft Visual Studio 11 Express for Windows 8 project, do this:

  1. Install the Live Software Development Kit (SDK), if you have not already done so.
  2. In your project, in Solution Explorer, right-click References > Add Reference.
  3. Click Windows > Extension SDKs > Live SDK for Windows Store app.
  4. Click Add, and then click Close.

Top

Enabling Microsoft IntelliSense

To enable Microsoft IntelliSense in an HTML file, do this:

  1. Add this <script> element in the <head> element.
    HTML
    <script src="///LiveSDKHTML/js/wl.js"></script>
  2. Create a new file named default.js.
  3. Add this comment to the top of the default.js file.
    JavaScript
    /// <reference path="///LiveSDKHTML/js/wl.js" />

    Note

    In Visual Studio, you can drag wl.js from the solution explorer and drop it onto default.js to add this reference.

Top

Loading the debug version

If you need to debug the JavaScript API, you can reference an uncompressed version of the library file, named wl.debug.js. Use the following code to reference the debugging version in a web app.

HTML
<script src="//js.live.net/v5.0/wl.debug.js"></script>

If you are creating a Windows Store app using JavaScript, the solution configuration that is selected in Visual Studio, for example, debug or release, determines which version of wl.js will be loaded.

Top

International support

For Windows Store apps using JavaScript, the locale for the current app session defaults to use the settings of the user's local computer. However, the developer may override the locale setting programmatically, as shown in the following example.

JavaScript
...
var ns = Windows.ApplicationModel.Resources.Core;
var rm = ns.ResourceManager;
var context = rm.current.defaultContext;
context.language = "fr";
...

Note Setting the locale must be done before calling WL.init.

To set the locale for a web app, you must load a localized version of the JavaScript library by adding to the URL a segment that specifies the culture name string for the localized version that you want. Insert this segment immediately after the version number segment. For example, to load the Japanese version of the JavaScript library, you might use the following code.

HTML
<script src="//js.live.net/v5.0/ja/wl.js"></script>

For a complete list of localized versions, see Supported locales.

Top

Live Connect authentication cookies

The JavaScript library uses a session cookie, wl_auth, to track and transmit OAuth authentication data as the user signs in to Live Connect. For more info about OAuth authentication, see OAuth 2.0.

When the JavaScript library is loaded as part of the OAuth redirect Uniform Resource Identifier (URI), it sets this cookie automatically. When it is loaded as part of a typical page, the library polls the cookie to determine when the sign-in state of the user changes.

The following table lists the data that is stored in subkeys in the wl_auth cookie.

Subkey | Data
access_token | The OAuth access token.
authentication_token | The authentication token.
error | The OAuth error, if one occurred.
error_description | The description of the OAuth error, if one occurred.
expires_in | The time remaining, in seconds, until the OAuth access token expires, if the token was provided.
scope | The OAuth scope value, if it was provided.

Note The wl_auth cookie is stored in the domain as the domain of your redirect URL.

Important Cookies are applicable only to web apps. Developers of Windows Store apps using JavaScript will have no need to interact with cookies.

In general, you do not have to handle the wl_auth cookie directly; the JavaScript library handles it for you. However, if your callback page processes the user’s authentication token through server-side code, such as with the wl.offline_access scope, your code is responsible for updating the cookie according to the following rules:

  • If the app successfully retrieves the authentication token, it must write the access_token, scope, and expires_in subkeys in the cookie that was received.

  • If an error is received from the authentication server, the app must write two subkeys: error and error_description. The value of the error subkey must be "access_denied". The value of the error_description subkey must be "Failed to retrieve user access token".

  • The callback page must load wl.js.

In all cases, your app must not overwrite any existing subkeys.

Top


WL.api function

Makes a call to the Live Connect Representational State Transfer (REST) API. This method encapsulates a REST API request, and then calls a callback function to process the response.

Parameters

properties

Required. A JSON object that contains the following properties, which are necessary to make the REST API call.

Name Type Description Default Value

path

string

Required. Contains the path to the REST API object. For information on specifying paths for REST objects, see REST reference.

None

method

string

Optional. An HTTP method that specifies the action required for the API call. These actions are standard REST API actions: "COPY", "GET", "MOVE", "PUT", "POST", and "DELETE".

"GET"

body

object

Optional. A JSON object that specifies the REST API request body. The body property is used only for "POST" and "PUT" requests.

None

callback

Specifies a callback function that is executed when the REST API call is complete. The callback function takes the API response object as a parameter. The response object exposes the data returned from Live Connect, or, if an error occurs, an error property that contains the error code.

Note Although the callback parameter is still supported, we recommend that you use the Promise object instead, which is described later in this topic.

Return value

Returns a Promise object. This object's then method provides the onSuccess, onError, and onProgress parameters to enable your code to handle a successful, failed, and in-progress call to the corresponding WL.api method, respectively.

Remarks

Important For Windows Store apps using JavaScript, before calling the WL.api function, your code must call either the WL.init or WL.login function with, at minimum, the required scopes for creating, reading, updating, or deleting the corresponding data. If you don't do this, the call to the WL.api function may fail. Also, this requirement applies to each webpage's current session. Therefore, if your app contains multiple webpages, each webpage must follow this requirement.

Examples

JavaScript
function createFolder_onClick() {
    WL.login({
        scope: "wl.skydrive_update"
    }).then(
        function (response) {
            WL.api({
                path: "me/skydrive",
                method: "POST",
                body: {
                    "name": "This is a new folder",
                    "description": "A new folder"
                }
            }).then(
                function(response) {
                    document.getElementById("infoArea").innerText =
                        "Created folder. Name: " + response.name + ", ID: " + response.id;
                },
                function (responseFailed) {
                    document.getElementById("infoArea").innerText =
                        "Error calling API: " + responseFailed.error.message;
                }
            );
        },
        function (responseFailed) {
            document.getElementById("infoArea").innerText =
                "Error signing in: " + responseFailed.error_description;
        }
    );
}

Requirements

Header
Not applicable

Library
Wl.js

DLL
Not applicable


WL.backgroundDownload function

Makes a call to download a file from Microsoft SkyDrive.

Important WL.backgroundDownload is supported only for use with Windows Store apps using JavaScript. If you are writing a web app, use WL.download instead.

Parameters

properties

Required. A JSON object that contains the following properties, which are necessary to make the REST API call:

Name Type Description Default Value

path

string

Required. The path to the file to download. For information on specifying paths for REST objects, see REST reference.

None

file_output

Windows.Storage.StorageFile

Optional. The file output object to which the downloaded file data is written.

None

callback

Optional. Specifies a callback function that is executed when the REST API call is complete. The callback function takes the API response object as a parameter. The response object exposes the data that is returned from Live Connect, or, if an error occurs, an error property that contains the error code.

Note Although the callback parameter is still supported, we recommend that you use the Promise object instead, which is described later in this topic.

Return value

Returns a Promise object. This object's then method accepts callback functions for onSuccess, onError, and onProgress to enable your code to handle a successful, failed, and in-progress call to the corresponding WL.download method, respectively.

The onSuccess callback is passed a response object that contains content_type and stream properties, representing the downloaded file's content type and file stream, respectively.

Remarks

Important Before calling the WL.backgroundDownload function, your code must call either the WL.init or WL.login function with, at minimum, the required scopes for downloading the corresponding files. If you don't do this, the call to the WL.backgroundDownload function may fail. Also, this requirement applies to each webpage's current session. Therefore, if your app contains multiple webpages, each webpage must follow this requirement.

Examples

JavaScript
function downloadFile_onClick() {
    var picker = setupSavePicker();
    picker.pickSaveFileAsync().then(
        function (file) {
            if (file && (file instanceof Windows.Storage.StorageFile)) {
                WL.login({
                    scope: "wl.skydrive"
                }).then(
                    function (response) {
                        WL.backgroundDownload({
                            path: "file.8c8ce076ca27823f.8C8CE076CA27823F!129/picture?type=thumbnail",
                            file_output: file
                        }).then(
                            function (response) {
                                document.getElementById("infoLabel").innerText = "Downloaded file.";
                            },
                            function (responseFailed) {
                                document.getElementById("infoLabel").innerText =
                                "Error calling API: " + responseFailed.error.message;
                            }
                        );
                    },
                    function (responseFailed) {
                        document.getElementById("infoLabel").innerText =
                            "Error signing in: " + responseFailed.error.message;
                    }
                );
            }
            else {
                document.getElementById("infoLabel").innerText = "Cannot download file.";
            }
        },
        function (fileFailed) {
            document.getElementById("infoLabel").innerText = "Cannot download file.";
        }
    );
}

function setupSavePicker() {
    var savepicker = new Windows.Storage.Pickers.FileSavePicker();
    savepicker.suggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.documentsLibrary;
    savepicker.fileTypeChoices.insert("Picture", [".jpg"]);
    return savepicker;
}

Requirements

Header
Not applicable

Library
Wl.js

DLL
Not applicable


WL.backgroundUpload function

Makes a call to upload a file to Microsoft SkyDrive.

Important WL.backgroundUpload is supported only for use with Windows Store apps using JavaScript. If you are writing a web app, use WL.upload instead.

Parameters

properties

Required. A JSON object that contains the following properties, which are necessary to make the REST API call.

Name Type Description Default Value

path

string

Required. The path to the file to upload.

None

file_name

string

Optional. The name of the file to upload.

None

file_input

Windows.Storage.StorageFile or File

Optional. The file input object to read the file from.

None

stream_input

Windows.Storage.Streams.IInputStream

Optional. The file input stream to read the file from.

None

overwrite

boolean or string

Optional. Indicates whether the uploaded file should overwrite an existing copy. Specify true or "true" to overwrite, false or "false" to not overwrite and for the WL.backgroundUpload method call to fail, or "rename" to not overwrite and enable SkyDrive to assign a new name to the uploaded file.

"false"

callback

Optional. Specifies a callback function that is executed when the REST API call is complete. The callback function takes the API response object as a parameter. The response object exposes the data returned from Live Connect, or if an error occurs, an error property that contains the error code.

Note Although the callback parameter is still supported, we recommend that you use the Promise object instead, which is described later in this topic.

Return value

Returns a Promise object. For Windows Store apps using JavaScript, this object's then method accepts callback functions for onSuccess, onError, and onProgress to enable your code to handle a successful, failed, and in-progress call to the corresponding WL.backgroudUpload method, respectively.

Remarks

Important Before calling the WL.backgroundUpload function, your code must call either the WL.init or WL.login function with, at minimum, the required scopes for uploading the corresponding file. If you don't do this, the call to the WL.backgroundUpload function may fail. Also, this requirement applies to each webpage's current session. Therefore, if your app contains multiple webpages, each webpage must follow this requirement.

Examples

JavaScript
function uploadFile_onClick() {
    var picker = setupOpenPicker();
    var filePickOp = picker.pickSingleFileAsync().then(
        function (file) {
            WL.login({
                scope: "wl.skydrive_update"
            }).then(
                function (response) {
                    WL.backgroundUpload({
                        path: "me/skydrive",
                        file_name: file.fileName,
                        file_input: file,
                        overwrite: "rename"
                    }).then(
                       function (response) {
                           document.getElementById("infoLabel").innerText = "Uploaded file.";
                       },
                       function (responseFailed) {
                           document.getElementById("infoLabel").innerText =
                               "Error calling API: " + responseFailed.error.message;
                       }
                    );
                },
                function (responseFailed) {
                    document.getElementById("infoLabel").innerText =
                        "Error signing in: " + responseFailed.error.message;
                }
            );
        },
        function (fileFailed) {
            document.getElementById("infoLabel").innerText = "Cannot upload file.";
        }
    );
}

function setupOpenPicker() {
    var openpicker = new Windows.Storage.Pickers.FileOpenPicker();
    openpicker.fileTypeFilter.replaceAll(["*"]);
    return openpicker;
}

Requirements

Header
Not applicable

Library
Wl.js

DLL
Not applicable


WL.canLogout function

Specifies whether the current user can be signed out of his or her Microsoft account.

Parameters

This function has no parameters.

Return value

Returns true if the user can be signed out; otherwise, returns false if the user can't be signed out.

Remarks

For Windows Store apps using JavaScript, you can use this function to determine whether you should display a control to the user to enable him or her to sign out of his or her Microsoft account. If this function returns true, you should display the control. However, if this function returns false, you should not display this control, as attempting to sign out the user in this case will have no effect.

For web apps, this function always returns true.

Requirements

Header
Not applicable

Library
Wl.js

DLL
Not applicable


WL.download function

Makes a call to download a file from Microsoft SkyDrive.

Important WL.download is supported only for use with web apps. Windows Store apps using JavaScript. If you are writing a Windows Store app using JavaScript, use WL.backgroundDownload instead.

Parameters

properties

Required. A JSON object that contains the following properties, which are necessary to make the REST API call:

Name Type Description Default Value

path

string

Required. The path to the file to download. For information on specifying paths for REST objects, see REST reference.

None

callback

Specifies a callback function that is executed when the REST API call is complete. The callback function takes the API response object as a parameter. The response object exposes the data that is returned from Live Connect, or, if an error occurs, an error property that contains the error code.

Note Although the callback parameter is still supported, we recommend that you use the Promise object instead, which is described later in this topic.

Return value

Returns a Promise object. This object's then method provides the onError parameter to enable your code to handle a failed call to the corresponding WL.download method.

Examples

HTML
<button onclick="downloadFile()">Open file directly (calling WL.download)</button>
HTML
function downloadFile() {
    WL.login({
        scope: "wl.skydrive"
    }).then(
        function (response) {
            WL.download({
                path: "file.a6b2a7e8f2515e5e.A6B2A7E8F2515E5E!131/content"
            }).then(
                function (response) {
                    // Will not be called for web apps.
                },
                function (responseFailed) {
                    document.getElementById("info").innerText =
                        "Error downloading file: " + responseFailed.error.message;
                }
            );
        },
        function (responseFailed) {
            document.getElementById("info").innerText =
                "Error signing in: " + responseFailed.error.message;
        }
    );
}

Requirements

Header
Not applicable

Library
Wl.js

DLL
Not applicable


WL.Event.subscribe function

Adds a handler to an event.

Parameters

event

Required. The name of the event to which to add a handler. The JavaScript API supports the following events.

Name Occurs when Event properties

auth.login

The user completes the sign-in process.

A string with the current status, for example, "connected".

The current session object instance.

auth.logout

The user completes the sign-out process.

None.

auth.sessionChange

The user's access token has changed.

None. Retrieve the current session by calling WL.getSession.

auth.statusChange

The user's status has changed.

None. Retrieve the user's status by calling WL.getLoginStatus.

wl.log

An error has occurred with an API call.

A string with the error message.

callback

Required. Specifies the name of the callback function to handle the event.

Return value

This function can return the following errors:

  • WL.Event.subscribe: The input parameter/property 'callback' must be included.
  • WL.Event.subscribe: The input value for parameter/property 'event' is not valid.

Remarks

Note

When handling the wl.log event, the logging attribute must be set to "true" in the call to WL.init; otherwise, log events will not be fired.

Examples

HTML
WL.Event.subscribe("auth.login", onLogin);

Requirements

Header
Not applicable

Library
Wl.js

DLL
Not applicable


WL.Event.unsubscribe function

Removes a handler from an event.

Parameters

event

Required. The name of the event from which to remove a handler. The JavaScript API supports the following events.

Name Occurs when

auth.login

The user completes the sign-in process.

auth.logout

The user completes the sign-out process.

auth.sessionChange

The user's access token has changed.

auth.statusChange

The user's status has changed.

wl.log

An error has occurred with an API call.

callback

Optional. Removes the callback function from the event. If this parameter is omitted or is null, all callback functions that are registered to the event are removed. Removes the callback function from the specified event.

Examples

HTML
WL.Event.unsubscribe("auth.logout");

Requirements

Header
Not applicable

Library
Wl.js

DLL
Not applicable


WL.fileDialog function

Displays the Microsoft SkyDrive file picker, which enables JavaScript-based web apps to display a pre-built, consistent user interface that enables a user to select files to upload and download to and from his or her SkyDrive storage location.

Parameters

properties

Required. A JSON object containing the following properties for displaying the button.

Name Type Description Default Value

mode

string

Required. Specifies the type of SkyDrive file picker to display. Specify "open" to display the download version of the file picker. Specify "save" to display the upload version of the file picker.

None.

select

string

Optional. Specify only if the mode property is set to "open". Specifies how many files the user can select to download. Specify "single" for a single file. Specify "multi" for multiple files.

"single"

lightbox

string

Optional. The color pallette to use for the file picker. Specify "white", "grey", or "transparent".

"white"

callback

Optional. A callback function that is executed after the user finishes interacting with the SkyDrive file picker.

Note Although the callback parameter is still supported, we recommend that you use the Promise object instead, which is described later in this topic.

Return value

Returns a Promise object. This object's then method provides the onSuccess and onError parameters to enable your code to handle a successful and failed call to the corresponding WL.fileDialog method, respectively.

Examples

The following example demonstrates how to use the upload version of the SkyDrive file picker.

HTML
<form>
    <input id="file" name="file" type="file" />
</form>
HTML
<button onclick="uploadFile_fileDialog()">Save file with SkyDrive file picker (calling WL.filedialog)</button>
HTML
function uploadFile_fileDialog() {
    WL.fileDialog({
        mode: "save"
    }).then(
        function (response) {
            WL.upload({
                path: response.data.folders[0].id,
                element: "file",
                overwrite: "rename"
            }).then(
                function (response) {
                    document.getElementById("info").innerText =
                        "File uploaded.";
                },
                function (responseFailed) {
                    document.getElementById("info").innerText =
                        "Error uploading file: " + responseFailed.error.message;
                }
            );
        },
        function (responseFailed) {
            document.getElementById("info").innerText =
                "Error getting folder info: " + responseFailed.error.message;
        }
    );
}

The following example demonstrates how to use the download version of the file picker.

HTML
<button onclick="downloadFile_fileDialog()">Open file with SkyDrive file picker (calling WL.filedialog)</button>
HTML
function downloadFile_fileDialog() {
    WL.fileDialog({
        mode: "open",
        select: "multi"
    }).then(
        function (response) {
            var msg = "";
            // For each folder selected...
            if (response.data.folders.length > 0) {
                for (folder = 0; folder < response.data.folders.length; folder++) {
                    // Use folder IDs to iterate through child folders and files as needed.
                    msg += "\n" + response.data.folders[folder].id;
                }
            }
            // For each file selected...
            if (response.data.files.length > 0) {
                for (file = 0; file < response.data.files.length; file++) {
                    // Use file IDs to iterate through files as needed.
                    msg += "\n" + response.data.files[file].id;
                }
            }
            document.getElementById("info").innerText =
                "Selected folders/files:" + msg;
        },
        function (responseFailed) {
            document.getElementById("info").innerText =
                "Error getting folder/file info: " + responseFailed.error.message;
        }
    );
}

Requirements

Header
Not applicable

Library
Wl.js

DLL
Not applicable


WL.getLoginStatus function

Returns the sign-in status of the current user. If the user is signed in and connected to your app, this function returns the session object. This is an asynchronous function that returns the user's status by contacting the Live Connect authentication web service.

Parameters

callback

Optional. Specifies the name of a callback function to execute when the user's sign-in status is retrieved. This function takes the status object as a parameter. For more info about the status object, see the "Return values" section that follows.

force

Optional. If set to "true", the function contacts the Live Connect authentication web service to determine the user's status. If set to "false" (the default), the function can return the user status that is currently in memory, if there is one. If the user's status has already been retrieved, the library can return the cached value. However, you can force the library to retrieve current status by setting the force parameter to "true".

Return value

Returns a Promise object. This object's then method provides the onSuccess and onError parameters to enable your code to handle a successful and failed call to the corresponding WL.getLoginStatus method, respectively.

In the body of the onSuccess function, a status object is returned, which contains the user's sign-in status and the session object. This object contains the following properties.

Property | Type | Description
status | string | The sign-in status of the user. Valid values are "connected", "notConnected", or "unknown".
session | object | A JSON object that contains the properties of the current session. For a detailed description of the session object's properties, see the "Return Values" section of WL.getSession.

Examples

HTML
function loginStatus() {
    WL.getLoginStatus(function(response) { alert("Your status is: " + response.status) });
}

Requirements

Header
Not applicable

Library
Wl.js

DLL
Not applicable


WL.getSession function

Retrieves the current session object synchronously, if a session object exists. For situations in which performance is critical, such as page loads, use the asynchronous WL.getLoginStatus method instead.

Parameters

This function has no parameters.

Return value

Returns the current session as a session object instance. The session object contains the following properties.

Property | Type | Description
access_token | string | The user's access token.
authentication_token | string | The authentication token.
scope | Array of string values | A list of scopes that the app has requested and that the user has consented to. Note This property is not available for Windows Store apps using JavaScript.
expires_in | number | The amount of time remaining, in seconds, until the user's access token expires. Note This property is not available for Windows Store apps using JavaScript.
expires | number | The exact time when the session will expire. This time is expressed in the number of seconds since 1 January, 1970. Note This property is not available for Windows Store apps using JavaScript.

Examples

The following example uses an event handler, onSessionChange, to handle the auth.sessionChange event. When called, onSessionChange calls WL.getSession to get the session object.

HTML
function onSessionChange() {
    var session = WL.getSession();
    if (session) {
    document.getElementById("infoLabel").innerText =
        "Something about the session changed.";
    }
    else {
        document.getElementById("infoLabel").innerText =
            "Signed out or session error.";
    }
}

Requirements

Header
Not applicable

Library
Wl.js

DLL
Not applicable


WL.init function

Initializes the JavaScript library. An app must call this function before making other function calls in the library, except for subscribing to events. Your app must call this function on every page before making other function calls in the library. The app should make function calls that subscribe to events before calling WL.init. If the JavaScript library has already been initialized on the page, calling this function succeeds silently; the client_id and redirect_uri parameters are not validated.

Parameters

properties

Required. A JSON object that must be formatted with the following properties.

Property Type Description Default Value

client_id

string

Web apps: Required. Specifies your app's OAuth client ID for web apps.

Windows Store apps using JavaScript: not needed.

None.

redirect_uri

string

Required. Contains the default redirect URI to be used for OAuth authentication. For web apps, the OAuth server redirects to this URI during the OAuth flow.

For Windows Store apps using JavaScript, specifying this value will enable the library to return the authentication token.

Web apps: the URL of the current page.

Windows Store apps using JavaScript: none.

scope

string

Optional. The scope values used to determine which portions of user data the app has access to, if the user consents.

For a single scope, use this format: scope: "wl.signin". For multiple scopes, use this format: scope: ["wl.signin", "wl.basic"].

None.

logging

boolean

Optional. If set to "true", the library logs error info to the web browser console and notifies your app by means of the wl.log event.

"true"

status

boolean

Web apps: optional.

Windows Store apps using JavaScript: not applicable.

If set to "true", the library attempts to retrieve the user's sign-in status from Live Connect.

"true"

response_type

string

Web apps: optional.

Windows Store apps using JavaScript: not applicable.

Specifies the OAuth response type value. If set to "token", the client receives the access token directly. If set to "code", the client receives an authorization code, and the app server that serves the redirect_uri page should retrieve the access_token from the OAuth server by using the authorization code and client secret.

You can only set response_type to "code" for web apps.

"token"

secure_cookie

string

Web apps: optional.

Windows Store apps using JavaScript: not applicable.

Optional. If set to "true", the library specifies a secure attribute when writing a cookie on an HTTPS page.

"false"

Return value

This function returns the following errors:

  • WL.init: The input parameter/property 'client_id' must be included.
  • WL.init: The input parameter/property 'properties' must be included.

Examples

Web sites can call WL.init as shown here.

HTML
WL.init({
    client_id: APP_CLIENT_ID,
    redirect_uri: REDIRECT_URL,
    scope: "wl.signin",
    response_type: "token"
});

Windows Store apps using JavaScript can call WL.init like this.

JavaScript
WL.init({scope: "wl.signin"});

Requirements

Header
Not applicable

Library
Wl.js

DLL
Not applicable


WL.login function

Signs in the user or expands the user's list of scopes. Because this function can result in launching the consent page prompt, you should call it only in response to a user action, such as clicking a button. Otherwise, the user's web browser might block the popup.

Typically, this function is used by apps that define their own sign-in controls, or by apps that ask users to grant additional permissions during an activity. For example, to enable a user to post his or her status to Live Connect, your app may have to prompt the user for permission and call this function with an expanded scope.

If you call this function when the user has already consented to the requested scope and is already signed in, the callback function is invoked immediately with the current session.

This function logs errors to the web browser console.

Parameters

properties

Required. A JSON object formatted with the following properties.

Name Type Description Default Value

redirect_uri

string

This parameter only applies to web apps.

Optional. Contains the redirect URI to be used for OAuth authentication. This value overrides the default redirect URI that is provided in the call to WL.init.

The redirect_uri value specified in WL.init.

scope

string or array of string values

Required. Specifies the scopes to which the user who is signing in consents.

For a single scope, use this format: scope: "wl.signin". For multiple scopes, use this format: scope: ["wl.signin", "wl.basic"].

If no scope is provided, the scope value of WL.init is used. If no scope is provided in WL.init or WL.login, WL.login returns an error.

Note WL.login can request the "wl.offline_access" scope, but it requires a server-side implementation, and the WL.init function must set its response_type property to "code". For more info, see Server-side scenarios.

None.

state

string

Windows Store apps using JavaScript: not applicable.

Web apps: Optional. If the WL.init function's response_type object is set to "code" and the app uses server-flow authentication, the state object here can be used to track the web app's calling state on the web app server side. For more info, see the description of the state query parameter in the Server-side scenarios topic's "Getting an authorization code" section.

None.

callback

Optional. Specifies a callback function to execute when sign-in is complete. The callback function takes the status object as a parameter. For a description of the status object, see WL.getLoginStatus. If you do not specify a callback function, your app can still get the sign-in callback info by listening for an auth.sessionChange or auth.statusChange event.

Note Although the callback parameter is still supported, we recommend that you use the Promise object instead.

Return value

Returns a Promise object. This object's then method provides the onSuccess, onError, and onProgress parameters to enable your code to handle a successful, failed, and in-progress call to the corresponding WL.login method, respectively.

Examples

The following example demonstrates how to sign in a user.

JavaScript
function streamlineAccountReg_onClick() {
    WL.login({
        scope: ["wl.signin", "wl.basic", "wl.birthday", "wl.emails"]
    }).then(
        function (response) {
            WL.api({
                path: "me",
                method: "GET"
            }).then(
                function (response) {
                    document.getElementById("first_name").innerText = response.first_name;
                    document.getElementById("last_name").innerText = response.last_name;
                    document.getElementById("email").innerText = response.emails.preferred;
                    document.getElementById("gender").innerText = response.gender;
                    document.getElementById("birthday").innerText =
                        response.birth_month + " " + response.birth_day + " " + response.birth_year;
                },
                function (responseFailed) {
                    document.getElementById("infoArea").innerText =
                        "Error calling API: " + responseFailed.error.message;
                }
            );
        },
        function (responseFailed)
        {
            document.getElementById("infoArea").innerText =
                "Error signing in: " + responseFailed.error_description;
        }
    );
}

Requirements

Header
Not applicable

Library
Wl.js

DLL
Not applicable


WL.logout function

Signs the user out of Live Connect and clears any user state that is maintained by the JavaScript library, such as cookies. If the user account is connected, this function logs out the user from the app, but not from the PC. This function is useful primarily for websites that do not use the sign-in control.

Parameters

callback

Optional. Specifies a callback function that is executed when sign-out is complete. The callback function takes the status object as a parameter. For a description of the status object, see WL.getLoginStatus. If you do not specify a callback function, your app can still get the sign-out callback info by listening for an auth.sessionChange or auth.statusChange event.

Note Although the callback parameter is still supported, we recommend that you use the Promise object instead, which is described later in this topic.

Return value

Returns a Promise object. This object's then method provides the onSuccess, onError, and onProgress parameters to enable your code to handle a successful, failed, and in-progress call to the corresponding WL.logout method, respectively.

Examples

HTML
function signUserOut() {
    WL.logout();
}
document.write("<button onclick='signUserOut()'>Click here to sign out!</button>");

Requirements

Header
Not applicable

Library
Wl.js

DLL
Not applicable


WL.ui function

Displays either the Live Connect sign-in button or the Microsoft SkyDrive file picker button. The sign-in button either prompts the user for his or her Microsoft account credentials if he or she is not signed in or else signs out the user if he or she is signed in. The file picker button displays the SkyDrive file picker to help the user select files to upload or download to or from his or her SkyDrive storage location.

Parameters

properties

Required. A JSON object containing the following properties for displaying the button.

Name Type Description Default Value

name

string

Required. Specifies the type of button to display. Specify "signin" to display the Live Connect sign-in button. Specify "skydrivepicker" to display the SkyDrive button..

None.

element

string

Required. The value of the id attribute of the <div> tag to display the button in.

None.

state

string

Windows Store apps using JavaScript: not applicable.

Web apps: Optional. If the name property is set to "signin", the WL.init function's response_type property is set to "code", and the app uses server-flow authentication, the state object here can be used to track the web app's calling state on the web app server side. For more info, see the description of the state query parameter in the Server-side scenarios topic's "Getting an authorization code" section.

None.

If the value of the name property is set to "skydrivepicker", the properties object can also contain the following.

Name Type Description Default Value

mode

string

Required. The type of SkyDrive file picker button to display. Specify "save" to display the upload button. Specify "open" to display the download button.

None.

select

string

Required if the mode property is set to "open". Specifies how many files the user can select to download. Specify "single" for a single file. Specify "multi" for multiple files.

"single"

theme

string

Optional. Defines the color pallette used for the file picker button. Valid values are "white" and "blue".

"white"

lightbox

string

Optional. Defines the color pallette used for the file picker dialog box. Valid values are "white", "gray", and "transparent".

"white"

onselected

object

Optional. If the mode property is set to "save", specifies the function to call after the user clicks either Save or Cancel in the file picker. If the mode property is set to "open", specifies the function to call after the user clicks either Open or Cancel in the file picker.

None.

onerror

object

Optional. Specifies the function to call if the selected files cannot be successfully uploaded or downloaded.

None.

If the value of the name property is set to "signin", the properties object can also contain the following.

Name Type Description Default Value

brand

string

Optional. Defines the brand, or type of icon, to be used with the Live Connect sign-in button. Valid values for this property are listed in the next table.

"windows"

theme

string

Optional. Defines the color pallette used for the sign-in button. For Windows Store apps using JavaScript, valid values are "dark" and "light".

For web apps, valid values are "blue" and "white".

"dark" (for Windows Store apps using JavaScript)

"blue" (for web apps)

type

string

Optional. Defines the type of button. Valid values for this property are listed in the second table following this one.

"signin"

sign_in_text

string

Optional. If the value of the type property is set to "custom", this value specifies the sign-in text to be displayed in the button.

None.

sign_out_text

string

Optional. If the value of the type property is "custom", this value specifies the sign-out text to be displayed in the button.

None.

onloggedin

object

Optional. Specifies the function to call after the user completes the sign-in process.

None.

onloggedout

object

Optional. Specifies the function to call after the user completes the sign-out process.

None.

onerror

object

Optional. Specifies the function to call whenever there is any error while the sign-in control is initializing or while the user is signing in.

None.

Tip Using the onloggedin, onloggedout, and onerror parameters is functionally equivalent to calling the WL.Event.subscribe("auth.login", callback) function.

The sign-in button's brand property can have one of the following values.

Value Description

"messenger"

Messenger. Shows the Messenger "buddy" icon.

"hotmail"

Hotmail. Shows the "envelope" icon.

"windows"

Live Connect. Shows the Live Connect "flag" icon. This is the default value for both web apps and Windows Store apps using JavaScript.

"skydrive"

SkyDrive. Shows the SkyDrive icon.

"none"

If the value "none" is specified, no icon is shown. If the brand property is left blank, the default value is shown.

The sign-in button's type property can have one of the following values.

Value Sign-in text Sign-out text Additional info

"signin"

Sign in

Sign out

Default.

"login"

Login

Logout

Not applicable.

"connect"

Connect

Sign out

Not applicable.

"custom"

The value supplied in the sign_in_text property.

The value supplied in the sign_out_text property.

Your app defines the text. If the app does not provide sign_in_text and sign_out_text property values, the library will return an error, and the button will not be displayed.

callback

Optional. A callback function that is executed after the sign-in button or file picker button is displayed.

Note Do not use the callback parameter to run code after the user finishes interacting with the sign-in button or file picker. Use a combination of the onselected, onloggedin, onloggedout, and onerror properties as previously described.

Remarks

The sign-in coding patterns that are appropriate for Windows Store apps using C# are described in the Guidelines for the Microsoft account sign-in experience.

Examples

The following example demonstrates how to display the Live Connect sign-in button.

HTML
WL.ui({
    name: "signin",
    element: "signin"
});

The following example demonstrates how to display the upload version of the SkyDrive file picker.

HTML
<div id="uploadFile_div">SkyDrive save button to appear here</div>
HTML
WL.ui({
    name: "skydrivepicker",
    element: "uploadFile_div",
    mode: "save",
    onselected: onUploadFileCompleted,
    onerror: onUploadFileError
});

function onUploadFileCompleted(response) {
    WL.upload({
        path: response.data.folders[0].id,
        element: "file",
        overwrite: "rename"
    }).then(
        function (response) {
            document.getElementById("info").innerText =
                "File uploaded.";
        },
        function (responseFailed) {
            document.getElementById("info").innerText =
                "Error uploading file: " + responseFailed.error.message;
        }
    );
};

function onUploadFileError(response) {
    document.getElementById("info").innerText =
        "Error getting folder info: " + response.error.message;
}

The following example demonstrates how to display the download version of the file picker.

HTML
<div id="downloadFile_div">SkyDrive open button to appear here</div>
HTML
WL.ui({
    name: "skydrivepicker",
    element: "downloadFile_div",
    mode: "open",
    select: "multi",
    onselected: onDownloadFileCompleted,
    onerror: onDownloadFileError
});

function onDownloadFileCompleted(response) {
    var msg = "";
    // For each folder selected...
    if (response.data.folders.length > 0) {
        for (folder = 0; folder < response.data.folders.length; folder++) {
            // Use folder IDs to iterate through child folders and files as needed.
            msg += "\n" + response.data.folders[folder].id;
        }
    }
    // For each file selected...
    if (response.data.files.length > 0) {
        for (file = 0; file < response.data.files.length; file++) {
            // Use file IDs to iterate through files as needed.
            msg += "\n" + response.data.files[file].id;
        }
    }
    document.getElementById("info").innerText =
        "Selected folders/files:" + msg;
};

function onDownloadFileError(responseFailed) {
    document.getElementById("info").innerText =
        "Error getting folder/file info: " + responseFailed.error.message;
}

Requirements

Header
Not applicable

Library
Wl.js

DLL
Not applicable


WL.upload function

Makes a call to upload a file to Microsoft SkyDrive.

Important WL.upload is supported only for use with web apps. If you are writing a Windows Store app using JavaScript, use WL.backgroundUpload instead.

Parameters

properties

Required. A JSON object that contains the following properties, which are necessary to make the REST API call.

Name Type Description Default Value

path

string

Required. The path to the file to upload.

None

element

string

Required. The id attribute of the <input> tag containing info about the file to upload.

None

overwrite

string

Optional. Indicates whether the uploaded file should overwrite an existing copy. Specify true or "true" to overwrite, false or "false" to not overwrite and for the WL.upload method call to fail, or "rename" to not overwrite and enable SkyDrive to assign a new name to the uploaded file.

"false"

callback

Optional. Specifies a callback function that is executed when the REST API call is complete. The callback function takes the API response object as a parameter. The response object exposes the data returned from Live Connect, or if an error occurs, an error property that contains the error code.

Note Although the callback parameter is still supported, we recommend that you use the Promise object instead, which is described later in this topic.

Return value

Returns a Promise object. This object's then method provides the onSuccess, onError, and onProgress parameters to enable your code to handle a successful, failed, and in-progress call to the corresponding WL.upload method, respectively; however, the onProgress parameter applies to newer web browsers such as Internet Explorer 10 only.

Examples

HTML
<form>
    <input id="file" name="file" type="file" />
</form>
HTML
<button onclick="uploadFile()">Save file directly (calling WL.upload)</button>
HTML
function uploadFile() {
    WL.login({
        scope: "wl.skydrive_update"
    }).then(
        function (response) {
            WL.upload({
                path: "folder.a6b2a7e8f2515e5e.A6B2A7E8F2515E5E!170",
                element: "file",
                overwrite: "rename"
            }).then(
                function (response) {
                    document.getElementById("info").innerText =
                        "File uploaded.";
                },
                function (responseFailed) {
                    document.getElementById("info").innerText =
                        "Error uploading file: " + responseFailed.error.message;
                }
            );
        },
        function (responseFailed) {
            document.getElementById("info").innerText =
                "Error signing in: " + responseFailed.error.message;
        }
    );
}

Requirements

Header
Not applicable

Library
Wl.js

DLL
Not applicable


JSONP scenarios

You can use JavaScript Objection Notation with padding (JSONP) in client-side JavaScript webpage code to interact directly with the Live Connect Representational State Transfer (REST) API. Using JSONP is especially helpful when you want to retrieve simple Live Connect info for an individual user without writing all of the code to call the Live Connect JavaScript API. For example, with as little as a single line of code, you can make a request for a user's full name, info about one of the user's contacts, or one of the user's photos.

There are two main usage patterns for using JSONP: you can call JSONP as a webpage loads, and you can call it in response to a user action on a webpage.

Calling JSONP as a webpage loads

In this usage pattern, JSONP is called while the containing webpage initially loads from beginning to end, as shown in the following code example.

HTML
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <title></title>
    </head>
    <body>
        <textarea id="response" style="width:100%" cols="0" rows="20"></textarea>

        <script src="JSONP.js"></script>
        <script src="json2.js"></script>

        <script>
            function onResponse(response) {
                var jsonAsString = JSON.stringify(response);

                document.getElementById("response").value = jsonAsString;
            }
        </script>

        <script src="">
        </script>

        <script>
            var scripts = document.getElementsByTagName("script");
            scripts[3].src = REST_API_URL;
        </script>
    </body>
</html>

The following occurs in the preceding code sample:

  1. While the webpage loads, when the JavaScript interpreter reaches the last script element, the interpreter takes the URL string from the script in the JSONP.js file and inserts it into the empty src attribute of the fourth script element.
  2. When the webpage finishes loading, the JavaScript interpreter invokes the fourth script element, which calls the Live Connect REST API. The REST API delivers the results of the call as a JavaScript Object Notation (JSON)-formatted string to the onResponse function. (This function is specified in the src attribute's callback URL parameter.)
  3. The onResponse function uses the JSON.stringify function to convert the JSON-formatted data into a string, which is displayed in the textarea control on the webpage.

The preceding code sample relies on two additional JavaScript scripts: JSONP.js and json2.js. The JSONP.js JavaScript file contains the following code.

JavaScript
var ENDPOINT_REST_API = "https://apis.live.net/",
    ENDPOINT_REST_API_VERSION = "v5.0/",
    REST_PATH_ME = "me/",
    REST_PATH_CONTACTS = "contacts",
    ACCESS_TOKEN_PARAM = "?access_token=",
    JSONP_CALLBACK_PARAM = "&callback=",
    JSONP_CALLBACK_FUNCTION = "onResponse";

var ACCESS_TOKEN = "EwBQAq1DBAAUlbRWyAJjK5w968Ru3Cyt/6GvwXwAAXNW6nTKzZqgl86qQPkmd1Yo4n+RZvmkdocatHGf3ZVvW2ZnrDFYg2cpMsbYEtA8pIQmdmCmx1WceM331ELb/uj+6Ckckq8A+xmzdOOiUiwhnO45ep8ty1n0vVURSHh4x9jKv7nQjGH+QJIV6AezLV+lIYYoyI+rqUzNYB+d8GGxuBSU/mgM/N8hYZMq8t95+OPl5TUmtJL+ptaACnFle/ne+fCjfacq3phbWdwvy7YSM69LEAaWAktP84vqNFN9Apyd1br6ifcWE3v1P2n3l4gHO6xXl+40fHICp7uioVZFysDV+eGP3qMPpTsZ7FDC1G3UmSMEI3Z5MdD5Pn4Q5r4DZgAACHsFxmD0xGYUIAGOfYQ7Ft4UFC9HgsHJlhImWVZz9ZZvF4xMDlfkHCuMRV9/5qn6JzA9/3UR0Of+724+vcsik/LNJSLeFTNzCKUTML+WVUitO2sXYDjzsz5E8T4xjIKMo0lAzfuCJ0bjTI1jWWuipyBaYNhz7wtl+eSID5iAi2xoloPLHyyfgTkk1dJRk2DwR239GZLwKbK+rWpER5u1cGHBRpIFMDJZIvPUz7AIeDaVQXf81jUAfZT1MdwsjwGdbnjni4csoQdpQNzjE0WC3HyEFM4jPSev/5eEfyaz8iM2O+RFXKA326gnPUYjvw8O3o1yqYyzGT5tbypNvDg1R9rIt7or479OGf1VV7yhOEE8CUb+RBtVoROsWEIBtxptrSlGmg7Nii9RahAAAA==";

var REST_API_URL = ENDPOINT_REST_API + ENDPOINT_REST_API_VERSION +
        REST_PATH_ME + REST_PATH_CONTACTS +
        ACCESS_TOKEN_PARAM + ACCESS_TOKEN +
        JSONP_CALLBACK_PARAM + JSONP_CALLBACK_FUNCTION;

The preceding script contains variables that can help you debug and isolate run-time errors caused by any changes to hard-coded URLs upon which the Live Connect REST API relies.

The json2.js script converts JSON-formatted strings and objects. Although similar functionality is supplied by default with several web browsers, this script is referenced locally to achieve compatibility with a wider range of web browsers. You can get this script by visiting a website, such as Introducing JSON (http://www.json.org).

Note To adapt the preceding code example for your own use, replace the value of the ACCESS_TOKEN with an access token that represents your requested scope for the user. For more info, see Server-side scenarios.

Calling JSONP in response to a user action in a webpage

In this usage pattern, JSONP is called only when the user performs an action in the containing webpage, as shown in the following code example.

HTML
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <title></title>
    </head>
    <body>
        <button id="callApi" onclick="onCallApiClicked()">Call API</button>
        <textarea id="response" style="width:100%" cols="0" rows="20"></textarea>

        <script src="JSONP.js"></script>
        <script src="json2.js"></script>

        <script>
            function onCallApiClicked() {
                var script = document.createElement("script");
                script.type = "text/javascript";
                script.language = "javascript";
                script.src = REST_API_URL;
                document.body.appendChild(script);
            }

            function onResponse(response) {
                var jsonAsString = JSON.stringify(response);
                document.getElementById("response").value = jsonAsString;
            }
        </script>
    </body>
</html>

This example differs from the example in the preceding section in the following ways:

  • Because none of the script elements initially contains any calls to the Live Connect REST API, nothing happens after the webpage finishes loading.
  • When the user clicks the Call API button, the onCallApiClicked function creates a new script element at the end of the webpage. The function takes the URL string from the JSONP.js script and inserts it into the element's src attribute.
  • After the function calls the document.body.appendChild function, the JavaScript interpreter invokes the new element, which then calls the Live Connect REST API.
  • The code continues to run as in the preceding section.

Each time the user clicks the Call API button, a new script element is created. As each new element is appended to the end of the webpage, the new element calls the Live Connect REST API.


Managed API (Windows 8 and Windows Phone)

The Live Connect Managed API (Windows 8 and Windows Phone) simplifies the process of accessing user data from within Windows Store apps and Windows Phone apps, and provides controls to facilitate the sign-in experience for users. It includes the following namespaces.

Namespace | Description
Microsoft.Live | Contains classes that simplify access to Live Connect OAuth authentication, user session data, and the Live Connect REST API.
Microsoft.Live.Controls | Contains the Live Connect controls, which facilitate the sign-in experience for users.


Microsoft.Live namespace

Contains classes that simplify access to Live Connect OAuth authentication, user session data, and the Live Connect REST API.

Note All of the following members apply to both Windows 8 and Windows Phone unless otherwise noted.

Members

The Microsoft.Live namespace has these types of members:

  • Classes
  • Enumerations

Classes

The Microsoft.Live namespace has these classes.

Class | Description
LiveAuthClient (Windows 8) | Used to retrieve session data from Live Connect.
LiveAuthClient (Windows Phone) | Used to retrieve session data from Live Connect.
LiveAuthException | Used to indicate when an exception has occurred during the Auth process.
LiveConnectClient (Windows 8) | Exposes the primary functionality of the Live Connect web service endpoints, and manages token expiry.
LiveConnectClient (Windows Phone) | Exposes the primary functionality of the Live Connect web service endpoints, and manages token expiry.
LiveConnectException | Used to indicate when an exception has occurred during the connection process.
LiveConnectSession (Windows 8) | Used to access the current session.
LiveConnectSession (Windows Phone) | Used to access the current session.
LiveDownloadCompletedEventArgs (Windows Phone) | Raised when a file download operation is completed.
LiveDownloadOperationResult (Windows 8) | Represents the results of a file download operation.
LiveDownloadOperationResult (Windows Phone) | Represents the result of a Microsoft SkyDrive file download request.
LiveDownloadProgressChangedEventArgs (Windows Phone) | Raised every time a chunk of data is downloaded during a download operation.
LiveLoginResult | Represents a live login.
LiveOperationCompletedEventArgs (Windows Phone) | Contains event arguments for the events raised when an operation is completed.
LiveOperationProgress (Windows 8) | Represents the progress of a file upload or download request.
LiveOperationResult | Represents the result of the operation.
LiveUploadProgressChangedEventArgs (Windows Phone) | Raised every time a chunk of data is uploaded during an upload operation.
LoginCompletedEventArgs (Windows Phone) | Contains event arguments for the events raised when login is completed.

Enumerations

The Microsoft.Live namespace has these enumerations.

Enumeration | Description
LiveConnectSessionStatus | Indicates the status of the session.
OverwriteOption | Indicates whether an incoming file that's being uploaded to Microsoft SkyDrive should overwrite an existing file with the same file name in that location.
ThemeType (Windows 8) | Specifies the theme type.

Requirements

Namespace

Microsoft.Live

Assembly
Microsoft.Live.dll


LiveAuthClient class

Used to retrieve session data from Live Connect.

Syntax

C#
public class LiveAuthClient

Attributes

None

Members

The LiveAuthClient class has these types of members:

  • Constructors
  • Events
  • Methods
  • Properties

Constructors

The LiveAuthClient class has these constructors.

Constructor | Description
LiveAuthClient() method | Initializes a new instance of the LiveAuthClient class.
LiveAuthClient(String) method | Initializes a new instance of the LiveAuthClient class with the specified redirect Uniform Resource Identifier (URI).

Events

The LiveAuthClient class has these events.

Event | Description
PropertyChanged event | Raises an event when the Session property is changed.

Methods

The LiveAuthClient class has these methods. It also inherits methods from the Object class.

Method | Description
InitializeAsync() method | Initializes a new LiveAuthClient.
InitializeAsync(IEnumerable<String>) method | Initializes a new LiveAuthClient with the given scopes.
LoginAsync(IEnumerable<String>) method | Logs in a user with the given scopes.
Logout() method | Signs the user out from Live Connect.

Properties

The LiveAuthClient class has these properties.

Property | Access type | Description
CanLogout property | Read-only | Gets whether the current user can be signed out of his or her Microsoft account.
Session property | Read-only | The current session for the connected user.
Theme property | Read/write | Defines the appearance of the sign-in control.

Requirements

Minimum supported client

 Windows 8

Minimum supported server

 None supported

Namespace

Microsoft.Live

Assembly
Microsoft.Live.dll


LiveAuthClient.CanLogout property

Gets whether the current user can be signed out of his or her Microsoft account.

Syntax

C#
public bool CanLogout { get; }

Property value

Type: Boolean

Returns True if the user can be signed out; otherwise, returns False if the user can't be signed out.

Requirements

Minimum supported client

 Windows 8

Minimum supported server

 None supported

Namespace

Microsoft.Live

Assembly
Microsoft.Live.dll

See also

LiveAuthClient


LiveAuthClient.InitializeAsync methods

Initiates the Live Connect sign-in flow in silent mode. If the user is already signed in and has connected the app to Live Connect, a session object is created with a valid access token.

This member is overloaded. For complete information about this member, including syntax, usage, and examples, click a name in the overload list.

Overload list

Method | Description
InitializeAsync() method | Initializes a new LiveAuthClient.
InitializeAsync(IEnumerable<String>) method | Initializes a new LiveAuthClient with the given scopes.

Requirements

Minimum supported client | Windows 8
Minimum supported server | None supported
Namespace | Microsoft.Live

See also

LiveAuthClient


LiveAuthClient.InitializeAsync() method

Initializes a new LiveAuthClient.

Syntax

C#
public Task<LiveLoginResult> InitializeAsync()

Parameters

This method has no parameters.

Return value

Type: Task<LiveLoginResult>

The user's login status and the session object.

Requirements

Minimum supported client

 Windows 8

Minimum supported server

 None supported

Namespace

Microsoft.Live

Assembly
Microsoft.Live.dll

See also

LiveAuthClient


LiveAuthClient.InitializeAsync(IEnumerable<String>) method

Initializes a new LiveAuthClient with the given scopes.

Syntax

C#
public Task<LiveLoginResult> InitializeAsync(
  IEnumerable<String> scopes
)

Parameters

scopes

Type: IEnumerable<String>

The list of scopes.

Return value

Type: Task<LiveLoginResult>

The user's login status and the session object.

Requirements

Minimum supported client

 Windows 8

Minimum supported server

 None supported

Namespace

Microsoft.Live

Assembly
Microsoft.Live.dll

See also

LiveAuthClient


LiveAuthClient.LiveAuthClient constructors

Initializes a new instance of the LiveAuthClient class.

This member is overloaded. For complete information about this member, including syntax, usage, and examples, click a name in the overload list.

Overload list

Constructor | Description
LiveAuthClient() constructor | Initializes a new instance of the LiveAuthClient class.
LiveAuthClient(String) constructor | Initializes a new instance of the LiveAuthClient class with the specified redirect Uniform Resource Identifier (URI).

Remarks

Important LiveAuthClient must be constructed in the app's UI thread.

Requirements

Minimum supported client

 Windows 8

Minimum supported server

 None supported

Minimum supported phone

 Windows Phone 7

Namespace

Microsoft.Live

Assembly
Microsoft.Live.dll

See also

LiveAuthClient


LiveAuthClient.LiveAuthClient() constructor

Initializes a new instance of the LiveAuthClient class.

Syntax

C#
public LiveAuthClient LiveAuthClient()

Parameters

This constructor has no parameters.

Return value

Type: LiveAuthClient

An initialized instance of the class.

Remarks

Important LiveAuthClient must be constructed in the app's UI thread.

Requirements

Minimum supported client

 Windows 8

Minimum supported server

 None supported

Namespace

Microsoft.Live

Assembly
Microsoft.Live.dll

See also

LiveAuthClient
LiveAuthClient(String)


LiveAuthClient.LiveAuthClient(String) constructor

Initializes a new instance of the LiveAuthClient class with the specified redirect Uniform Resource Identifier (URI).

Syntax

C#
public LiveAuthClient LiveAuthClient(
  string redirectUri
)

Parameters

redirectUri

Type: String

The redirect URI corresponding to the one specified in the Windows Store Dashboard or the Live Connect app management site for the corresponding app's client ID.

Return value

Type: LiveAuthClient

An initialized instance of the class.

Remarks

Important LiveAuthClient must be constructed in the app's UI thread.

Requirements

Minimum supported client

 Windows 8

Minimum supported server

 None supported

Namespace

Microsoft.Live

Assembly
Microsoft.Live.dll

See also

LiveAuthClient
LiveAuthClient() constructor


LiveAuthClient.LoginAsync(IEnumerable<String>) method

Logs in a user with the given scopes.

Syntax

C#
public Task<LiveLoginResult> LoginAsync(
  IEnumerable<String> scopes
)

Parameters

scopes

Type: IEnumerable<String>

A list of scopes that are needed by the application.

Return value

Type: Task<LiveLoginResult>

The user's login status and the session object.

Remarks

Important LoginAsync must be called from the app's UI thread.

Requirements

Minimum supported client

 Windows 8

Minimum supported server

 None supported

Namespace

Microsoft.Live

Assembly
Microsoft.Live.dll

See also

LiveAuthClient


LiveAuthClient.Logout method

Signs the user out from Live Connect.

Note that this method does not sign the user out of Windows, it only clears any cached sessions for the current app.

Syntax

C#
public  Logout()

Parameters

This method has no parameters.

Return value

Requirements

Minimum supported client

 Windows 8

Minimum supported server

 None supported

Namespace

Microsoft.Live

Assembly
Microsoft.Live.dll

See also

LiveAuthClient


LiveAuthClient.PropertyChanged event

Raises an event when the Session property is changed.

Syntax

C#
public event PropertyChangedEventHandler PropertyChanged

Event information

Delegate PropertyChangedEventHandler

Requirements

Minimum supported client

 Windows 8

Minimum supported server

 None supported

Namespace

Microsoft.Live

Assembly
Microsoft.Live.dll

See also

LiveAuthClient


LiveAuthClient.Session property

The current session for the connected user.

Syntax

C#
public LiveConnectSession Session { get; }

Property value

Type: LiveConnectSession

Used to access the current session.

Requirements

Minimum supported client

 Windows 8

Minimum supported server

 None supported

Namespace

Microsoft.Live

Assembly
Microsoft.Live.dll

See also

LiveAuthClient


LiveAuthClient.Theme property

Defines the appearance of the sign-in control.

Syntax

C#
public string Theme { get; set; }

Property value

Type: string

Specifies the appearance of the sign-in control. This property can be one of the following values.

Value | Description
dark | Specifies the dark theme. For Windows Store apps only.
light | Specifies the light theme. For Windows Store apps only.
default | Specifies the default theme (dark). For Windows Store apps only.

Requirements

Minimum supported client

 Windows 8

Minimum supported server

 None supported

Namespace

Microsoft.Live

Assembly
Microsoft.Live.dll

See also

LiveAuthClient


LiveAuthClient class

Used to retrieve session data from Live Connect.

Syntax

C#
public class LiveAuthClient

Attributes

None

Members

The LiveAuthClient class has these types of members:

  • Constructors
  • Events
  • Methods
  • Properties

Constructors

The LiveAuthClient class has these constructors.

Constructor | Description
LiveAuthClient(String) method | Initializes a new instance of the LiveAuthClient class and sets the client ID.

Events

The LiveAuthClient class has these events.

Event | Description
InitializeCompleted event | Raised when an InitializeAsync operation is completed.
LoginCompleted event | Raised when a LoginAsync operation is completed.
PropertyChanged event | Raises an event when the Session property is changed.

Methods

The LiveAuthClient class has these methods. It also inherits methods from the Object class.

Method | Description
InitializeAsync() method | Initiates the Live Connect sign-in flow in silent mode. If the user is already signed in and has connected the app to Live Connect, a Session object is created with a valid access token.
InitializeAsync(IEnumerable<String>) method | Initializes the Session object by loading it from cache, specifying a list of scopes.
InitializeAsync(IEnumerable<String>, Object) method | Initializes the Session object by loading it from cache, specifying a list of scopes and a user state.
InitializeAsync(Object) method | Initiates the Live Connect sign-in flow in silent mode. If the user is already signed in and has connected the app to Live Connect, a Session object is created with a valid access token.
LoginAsync(IEnumerable<String>) method | Initiates the Live Connect sign-in flow, or presents a Live Connect consent page.
LoginAsync(IEnumerable<String>, Object) method | Initiates the Live Connect sign-in flow, or presents a Live Connect consent page.
Logout() method | Signs the user out from Live Connect.

Properties

The LiveAuthClient class has these properties.

Property | Access type | Description
Session property | Read-only | The current session for the connected user.

Requirements

Minimum supported client

 None supported

Minimum supported server

 None supported

Minimum supported phone

 Windows Phone 7

Namespace

Microsoft.Live

Assembly
Microsoft.Live.dll


LiveAuthClient.InitializeAsync methods

InitializeAsync initiates the Live Connect sign-in flow in silent mode. If the user is already signed in and has connected the app to Live Connect, a session object is created with a valid access token.

This member is overloaded. For complete information about this member, including syntax, usage, and examples, click a name in the overload list.

Overload list

Method | Description
InitializeAsync() method | Initiates the Live Connect sign-in flow in silent mode. If the user is already signed in and has connected the app to Live Connect, a Session object is created with a valid access token.
InitializeAsync(Object) method | Initiates the Live Connect sign-in flow in silent mode. If the user is already signed in and has connected the app to Live Connect, a Session object is created with a valid access token.
InitializeAsync(IEnumerable<String>) method | Initializes the Session object by loading it from cache, specifying a list of scopes.
InitializeAsync(IEnumerable<String>, Object) method | Initializes the Session object by loading it from cache, specifying a list of scopes and a user state.

Requirements

Minimum supported client

 None supported

Minimum supported server

 None supported

Minimum supported phone

 Windows Phone 7

Namespace

Microsoft.Live

Assembly
Microsoft.Live.dll

See also

LiveAuthClient


LiveAuthClient.InitializeAsync() method

Initiates the Live Connect sign-in flow in silent mode. If the user is already signed in and has connected the app to Live Connect, a Session object is created with a valid access token.

Syntax

C#
public InitializeAsync()

Parameters

This method has no parameters.

Requirements

Minimum supported client

 None supported

Minimum supported server

 None supported

Minimum supported phone

 Windows Phone 7

Namespace

Microsoft.Live

Assembly
Microsoft.Live.dll

See also

LiveAuthClient
InitializeAsync(Object)
InitializeAsync(IEnumerable<string>)
InitializeAsync(IEnumerable<string>, Object)


LiveAuthClient.InitializeAsync(Object) method

Initiates the Live Connect sign-in flow in silent mode. If the user is already signed in and has connected the app to Live Connect, a Session object is created with a valid access token.

Syntax

C#
public InitializeAsync(
  object userState
)

Parameters

userState

Type: Object

The user state object that is used to retrieve an access token for the user.

Requirements

Minimum supported client

 None supported

Minimum supported server

 None supported

Minimum supported phone

 Windows Phone 7

Namespace

Microsoft.Live

Assembly
Microsoft.Live.dll

See also

LiveAuthClient
InitializeAsync()
InitializeAsync(IEnumerable<String>)
InitializeAsync(IEnumerable<String>, Object)


LiveAuthClient.InitializeAsync(IEnumerable<String>) method

Initializes the Session object by loading it from cache, specifying a list of scopes.

Syntax

C#
public InitializeAsync(
  IEnumerable<String> scopes
)

Parameters

scopes

Type: IEnumerable<String>

The list of scopes.

Requirements

Minimum supported client

 None supported

Minimum supported server

 None supported

Minimum supported phone

 Windows Phone 7

Namespace

Microsoft.Live

Assembly
Microsoft.Live.dll

See also

LiveAuthClient
InitializeAsync()
InitializeAsync(Object)
InitializeAsync(IEnumerable<String>, Object)


LiveAuthClient.InitializeAsync(IEnumerable<String>, Object) method

Initializes the Session object by loading it from cache, specifying a list of scopes and a user state.

Syntax

C#
public InitializeAsync(
  IEnumerable<String> scopes,
  object userState
)

Parameters

scopes

Type: IEnumerable<String>

The list of scopes.

userState

Type: Object

The user state.

Requirements

Minimum supported client

 None supported

Minimum supported server

 None supported

Minimum supported phone

 Windows Phone 7

Namespace

Microsoft.Live

Assembly
Microsoft.Live.dll

See also

LiveAuthClient
InitializeAsync()
InitializeAsync(Object)
InitializeAsync(IEnumerable<String>)


LiveAuthClient.InitializeCompleted event

Raised when an InitializeAsync operation is completed.

Syntax

C#
public event EventHandler<LoginCompletedEventArgs> InitializeCompleted

Event information

Delegate EventHandler<LoginCompletedEventArgs>

Requirements

Minimum supported client

 None supported

Minimum supported server

 None supported

Minimum supported phone

 Windows Phone 7

Namespace

Microsoft.Live

Assembly
Microsoft.Live.dll

See also

LiveAuthClient


LiveAuthClient.LiveAuthClient(String) constructor

Initializes a new instance of the LiveAuthClient class and sets the client ID.

Syntax

C#
public LiveAuthClient LiveAuthClient(
  string clientID
)

Parameters

clientID

Type: String

A unique identifier that is used by the client app to connect to Live Connect.

Return value

Type: LiveAuthClient

An initialized instance of the class.

Requirements

Minimum supported client

 None supported

Minimum supported server

 None supported

Minimum supported phone

 Windows Phone 7

Namespace

Microsoft.Live

Assembly
Microsoft.Live.dll

See also

LiveAuthClient
LiveAuthClient() constructor


LiveAuthClient.LoginAsync methods

Initiates the Live Connect sign-in flow, or presents a Live Connect consent page. You can use LoginAsync as an alternative to the sign-in control, or to prompt the user for additional permissions in the context of an activity.

This member is overloaded. For complete information about this member, including syntax, usage, and examples, click a name in the overload list.

Overload list

Method | Description
LoginAsync(IEnumerable<String>) method | Initiates the Live Connect sign-in flow, or presents a Live Connect consent page.
LoginAsync(IEnumerable<String>, Object) method | Initiates the Live Connect sign-in flow, or presents a Live Connect consent page.

Remarks

Important LiveAuthClient must be constructed in the app's UI thread.

Requirements

Minimum supported client

 None supported

Minimum supported server

 None supported

Minimum supported phone

 Windows Phone 7

Namespace

Microsoft.Live

Assembly
Microsoft.Live.dll

See also

LiveAuthClient


LiveAuthClient.LoginAsync(IEnumerable<String>) method

Initiates the Live Connect sign-in flow, or presents a Live Connect consent page. You can use LoginAsync as an alternative to the sign-in control, or to prompt the user for additional permissions in the context of an activity.

Syntax

C#
public LoginAsync(
  IEnumerable<String> scopes
)

Parameters

scopes

Type: IEnumerable<String>

A list of scopes that are needed by the app.

Remarks

Important LoginAsync must be called from the app's UI thread.

Requirements

Minimum supported client

 None supported

Minimum supported server

 None supported

Minimum supported phone

 Windows Phone 7

Namespace

Microsoft.Live

Assembly
Microsoft.Live.dll

See also

LiveAuthClient
LoginAsync(IEnumerable<String>, Object)


LiveAuthClient.LoginAsync(IEnumerable<String>, Object) method

Initiates the Live Connect sign-in flow, or presents a Live Connect consent page. You can use LoginAsync as an alternative to the sign-in control, or to prompt the user for additional permissions in the context of an activity.

Syntax

C#
public LoginAsync(
  IEnumerable<String> scopes,
  object userState
)

Parameters

scopes

Type: IEnumerable<String>

A list of scopes that are needed by the application.

userState

Type: Object

The current user state.

Remarks

Important LoginAsync must be called from the app's UI thread.

Requirements

Minimum supported client

 None supported

Minimum supported server

 None supported

Minimum supported phone

 Windows Phone 7

Namespace

Microsoft.Live

Assembly
Microsoft.Live.dll

See also

LiveAuthClient
LoginAsync(IEnumerable<String>)


LiveAuthClient.LoginCompleted event

Raised when a LoginAsync operation is completed.

Syntax

C#
public event EventHandler<LoginCompletedEventArgs> LoginCompleted

Event information

Delegate EventHandler<LoginCompletedEventArgs>

Requirements

Minimum supported client

 None supported

Minimum supported server

 None supported

Minimum supported phone

 Windows Phone 7

Namespace

Microsoft.Live

Assembly
Microsoft.Live.dll

See also

LiveAuthClient


LiveAuthClient.Logout method

Signs the user out from Live Connect.

Note that this method does not sign the user out of Windows, it only clears any cached sessions for the current app.

Syntax

C#
public  Logout()

Parameters

This method has no parameters.

Return value

Requirements

Minimum supported client

 None supported

Minimum supported server

 None supported

Minimum supported phone

 Windows Phone 7

Namespace

Microsoft.Live

Assembly
Microsoft.Live.dll

See also

LiveAuthClient


LiveAuthClient.PropertyChanged event

Raises an event when the Session property is changed.

Syntax

C#
public event PropertyChangedEventHandler PropertyChanged

Event information

Delegate PropertyChangedEventHandler

Requirements

Minimum supported client

 None supported

Minimum supported server

 None supported

Minimum supported phone

 Windows Phone 7

Namespace

Microsoft.Live

Assembly
Microsoft.Live.dll

See also

LiveAuthClient


LiveAuthClient.Session property

The current session for the connected user.

Syntax

C#
public LiveConnectSession Session { get; }

Property value

Type: LiveConnectSession

Used to access the current session.

Requirements

Minimum supported client

 None supported

Minimum supported server

 None supported

Minimum supported phone

 Windows Phone 7

Namespace

Microsoft.Live

Assembly
Microsoft.Live.dll

See also

LiveAuthClient


LiveAuthException class

Used to indicate when an exception has occurred during the Auth process.

Syntax

C#
public class LiveAuthException

Attributes

None

Members

The LiveAuthException class has these types of members:

  • Constructors
  • Methods
  • Properties

Constructors

The LiveAuthException class has these constructors.

Constructor | Description
LiveAuthException() method | Initializes a new instance of the LiveAuthException class.
LiveAuthException(String, String) method | Initializes a new instance of the LiveAuthException class, passing an error code string and a message string.
LiveAuthException(String, String, Exception) method | Initializes a new instance of the LiveAuthException class, passing an error code string, a message string, and a Exception object.

Methods

The LiveAuthException class has these methods. It also inherits methods from the Object class.

Method | Description
ToString() method | Returns a string that represents the current object.

Properties

The LiveAuthException class has these properties.

Property | Access type | Description
ErrorCode property | Read-only | The error code that is returned from the Auth operation.

Requirements

Minimum supported client

 Windows 8

Minimum supported server

 None supported

Minimum supported phone

 Windows Phone 7

Namespace

Microsoft.Live

Assembly
Microsoft.Live.dll


LiveAuthException.ErrorCode property

The error code that is returned from the Auth operation.

Syntax

C#
public string ErrorCode { get; }

Property value

Type: String

The error code.

Requirements

Minimum supported client

 Windows 8

Minimum supported server

 None supported

Minimum supported phone

 Windows Phone 7

Namespace

Microsoft.Live

Assembly
Microsoft.Live.dll

See also

LiveAuthException
LiveAuthClient


LiveAuthException.LiveAuthException constructors

Initializes a new instance of the LiveAuthException class.

This member is overloaded. For complete information about this member, including syntax, usage, and examples, click a name in the overload list.

Overload list

Constructor | Description
LiveAuthException() constructor | Initializes a new instance of the LiveAuthException class.
LiveAuthException(String, String) constructor | Initializes a new instance of the LiveAuthException class, passing an error code string and a message string.
LiveAuthException(String, String, Exception) constructor | Initializes a new instance of the LiveAuthException class, passing an error code string, a message string, and a Exception object.

Requirements

Minimum supported client

 Windows 8

Minimum supported server

 None supported

Minimum supported phone

 Windows Phone 7

Namespace

Microsoft.Live

Assembly
Microsoft.Live.dll

See also

LiveAuthException


LiveAuthException.LiveAuthException() constructor

Initializes a new instance of the LiveAuthException class.

Syntax

C#
public  LiveAuthException()

Parameters

This constructor has no parameters.

Return value

Requirements

Minimum supported client

 Windows 8

Minimum supported server

 None supported

Minimum supported phone

 Windows Phone 7

Namespace

Microsoft.Live

Assembly
Microsoft.Live.dll

See also

LiveAuthException
LiveAuthException(String, String)
LiveAuthException(String, String, Exception)


LiveAuthException.LiveAuthException(String, String) constructor

Initializes a new instance of the LiveAuthException class, passing an error code string and a message string.

Syntax

C#
public LiveAuthException(
  string errorCode,
  string message
)

Parameters

errorCode

Type: String

The error code for the exception.

message

Type: String

The exception message.

Requirements

Minimum supported client

 Windows 8

Minimum supported server

 None supported

Minimum supported phone

 Windows Phone 7

Namespace

Microsoft.Live

Assembly
Microsoft.Live.dll

See also

LiveAuthException
LiveAuthException()
LiveAuthException(String, String, Exception)


LiveAuthException.LiveAuthException(String, String, Exception) constructor

Initializes a new instance of the LiveAuthException class, passing an error code string, a message string, and a Exception object.

Syntax

C#
public LiveAuthException(
  string errorCode,
  string message,
  Exception innerException
)

Parameters

errorCode

Type: String

The error code for the exception.

message

Type: String

The exception message.

innerException

Type: Exception

The inner exception.

Requirements

Minimum supported client

 Windows 8

Minimum supported server

 None supported

Minimum supported phone

 Windows Phone 7

Namespace

Microsoft.Live

Assembly
Microsoft.Live.dll

See also

LiveAuthException
LiveAuthException()
LiveAuthException(String, String)


LiveAuthException.ToString method

Returns a string that represents the current object.

Syntax

C#
public string ToString()

Parameters

This method has no parameters.

Return value

Requirements

Minimum supported client

 Windows 8

Minimum supported server

 None supported

Minimum supported phone

 Windows Phone 7

Namespace

Microsoft.Live

Assembly
Microsoft.Live.dll

See also

LiveAuthException


LiveConnectClient class

Exposes the primary functionality of the Live Connect web service endpoints, and manages token expiry.

Syntax

C#
public class LiveConnectClient

Attributes

None

Members

The LiveConnectClient class has these types of members:

  • Constructors
  • Methods
  • Properties

Constructors

The LiveConnectClient class has these constructors.

Constructor | Description
LiveConnectClient(LiveConnectSession) constructor | Initializes a new instance of the LiveConnectClient class.

Methods

The LiveConnectClient class has these methods. It also inherits methods from the Object class.

Method | Description
BackgroundDownloadAsync(String) method | Performs a download of a file with a given path.
BackgroundDownloadAsync(String, CancellationToken, IProgress<LiveOperationProgress>) method | Performs a download of a file with a given path, cancellation token, and LiveOperationProgress.
BackgroundDownloadAsync(String, IStorageFile) method | Performs a download of a file with a given path and output file to hold the downloaded file contents.
BackgroundDownloadAsync(String, IStorageFile, CancellationToken, IProgress<LiveOperationProgress>) method | Performs a download of a file with a given path, cancellation token, LiveOperationProgress, and output file to hold the downloaded file contents.
BackgroundUploadAsync(String, String, IInputStream, OverwriteOption) method | Uploads a resource with a given path, file name, stream contents, and the option to overwrite an existing file.
BackgroundUploadAsync(String, String, IInputStream, OverwriteOption, CancellationToken, IProgress<LiveOperationProgress>) method | Uploads a resource with a given path, file name, stream contents, cancellation token, LiveOperationProgress, and the option to overwrite an existing file.
BackgroundUploadAsync(String, String, IStorageFile, OverwriteOption) method | Uploads a resource with a given path, file name, file contents, and the option to overwrite an existing file.
BackgroundUploadAsync(String, String, IStorageFile, OverwriteOption, CancellationToken, IProgress<LiveOperationProgress>) method | Uploads a resource with a given path, file name, file contents, cancellation token, LiveOperationProgress, and the option to overwrite an existing file.
CopyAsync(String, String) method | Performs a copy of a file with the given path and destination.
CopyAsync(String, String, CancellationToken) method | Performs a copy of a file with the given path, destination, and cancellation token.
DeleteAsync(String) method | Performs a delete of a file with the given path.
DeleteAsync(String, CancellationToken) method | Performs a delete of a file with the given path and cancellation token.
GetAsync(String) method | Performs a get of a file with a given path.
GetAsync(String, CancellationToken) method | Performs a get of a file with a given path and cancellation token.
MoveAsync(String, String) method | Performs a move of a resource for a given path and destination.
MoveAsync(String, String, CancellationToken) method | Performs a move of a resource for a given path, destination, and cancellation token.
PostAsync(String, IDictionary<String, Object>) method | Performs a post for a given path and message request body.
PostAsync(String, IDictionary<String, Object>, CancellationToken) method | Performs a post for a given path, message request body, and cancellation token.
PostAsync(String, String) method | Performs a post for a given path and message request body.
PostAsync(String, String, CancellationToken) method | Performs a post for a given path, message request body, and cancellation token.
PutAsync(String, IDictionary<String, Object>) method | Performs a put that updates a resource with a given path and message body.
PutAsync(String, IDictionary<String, Object>, CancellationToken) method | Performs a put that updates a resource with a given path, message body, and cancellation token.
PutAsync(String, String) method | Performs a put that updates a resource with a given path and message body.
PutAsync(String, String, CancellationToken) method | Performs a put that updates a resource with a given path, message body, and cancellation token.

Properties

The LiveConnectClient class has these properties.

Property | Access type | Description
Session property | Read-only | Contains the current session data used by the LiveConnectClient class.

Requirements

Minimum supported client

 Windows 8

Minimum supported server

 None supported

Namespace

Microsoft.Live

Assembly
Microsoft.Live.dll


LiveConnectClient.BackgroundDownloadAsync methods

Downloads a file and writes the file content to a stream provided by the app.

This member is overloaded. For complete information about this member, including syntax, usage, and examples, click a name in the overload list.

Overload list

Method | Description
BackgroundDownloadAsync(String, IStorageFile, CancellationToken, IProgress<LiveOperationProgress>) method | Performs a download of a file with a given path, cancellation token, LiveOperationProgress, and output file to hold the downloaded file contents.
BackgroundDownloadAsync(String) method | Performs a download of a file with a given path.
BackgroundDownloadAsync(String, IStorageFile) method | Performs a download of a file with a given path and output file to hold the downloaded file contents.
BackgroundDownloadAsync(String, CancellationToken, IProgress<LiveOperationProgress>) method | Performs a download of a file with a given path, cancellation token, and LiveOperationProgress.

Requirements

Minimum supported client

 Windows 8

Minimum supported server

 None supported

Namespace

Microsoft.Live

Assembly
Microsoft.Live.dll

See also

LiveConnectClient


LiveConnectClient.BackgroundDownloadAsync(String) method

Performs a download of a file with a given path.

Syntax

C#
public Task<LiveDownloadOperationResult> BackgroundDownloadAsync(
  string path
)

Parameters

path

Type: String

The relative path to the item to download.

Return value

Type: Task<LiveDownloadOperationResult>

The LiveDownloadOperationResult that contains the file contents.

Error codes

Name Meaning
ArgumentNullException

A parameter that was passed in is null.

Error codes

Name Meaning
ArgumentNullException

A parameter that was passed in is null.

Remarks

This is a helper function that makes calls to the Live Connect Representational State Transfer (REST) API. It supports all paths in the REST API.

BackgroundDownloadAsync automatically uses the access token returned from user sign-in by the constructor, making it possible for a site to omit working directly with access tokens. If the access token cookie is set, BackgroundDownloadAsync uses that as well.

Requirements

Minimum supported client

 Windows 8

Minimum supported server

 None supported

Namespace

Microsoft.Live

Assembly
Microsoft.Live.dll

See also

LiveConnectClient


LiveConnectClient.BackgroundDownloadAsync(String, CancellationToken, IProgress<LiveOperationProgress>) method

Performs a download of a file with a given path, cancellation token, and LiveOperationProgress.

Syntax

C#
public Task<LiveDownloadOperationResult> BackgroundDownloadAsync(
  string path,
  CancellationToken ct,
  IProgress<LiveOperationProgress> progress
)

Parameters

path

Type: String

The relative path to the item to download.

ct

Type: CancellationToken

The cancellation token used to provide notification that operations should be cancelled.

progress

Type: IProgress<LiveOperationProgress>

The progress handler that the calling app uses to receive progress updates.

Return value

Type: Task<LiveDownloadOperationResult>

The LiveDownloadOperationResult that contains the file contents.

Error codes

Name Meaning
ArgumentNullException

A parameter that was passed in is null.

Error codes

Name Meaning
ArgumentNullException

A parameter that was passed in is null.

Remarks

This is a helper function that makes calls to the Live Connect Representational State Transfer (REST) API. It supports all paths in the REST API.

BackgroundDownloadAsync automatically uses the access token returned from user sign-in by the constructor, making it possible for a site to omit working directly with access tokens. If the access token cookie is set, BackgroundDownloadAsync uses that as well.

Requirements

Minimum supported client

 Windows 8

Minimum supported server

 None supported

Namespace

Microsoft.Live

Assembly
Microsoft.Live.dll

See also

LiveConnectClient


LiveConnectClient.BackgroundDownloadAsync(String, IStorageFile) method

Performs a download of a file with a given path and output file to hold the downloaded file contents.

Syntax

C#
public Task<LiveDownloadOperationResult> BackgroundDownloadAsync(
  string path,
  IStorageFile outputFile
)

Parameters

path

Type: String

The relative path to the item to download.

outputFile

Type: IStorageFile

The file object to which the downloaded content is written.

Return value

Type: Task<LiveDownloadOperationResult>

The LiveDownloadOperationResult.

Error codes

Name Meaning
ArgumentNullException

A parameter that was passed in is null.

Error codes

Name Meaning
ArgumentNullException

A parameter that was passed in is null.

Remarks

This is a helper function that makes calls to the Live Connect Representational State Transfer (REST) API. It supports all paths in the REST API.

BackgroundDownloadAsync automatically uses the access token returned from user sign-in by the constructor, making it possible for a site to omit working directly with access tokens. If the access token cookie is set, BackgroundDownloadAsync uses that as well.

Requirements

Minimum supported client

 Windows 8

Minimum supported server

 None supported

Namespace

Microsoft.Live

Assembly
Microsoft.Live.dll

See also

LiveConnectClient


LiveConnectClient.BackgroundDownloadAsync(String, IStorageFile, CancellationToken, IProgress<LiveOperationProgress>) method

Performs a download of a file with a given path, cancellation token, LiveOperationProgress, and output file to hold the downloaded file contents.

Syntax

C#
public Task<LiveDownloadOperationResult> BackgroundDownloadAsync(
  string path,
  IStorageFile outputFile,
  CancellationToken ct,
  IProgress<LiveOperationProgress> progress
)

Parameters

path

Type: String

The relative path to the item to download.

outputFile

Type: IStorageFile

The file object to which the downloaded content is written.

ct

Type: CancellationToken

The cancellation token that is used to provide notification that operations should be cancelled.

progress

Type: IProgress<LiveOperationProgress>

The progress handler that the calling app uses to receive progress updates.

Return value

Type: Task<LiveDownloadOperationResult>

The LiveDownloadOperationResult.

Error codes

Name Meaning
ArgumentNullException

A parameter that was passed in is null.

Error codes

Name Meaning
ArgumentNullException

A parameter that was passed in is null.

Remarks

This is a helper function that makes calls to the Live Connect Representational State Transfer (REST) API. It supports all paths in the REST API.

BackgroundDownloadAsync automatically uses the access token returned from user sign-in by the constructor, making it possible for a site to omit working directly with access tokens. If the access token cookie is set, BackgroundDownloadAsync uses that as well.

Requirements

Minimum supported client

 Windows 8

Minimum supported server

 None supported

Namespace

Microsoft.Live

Assembly
Microsoft.Live.dll

See also

LiveConnectClient


LiveConnectClient.BackgroundUploadAsync methods

Uploads resources to a user's Microsoft SkyDrive account.

This member is overloaded. For complete information about this member, including syntax, usage, and examples, click a name in the overload list.

Overload list

Method | Description
BackgroundUploadAsync(String, String, Stream, OverwriteOption, CancellationToken, IProgress<LiveOperationProgress>) method | Uploads a resource with a given path, file name, stream contents, cancellation token, LiveOperationProgress, and the option to overwrite an existing file.
BackgroundUploadAsync(String, String, IStorageFile, OverwriteOption, CancellationToken, IProgress<LiveOperationProgress>) method | Uploads a resource with a given path, file name, file contents, cancellation token, LiveOperationProgress, and the option to overwrite an existing file.
BackgroundUploadAsync(String, String, Stream, OverwriteOption) method | Uploads a resource with a given path, file name, stream contents, and the option to overwrite an existing file.
BackgroundUploadAsync(String, String, IStorageFile, OverwriteOption) method | Uploads a resource with a given path, file name, file contents, and the option to overwrite an existing file.

Requirements

Minimum supported client

 Windows 8

Minimum supported server

 None supported

Namespace

Microsoft.Live

Assembly
Microsoft.Live.dll

See also

LiveConnectClient


LiveConnectClient.BackgroundUploadAsync(String, String, IStorageFile, OverwriteOption) method

Uploads a resource with a given path, file name, file contents, and the option to overwrite an existing file.

Syntax

C#
public Task<LiveOperationResult> BackgroundUploadAsync(
  string path,
  string fileName,
  IStorageFile inputFile,
  OverwriteOption option
)

Parameters

path

Type: String

The destination path for the upload.

fileName

Type: String

The name of the file to upload.

inputFile

Type: IStorageFile

The file to add to the body of the API call.

option

Type: OverwriteOption

Specifies whether the file that's being uploaded to SkyDrive should overwrite an existing file with the same file name in that location.

Return value

Type: Task<LiveOperationResult>

The LiveOperationResult object with the populated session and result.

Error codes

Name Meaning
ArgumentNullException

A parameter that was passed in is null.

Error codes

Name Meaning
ArgumentNullException

A parameter that was passed in is null.

Remarks

This method uses an HTTP PUT call to the Live Connect Representational State Transfer (REST) API and returns the response as an IStorageFile.

BackgroundUploadAsync automatically uses the access token returned from user sign-in by the constructor, making it possible for a site to omit working directly with access tokens. If the access token cookie is set, BackgroundUploadAsync uses that as well.

Requirements

Minimum supported client

 Windows 8

Minimum supported server

 None supported

Namespace

Microsoft.Live

Assembly
Microsoft.Live.dll

See also

LiveConnectClient


LiveConnectClient.BackgroundUploadAsync(String, String, IStorageFile, OverwriteOption, CancellationToken, IProgress<LiveOperationProgress>) method

Uploads a resource with a given path, file name, file contents, cancellation token, LiveOperationProgress, and the option to overwrite an existing file.

Syntax

C#
public Task<LiveOperationResult> BackgroundUploadAsync(
  string path,
  string fileName,
  IStorageFile inputFile,
  OverwriteOption option,
  CancellationToken ct,
  IProgress<LiveOperationProgress>  progress
)

Parameters

path

Type: String

The destination path for the upload.

fileName

Type: String

The name of the file to upload.

inputFile

Type: IStorageFile

The file to add to the body of the API call.

option

Type: OverwriteOption

Specifies whether the file that's being uploaded to SkyDrive should overwrite an existing file with the same file name in that location.

ct

Type: CancellationToken

The cancellation token that is used to provide notification that operations should be cancelled.

progress

Type: IProgress<LiveOperationProgress>

The progress handler that the calling app uses to receive progress updates.

Return value

Type: Task<LiveOperationResult>

The LiveOperationResult object with the populated session and result.

Error codes

Name Meaning
ArgumentNullException

A parameter that was passed in is null.

Error codes

Name Meaning
ArgumentNullException

A parameter that was passed in is null.

Remarks

This method uses an HTTP PUT call to the Live Connect Representational State Transfer (REST) API and returns the response as an IStorageFile.

BackgroundUploadAsync automatically uses the access token returned from user sign-in by the constructor, making it possible for a site to omit working directly with access tokens. If the access token cookie is set, BackgroundUploadAsync uses that as well.

Requirements

Minimum supported client

 Windows 8

Minimum supported server

 None supported

Namespace

Microsoft.Live

Assembly
Microsoft.Live.dll

See also

LiveConnectClient


LiveConnectClient.BackgroundUploadAsync(String, String, IInputStream, OverwriteOption) method

Uploads a resource with a given path, file name, stream contents, and the option to overwrite an existing file.

Syntax

C#
public Task<LiveOperationResult> BackgroundUploadAsync(
  string path,
  string fileName,
  IInputStream inputStream,
  OverwriteOption option
)

Parameters

path

Type: String

The destination path for the upload.

fileName

Type: String

The name of the file to be uploaded.

inputStream

Type: IInputStream

The stream to add to the body of the API request.

option

Type: OverwriteOption

Specifies whether the file that's being uploaded to SkyDrive should overwrite an existing file with the same file name in that location.

Return value

Type: Task<LiveOperationResult>

The LiveOperationResult object with the populated session and result.

Error codes

Name Meaning
ArgumentNullException

A parameter that was passed in is null.

Error codes

Name Meaning
ArgumentNullException

A parameter that was passed in is null.

Remarks

This method uses an HTTP PUT call to the Live Connect Representational State Transfer (REST) API and returns the response as an Stream.

BackgroundUploadAsync automatically uses the access token returned from user sign-in by the constructor, making it possible for a site to omit working directly with access tokens. If the access token cookie is set, BackgroundUploadAsync uses that as well.

Requirements

Minimum supported client

 Windows 8

Minimum supported server

 None supported

Namespace

Microsoft.Live

Assembly
Microsoft.Live.dll

See also

LiveConnectClient


LiveConnectClient.BackgroundUploadAsync(String, String, IInputStream, OverwriteOption, CancellationToken, IProgress<LiveOperationProgress>) method

Uploads a resource with a given path, file name, stream contents, cancellation token, LiveOperationProgress, and the option to overwrite an existing file.

Syntax

C#
public Task<LiveOperationResult> BackgroundUploadAsync(
  string path,
  string fileName,
  IInputStream inputStream,
  OverwriteOption option,
  CancellationToken ct,
  IProgress<LiveOperationProgress>  progress
)

Parameters

path

Type: String

The destination path for the upload.

fileName

Type: String

The name of the file to be uploaded.

inputStream

Type: IInputStream

The stream to add to the body of the API request.

option

Type: OverwriteOption

Specifies whether the file that's being uploaded to SkyDrive should overwrite an existing file with the same file name in that location.

ct

Type: CancellationToken

The cancellation token that is used to provide notification that operations should be cancelled.

progress

Type: IProgress<LiveOperationProgress>

The progress handler that the calling app uses to receive progress updates.

Return value

Type: Task<LiveOperationResult>

The LiveOperationResult object with the populated session and result.

Error codes

Name Meaning
ArgumentNullException

A parameter that was passed in is null.

Error codes

Name Meaning
ArgumentNullException

A parameter that was passed in is null.

Remarks

This method uses an HTTP PUT call to the Live Connect Representational State Transfer (REST) API and returns the response as an Stream.

BackgroundUploadAsync automatically uses the access token returned from user sign-in by the constructor, making it possible for a site to omit working directly with access tokens. If the access token cookie is set, BackgroundUploadAsync uses that as well.

Requirements

Minimum supported client

 Windows 8

Minimum supported server

 None supported

Namespace

Microsoft.Live

Assembly
Microsoft.Live.dll

See also

LiveConnectClient


LiveConnectClient.CopyAsync methods

Performs a copy of a file.

This member is overloaded. For complete information about this member, including syntax, usage, and examples, click a name in the overload list.

Overload list

Method | Description
CopyAsync(String, String) method | Performs a copy of a file with the given path and destination.
CopyAsync(String, String, CancellationToken) method | Performs a copy of a file with the given path, destination, and cancellation token.

Requirements

Minimum supported client

 Windows 8

Minimum supported server

 None supported

Namespace

Microsoft.Live

Assembly
Microsoft.Live.dll

See also

LiveConnectClient


LiveConnectClient.Copy(String, String) method

Performs a copy of a file with the given path and destination.

Syntax

C#
public Task<LiveOperationResult> Copy(
  string path,
  string destination
)

Parameters

path

Type: String

The resource ID of the file to copy.

destination

Type: String

The destination path to which the item is copied.

Return value

Type: Task<LiveOperationResult>

The data returned by the API service for the copy operation.

Error codes

Name Meaning
ArgumentNullException

A parameter that was passed in is null.

Error codes

Name Meaning
ArgumentNullException

A parameter that was passed in is null.

Remarks

This is a helper function that makes calls using HTTP COPY to the Live Connect Representational State Transfer (REST) API. It supports all paths and methods in the REST API for read and write.

Copy automatically uses the access token returned from user sign-in by the constructor, making it possible for a site to omit working directly with access tokens. If the access token cookie is set, Copy uses that as well.

Requirements

Minimum supported client

 Windows 8

Minimum supported server

 None supported

Namespace

Microsoft.Live

Assembly
Microsoft.Live.dll

See also

LiveConnectClient
Copy(String, String, CancellationToken)


LiveConnectClient.CopyAsync(String, String, CancellationToken) method

Performs a copy of a file with the given path, destination, and cancellation token.

Syntax

C#
public Task<LiveOperationResult> CopyAsync(
  string path,
  string destination,
  CancellationToken ct
)

Parameters

path

Type: String

The resource ID of the file to copy.

destination

Type: String

The destination path to which the item is copied.

ct

Type: CancellationToken

The cancellation token that is used to provide notification that operations should be cancelled.

Return value

Type: Task<LiveOperationResult>

The data returned by the API service for the copy operation.

Remarks

This is a helper function that makes calls using HTTP COPY to the Live Connect Representational State Transfer (REST) API. It supports all paths in the REST API.

Copy automatically uses the access token returned from user sign-in by the constructor, making it possible for a site to omit working directly with access tokens. If the access token cookie is set, Copy uses that as well.

Requirements

Minimum supported client

 Windows 8

Minimum supported server

 None supported

Namespace

Microsoft.Live

Assembly
Microsoft.Live.dll

See also

LiveConnectClient
Copy(String, String)


LiveConnectClient.DeleteAsync methods

Performs a delete of a file.

Overload list

Method | Description
DeleteAsync(String) method | Performs a delete of a file with the given path.
DeleteAsync(String, CancellationToken) method | Performs a delete of a file with the given path and cancellation token.

Remarks

This member is overloaded. For complete information about this member, including syntax, usage, and examples, click a name in the overload list.

Requirements

Minimum supported client

 Windows 8

Minimum supported server

 None supported

Namespace

Microsoft.Live

Assembly
Microsoft.Live.dll

See also

LiveConnectClient


LiveConnectClient.DeleteAsync(String) method

Performs a delete of a file with the given path.

Syntax

C#
public Task<LiveOperationResult> DeleteAsync(
  string path
)

Parameters

path

Type: String

The relative URL to the resource to delete.

Return value

Type: Task<LiveOperationResult>

The LiveOperationResult object with the populated session and result.

Error codes

Name Meaning
ArgumentNullException

A parameter that was passed in is null.

Error codes

Name Meaning
ArgumentNullException

A parameter that was passed in is null.

Remarks

This is a helper function that makes calls using HTTP DELETE to the Live Connect Representational State Transfer (REST) API. It supports all paths in the REST API.

Delete automatically uses the access token returned from user sign-in by the constructor, making it possible for a site to omit working directly with access tokens. If the access token cookie is set, DeleteAsync uses that as well.

Requirements

Minimum supported client

 Windows 8

Minimum supported server

 None supported

Namespace

Microsoft.Live

Assembly
Microsoft.Live.dll

See also

LiveConnectClient


LiveConnectClient.DeleteAsync(String, CancellationToken) method

Performs a delete of a file with the given path and cancellation token.

Syntax

C#
public Task<LiveOperationResult> DeleteAsync(
  string path,
  CancellationToken ct
)

Parameters

path

Type: String

The relative URL to the resource to delete.

ct

Type: CancellationToken

The cancellation token used to provide notification that operations should be cancelled.

Return value

Type: Task<LiveOperationResult>

The LiveOperationResult object with the populated session and result.

Error codes

Name Meaning
ArgumentNullException

A parameter that was passed in is null.

Error codes

Name Meaning
ArgumentNullException

A parameter that was passed in is null.

Remarks

This is a helper function that makes calls using HTTP DELETE to the Live Connect Representational State Transfer (REST) API. It supports all paths in the REST API.

DeleteAsync automatically uses the access token returned from user sign-in by the constructor, making it possible for a site to omit working directly with access tokens. If the access token cookie is set, DeleteAsync uses that as well.

Requirements

Minimum supported client

 Windows 8

Minimum supported server

 None supported

Namespace

Microsoft.Live

Assembly
Microsoft.Live.dll

See also

LiveConnectClient
DeleteAsync


LiveConnectClient.GetAsync methods

Performs a get of a file with a given path.

This member is overloaded. For complete information about this member, including syntax, usage, and examples, click a name in the overload list.

Overload list

Method | Description
GetAsync(String) method | Performs a get of a file with a given path.
GetAsync(String, CancellationToken) method | Performs a get of a file with a given path and cancellation token.

Requirements

Minimum supported client

 Windows 8

Minimum supported server

 None supported

Namespace

Microsoft.Live

Assembly
Microsoft.Live.dll

See also

LiveConnectClient


LiveConnectClient.GetAsync(String) method

Performs a get of a file with a given path.

Syntax

C#
public Task<LiveOperationResult> GetAsync(
  string path
)

Parameters

path

Type: String

The relative path to the item to retrieve.

Return value

Type: Task<LiveOperationResult>

The data returned by the API service for the get operation.

Remarks

This is a helper function that makes calls using HTTP GET to the Live Connect Representational State Transfer (REST) API. It supports all paths in the REST API.

GetAsync automatically uses the access token returned from user sign-in by the constructor, making it possible for a site to omit working directly with access tokens. If the access token cookie is set, GetAsync uses that as well.

Requirements

Minimum supported client

 Windows 8

Minimum supported server

 None supported

Namespace

Microsoft.Live

Assembly
Microsoft.Live.dll

See also

LiveConnectClient


LiveConnectClient.GetAsync(String, CancellationToken) method

Performs a get of a file with a given path and cancellation token.

Syntax

C#
public Task<LiveOperationResult> GetAsync(
  string path,
  CancellationToken ct
)

Parameters

path

Type: String

The relative path to the item to retrieve.

ct

Type: CancellationToken

The cancellation token that is used to provide notification that operations should be cancelled.

Return value

Type: Task<LiveOperationResult>

The data returned by the API service for the get operation.

Remarks

This is a helper function that makes calls using HTTP GET to the Live Connect Representational State Transfer (REST) API. It supports all paths in the REST API.

GetAsync automatically uses the access token returned from user sign-in by the constructor, making it possible for a site to omit working directly with access tokens. If the access token cookie is set, GetAsync uses that as well.

Requirements

Minimum supported client

 Windows 8

Minimum supported server

 None supported

Namespace

Microsoft.Live

Assembly
Microsoft.Live.dll

See also

LiveConnectClient


LiveConnectClient.LiveConnectClient(LiveConnectSession) constructor

Initializes a new instance of the LiveConnectClient class.

Syntax

C#
public LiveConnectClient LiveConnectClient(
  LiveConnectSession session
)

Parameters

session

Type: LiveConnectSession

The LiveConnectSession that contains all the access information for the service.

Return value

Type: LiveConnectClient

An initialized instance of the class.

Requirements

Minimum supported client

 Windows 8

Minimum supported server

 None supported

Namespace

Microsoft.Live

Assembly
Microsoft.Live.dll

See also

LiveConnectClient


LiveConnectClient.MoveAsync methods

Performs a move of a resource for a given path and destination.

This member is overloaded. For complete information about this member, including syntax, usage, and examples, click a name in the overload list.

Overload list

Method | Description
MoveAsync(String, String) method | Performs a move of a resource for a given path and destination.
MoveAsync(String, String, CancellationToken) method | Performs a move of a resource for a given path, destination, and cancellation token.

Requirements

Minimum supported client

 Windows 8

Minimum supported server

 None supported

Namespace

Microsoft.Live

Assembly
Microsoft.Live.dll

See also

LiveConnectClient


LiveConnectClient.MoveAsync(String, String) method

Performs a move of a resource for a given path and destination.

Syntax

C#
public Task<LiveOperationResult> MoveAsync(
  string path,
  string destination
)

Parameters

path

Type: String

The relative path to the item to move.

destination

Type: String

The path to which to move the resource.

Return value

Type: Task<LiveOperationResult>

The data returned by the API service for the move operation.

Error codes

Name Meaning
ArgumentNullException

A parameter that was passed in is null.

Error codes

Name Meaning
ArgumentNullException

A parameter that was passed in is null.

Remarks

This is a helper function that makes an HTTP MOVE call to the Live Connect Representational State Transfer (REST) API.

MoveAsync automatically uses the access token returned from user sign-in by the constructor, making it possible for a site to omit working directly with access tokens. If the access token cookie is set, MoveAsync uses that as well.

Requirements

Minimum supported client

 Windows 8

Minimum supported server

 None supported

Namespace

Microsoft.Live

Assembly
Microsoft.Live.dll

See also

LiveConnectClient


LiveConnectClient.MoveAsync(String, String, CancellationToken) method

Performs a move of a resource for a given path, destination, and cancellation token.

Syntax

C#
public Task<LiveOperationResult> MoveAsync(
  string path,
  string destination,
  CancellationToken ct
)

Parameters

path

Type: String

The relative path to the item to move.

destination

Type: String

The path to which to move the resource.

ct

Type: CancellationToken

The cancellation token that is used to provide notification that operations should be cancelled.

Return value

Type: Task<LiveOperationResult>

The data returned by the API service for the move operation.

Error codes

Name Meaning
ArgumentNullException

A parameter that was passed in is null.

Error codes

Name Meaning
ArgumentNullException

A parameter that was passed in is null.

Remarks

This is a helper function that makes an HTTP MOVE call to the Live Connect Representational State Transfer (REST) API.

MoveAsync automatically uses the access token returned from user sign-in by the constructor, making it possible for a site to omit working directly with access tokens. If the access token cookie is set, MoveAsync uses that as well.

Requirements

Minimum supported client

 Windows 8

Minimum supported server

 None supported

Namespace

Microsoft.Live

Assembly
Microsoft.Live.dll

See also

LiveConnectClient


LiveConnectClient.PostAsync methods

Performs a post of a resource. The post adds a new resource to a collection.

This member is overloaded. For complete information about this member, including syntax, usage, and examples, click a name in the overload list.

Overload list

Method | Description
PostAsync(String, String) method | Performs a post for a given path and message request body.
PostAsync(String, String, CancellationToken) method | Performs a post for a given path, message request body, and cancellation token.
PostAsync(String, IDictionary<String, Object>) method | Performs a post for a given path and message request body.
PostAsync(String, IDictionary<String, Object>, CancellationToken) method | Performs a post for a given path, message request body, and cancellation token.

Requirements

Minimum supported client

 Windows 8

Minimum supported server

 None supported

Namespace

Microsoft.Live

Assembly
Microsoft.Live.dll

See also

LiveConnectClient


LiveConnectClient.PostAsync(String, IDictionary<String ,Object>) method

Performs a post for a given path and message request body. The post adds a new resource to a collection.

Syntax

C#
public Task<LiveOperationResult> PostAsync(
  string path,
  IDictionary<String ,Object> body
)

Parameters

path

Type: String

The path to the resource collection where the object is to post.

body

Type: IDictionary<String ,Object>

The message body to include in the API call.

Return value

Type: Task<LiveOperationResult>

The LiveOperationResult object with the populated session and result.

Error codes

Name Meaning
ArgumentNullException

A parameter that was passed in is null.

Error codes

Name Meaning
ArgumentNullException

A parameter that was passed in is null.

Remarks

This is a helper function that makes an HTTP POST call to the Live Connect Representational State Transfer (REST) API.

PostAsync automatically uses the access token returned from user sign-in by the constructor, making it possible for a site to omit working directly with access tokens. If the access token cookie is set, PostAsync uses that as well.

Requirements

Minimum supported client

 Windows 8

Minimum supported server

 None supported

Namespace

Microsoft.Live

Assembly
Microsoft.Live.dll

See also

LiveConnectClient


LiveConnectClient.PostAsync(String, IDictionary<String ,Object>, CancellationToken) method

Performs a post for a given path, message request body, and cancellation token. The post adds a new resource to a collection.

Syntax

C#
public Task<LiveOperationResult> PostAsync(
  string path,
  IDictionary<String ,Object> body,
  CancellationToken ct
)

Parameters

path

Type: String

The path to the resource collection where the object is to post.

body

Type: IDictionary<String ,Object>

The message body to include in the API call.

ct

Type: CancellationToken

The cancellation token that is used to provide notification that operations should be cancelled.

Return value

Type: Task<LiveOperationResult>

The LiveOperationResult object with the populated session and result.

Error codes

Name Meaning
ArgumentNullException

A parameter that was passed in is null.

Error codes

Name Meaning
ArgumentNullException

A parameter that was passed in is null.

Remarks

This is a helper function that makes an HTTP POST call to the Live Connect Representational State Transfer (REST) API.

PostAsync automatically uses the access token returned from user sign-in by the constructor, making it possible for a site to omit working directly with access tokens. If the access token cookie is set, PostAsync uses that as well.

Requirements

Minimum supported client

 Windows 8

Minimum supported server

 None supported

Namespace

Microsoft.Live

Assembly
Microsoft.Live.dll

See also

LiveConnectClient


LiveConnectClient.PostAsync(String, String) method

Performs a post for a given path and message request body. The post adds a new resource to a collection.

Syntax

C#
public Task<LiveOperationResult> PostAsync(
  string path,
  string body
)

Parameters

path

Type: String

The path to the resource collection where the object is to post.

body

Type: String

The message body to include in the API call.

Return value

Type: Task<LiveOperationResult>

The LiveOperationResult object with the populated session and result.

Error codes

Name Meaning
ArgumentNullException

A parameter that was passed in is null.

Error codes

Name Meaning
ArgumentNullException

A parameter that was passed in is null.

Remarks

This is a helper function that makes an HTTP POST call to the Live Connect Representational State Transfer (REST) API.

PostAsync automatically uses the access token returned from user sign-in by the constructor, making it possible for a site to omit working directly with access tokens. If the access token cookie is set, PostAsync uses that as well.

Requirements

Minimum supported client

 Windows 8

Minimum supported server

 None supported

Namespace

Microsoft.Live

Assembly
Microsoft.Live.dll

See also

LiveConnectClient


LiveConnectClient.PostAsync(String, String, CancellationToken) method

Performs a post for a given path, message request body, and cancellation token. The post adds a new resource to a collection.

Syntax

C#
public Task<LiveOperationResult> PostAsync(
  string path,
  string body,
  CancellationToken ct
)

Parameters

path

Type: String

The path to the resource collection where the object is to post.

body

Type: String

The message body to include in the API call.

ct

Type: CancellationToken

The cancellation token that is used to provide notification that operations should be cancelled.

Return value

Type: Task<LiveOperationResult>

The LiveOperationResult object with the populated session and result.

Error codes

Name Meaning
ArgumentNullException

A parameter that was passed in is null.

Error codes

Name Meaning
ArgumentNullException

A parameter that was passed in is null.

Remarks

This is a helper function that makes an HTTP POST call to the Live Connect Representational State Transfer (REST) API.

PostAsync automatically uses the access token returned from user sign-in by the constructor, making it possible for a site to omit working directly with access tokens. If the access token cookie is set, PostAsync uses that as well.

Requirements

Minimum supported client

 Windows 8

Minimum supported server

 None supported

Namespace

Microsoft.Live

Assembly
Microsoft.Live.dll

See also

LiveConnectClient


LiveConnectClient.PutAsync methods

Performs a put that updates a resource.

This member is overloaded. For complete information about this member, including syntax, usage, and examples, click a name in the overload list.

Overload list

Method | Description
PutAsync(String, String) method | Performs a put that updates a resource with a given path and message body.
PutAsync(String, String, CancellationToken) method | Performs a put that updates a resource with a given path, message body, and cancellation token.
PutAsync(String, IDictionary<String, Object>) method | Performs a put that updates a resource with a given path and message body.
PutAsync(String, IDictionary<String, Object>, CancellationToken) method | Performs a put that updates a resource with a given path, message body, and cancellation token.

Requirements

Minimum supported client

 Windows 8

Minimum supported server

 None supported

Namespace

Microsoft.Live

Assembly
Microsoft.Live.dll

See also

LiveConnectClient


LiveConnectClient.PutAsync(String, IDictionary<String ,Object>) method

Performs a put that updates a resource with a given path and message body.

Syntax

C#
public Task<LiveOperationResult> PutAsync(
  string path,
  IDictionary<String ,Object> body
)

Parameters

path

Type: String

The relative path to the resource to update.

body

Type: IDictionary<String ,Object>

The message body to include in the API call.

Return value

Type: Task<LiveOperationResult>

The data returned by the API service for the put operation.

Error codes

Name Meaning
ArgumentNullException

A parameter that was passed in is null.

Error codes

Name Meaning
ArgumentNullException

A parameter that was passed in is null.

Remarks

This is a helper function that makes an HTTP PUT call to the Live Connect Representational State Transfer (REST) API.

PutAsync automatically uses the access token returned from user sign-in by the constructor, making it possible for a site to omit working directly with access tokens. If the access token cookie is set, PutAsync uses that as well.

Requirements

Minimum supported client

 Windows 8

Minimum supported server

 None supported

Namespace

Microsoft.Live

Assembly
Microsoft.Live.dll

See also

LiveConnectClient


LiveConnectClient.PutAsync(String, IDictionary<String ,Object>, CancellationToken) method

Performs a put that updates a resource with a given path, message body, and cancellation token.

Syntax

C#
public Task<LiveOperationResult> PutAsync(
  string path,
  IDictionary<String ,Object> body,
  CancellationToken ct
)

Parameters

path

Type: String

The relative path to the resource to update.

body

Type: IDictionary<String ,Object>

The message body to include in the API call.

ct

Type: CancellationToken

The cancellation token that is used to provide notification that operations should be cancelled.

Return value

Type: Task<LiveOperationResult>

The data returned by the API service for the put operation.

Error codes

Name Meaning
ArgumentNullException

A parameter that was passed in is null.

Error codes

Name Meaning
ArgumentNullException

A parameter that was passed in is null.

Remarks

This is a helper function that makes an HTTP PUT call to the Live Connect Representational State Transfer (REST) API.

PutAsync automatically uses the access token returned from user sign-in by the constructor, making it possible for a site to omit working directly with access tokens. If the access token cookie is set, PutAsync uses that as well.

Requirements

Minimum supported client

 Windows 8

Minimum supported server

 None supported

Namespace

Microsoft.Live

Assembly
Microsoft.Live.dll

See also

LiveConnectClient


LiveConnectClient.PutAsync(String, String) method

Performs a put that updates a resource with a given path and message body.

Syntax

C#
public Task<LiveOperationResult> PutAsync(
  string path,
  string body
)

Parameters

path

Type: String

The relative path to the resource to update.

body

Type: String

The message body to include in the API call.

Return value

Type: Task<LiveOperationResult>

The data returned by the API service for the put operation.

Error codes

Name Meaning
ArgumentNullException

A parameter that was passed in is null.

Error codes

Name Meaning
ArgumentNullException

A parameter that was passed in is null.

Remarks

This is a helper function that makes an HTTP PUT call to the Live Connect Representational State Transfer (REST) API.

PutAsync automatically uses the access token returned from user sign-in by the constructor, making it possible for a site to omit working directly with access tokens. If the access token cookie is set, PutAsync uses that as well.

Requirements

Minimum supported client

 Windows 8

Minimum supported server

 None supported

Namespace

Microsoft.Live

Assembly
Microsoft.Live.dll

See also

LiveConnectClient


LiveConnectClient.PutAsync(String, String, CancellationToken) method

Performs a put that updates a resource with a given path, message body, and cancellation token.

Syntax

C#
public Task<LiveOperationResult> PutAsync(
  string path,
  string body,
  CancellationToken ct
)

Parameters

path

Type: String

The relative path to the resource to update.

body

Type: String

The message body to include in the API call.

ct

Type: CancellationToken

The cancellation token that is used to provide notification that operations should be cancelled.

Return value

Type: Task<LiveOperationResult>

The data returned by the API service for the put operation.

Error codes

Name Meaning
ArgumentNullException

A parameter that was passed in is null.

Error codes

Name Meaning
ArgumentNullException

A parameter that was passed in is null.

Remarks

This is a helper function that makes an HTTP PUT call to the Live Connect Representational State Transfer (REST) API.

PutAsync automatically uses the access token returned from user sign-in by the constructor, making it possible for a site to omit working directly with access tokens. If the access token cookie is set, PutAsync uses that as well.

Requirements

Minimum supported client

 Windows 8

Minimum supported server

 None supported

Namespace

Microsoft.Live

Assembly
Microsoft.Live.dll

See also

LiveConnectClient


LiveConnectClient.Session property

Contains the current session data used by the LiveConnectClient class.

Syntax

C#
public LiveConnectSession Session { get; }

Property value

Type: LiveConnectSession

Session

Requirements

Minimum supported client

 Windows 8

Minimum supported server

 None supported

Namespace

Microsoft.Live

Assembly
Microsoft.Live.dll

See also

LiveConnectClient


LiveConnectClient class

Exposes the primary functionality of the Live Connect web service endpoints, and manages token expiry.

Syntax

C#
public class LiveConnectClient

Attributes

None

Members

The LiveConnectClient class has these types of members:

  • Constructors
  • Events
  • Methods
  • Properties

Constructors

The LiveConnectClient class has these constructors.

Constructor | Description
LiveConnectClient(LiveConnectSession) constructor | Initializes a new instance of the LiveConnectClient class.

Events

The LiveConnectClient class has these events.

Event | Description
BackgroundDownloadCompleted event | Raised after a file has been downloaded from Microsoft SkyDrive to Windows Phone isolated storage. The file should finish downloading even if the app that starts the file download quits or is suspended.
BackgroundDownloadProgressChanged event | Raised at indeterminate times while a file is downloading from Microsoft SkyDrive to Windows Phone isolated storage. The file should continue downloading even if the app that starts the file download quits or is suspended.
BackgroundUploadCompleted event | Raised after a file has been uploaded from Windows Phone isolated storage to Microsoft SkyDrive. The file should finish uploading even if the app that starts the file upload quits or is suspended.
BackgroundUploadProgressChanged event | Raised at indeterminate times while a file is uploading from Windows Phone isolated storage to Microsoft SkyDrive. The file should continue uploading even if the app that starts the file upload quits or is suspended.
CopyCompleted event | Raised when a CopyAsync operation is completed.
DeleteCompleted event | Raised when a DeleteAsync operation is completed.
DownloadCompleted event | Raised when a DownloadAsync operation is completed.
DownloadProgressChanged event | Raised every time a chunk of data is downloaded during a DownloadAsync operation.
GetCompleted event | Raised when a GetAsync operation is completed.
MoveCompleted event | Raised when a MoveAsync operation is completed.
PostCompleted event | Raised when a PostAsync operation is completed.
PutCompleted event | Raised when a PutAsync operation is completed.
UploadCompleted event | Raised when an UploadAsync operation is complete.
UploadProgressChanged event | Raised every time a chunk of data is uploaded during an UploadAsync operation.

Methods

The LiveConnectClient class has these methods. It also inherits methods from the Object class.

Method | Description
AttachPendingTransfers method | After an app starts or resumes, checks to see if any associated in-progress file download or upload requests are currently in progress.
BackgroundDownloadAsync(String, Uri) method | Begins downloading a file from Microsoft SkyDrive to Windows Phone isolated storage. The file download should continue even if the app that starts the file download quits or is suspended.
BackgroundDownloadAsync(String, Uri, String) method | Begins downloading a file from Microsoft SkyDrive to Windows Phone isolated storage. The file download should continue even if the app that starts the file download quits or is suspended.
BackgroundUploadAsync(String, Uri, OverwriteOption) method | Begins uploading a file from Windows Phone isolated storage to Microsoft SkyDrive. The file upload should continue even if the app that starts the file upload quits or is suspended.
BackgroundUploadAsync(String, Uri, OverwriteOption, String) method | Begins uploading a file from Windows Phone isolated storage to Microsoft SkyDrive. The file upload should continue even if the app that starts the file upload quits or is suspended.
CopyAsync(String, String) method | Performs a copy of a file using the Representational State Transfer (REST) API, passing a string containing the path of the item to copy, and a string with the destination path.
CopyAsync(String, String, Object) method | Performs a copy of a file using the Representational State Transfer (REST) API, passing a string containing the path of the item to copy, a string with the destination path, and the current user state.
DeleteAsync(String) method | Performs a delete of a file using the Representational State Transfer (REST) API for a given path.
DeleteAsync(String, Object) method | Deletes a file using the Representational State Transfer (REST) API for a given path and user state.
DownloadAsync(String) method | Downloads a file with a given path.
DownloadAsync(String, Object) method | Downloads a file with a given path and user state.
GetAsync(String) method | Performs a get of a file for a given file.
GetAsync(String, Object) method | Performs a get of a file using a given path.
MoveAsync(String, String) method | Moves a file from one folder to another using the Representational State Transfer (REST) API.
MoveAsync(String, String, Object) method | Moves a file from one folder to another using the Representational State Transfer (REST) API.
PostAsync(String, IDictionary<String, Object>) method | Performs a post of a resource for a given path and body.
PostAsync(String, IDictionary<String, Object>, Object) method | Performs a post for a given path, body, and user state.
PostAsync(String, String) method | Performs a post of a resource for a given path and body.
PostAsync(String, String, Object) method | Performs an asynchronous put for a given path and body.
PutAsync(String, IDictionary<String, Object>) method | Performs an asynchronous put of a resource for a given path and body.
PutAsync(String, IDictionary<String, Object>, Object) method | Performs an asynchronous put of a resource for a given path and body.
PutAsync(String, String) method | Performs an asynchronous put of a resource.
PutAsync(String, String, Object) method | Performs an asynchronous put for a given path and body.
UploadAsync(String, String, Stream, OverwriteOption) method | Performs an asynchronous upload of a resource with a given path, file name, stream contents, user state, and the option to overwrite an existing file.
UploadAsync(String, String, Stream, OverwriteOption, Object) method | Performs an asynchronous upload of a resource with a given path, file name, stream contents, and user state.

Properties

The LiveConnectClient class has these properties.

Property | Access type | Description
Session property | Read-only | Contains the current session data used by the LiveConnectClient class.

Requirements

Minimum supported client

 None supported

Minimum supported server

 None supported

Minimum supported phone

 Windows Phone 7

Namespace

Microsoft.Live

Assembly
Microsoft.Live.dll


LiveConnectClient.AttachPendingTransfers method

After an app starts or resumes, checks to see if any associated in-progress file download or upload requests are currently in progress.

Syntax

C#
public AttachPendingTransfers()

Parameters

This method has no parameters.

Remarks

For each file download or upload request that is still in progress, the BackgroundDownloadProgressChanged or BackgroundUploadProgressChanged event is called, respectively. For each completed file download or upload request, the BackgroundDownloadCompleted or BackgroundUploadCompleted event is called, respectively.

Requirements

Minimum supported client

 None supported

Minimum supported server

 None supported

Minimum supported phone

 Windows Phone 7

Namespace

Microsoft.Live

Assembly
Microsoft.Live.dll

See also

LiveConnectClient class


LiveConnectClient.BackgroundDownloadAsync methods

Performs an asynchronous background file download operation using the Representational State Transfer (REST) API.

This member is overloaded. For complete information about this member, including syntax, usage, and examples, click a name in the overload list.

Overload list

Method | Description
BackgroundDownloadAsync(String, Uri) | Begins downloading a file from Microsoft SkyDrive to Windows Phone isolated storage. The file download should continue even if the app that starts the file download quits or is suspended.
BackgroundDownloadAsync(String, Uri, String) | Begins downloading a file from Microsoft SkyDrive to Windows Phone isolated storage. The file download should continue even if the app that starts the file download quits or is suspended.

Remarks

BackgroundDownloadAsync is a helper function for making calls to the REST API. It supports all paths and methods in the REST API.

Requirements

Minimum supported client | None supported
Minimum supported server | None supported
Minimum supported phone | Windows Phone 7
Namespace | Microsoft.Live

See also

LiveConnectClient


LiveConnectClient.BackgroundDownloadAsync(String, Uri) method

Begins downloading a file from Microsoft SkyDrive to Windows Phone isolated storage. The file download should continue even if the app that starts the file download quits or is suspended.

Syntax

C#
public BackgroundDownloadAsync(
  string path,
  Uri downloadLocation
)

Parameters

path

Type: String

The file ID of the file to download from SkyDrive, for example "file.22688711f5410e6c.22688711F5410E6C!942".

downloadLocation

Type: Uri

A unique isolated storage path to where the file is to be downloaded, for example "/shared/transfers/myFile1.txt".

Requirements

Minimum supported client

 None supported

Minimum supported server

 None supported

Minimum supported phone

 Windows Phone 7

Namespace

Microsoft.Live

Assembly
Microsoft.Live.dll

See also

LiveConnectClient class


LiveConnectClient.BackgroundDownloadAsync(String, Uri, String) method

Begins downloading a file from Microsoft SkyDrive to Windows Phone isolated storage. The file download should continue even if the app that starts the file download quits or is suspended.

Syntax

C#
public BackgroundDownloadAsync(
  string path,
  Uri downloadLocation,
  string userState
)

Parameters

path

Type: String

The file ID of the file to download from SkyDrive, for example "file.22688711f5410e6c.22688711F5410E6C!942".

downloadLocation

Type: Uri

A unique isolated storage path to where the file is to be downloaded, for example "/shared/transfers/myFile1.txt".

userState

Type: String

A unique identifier for the downloaded file so that info about the file can be accessed in a call to the accompanying BackgroundDownloadCompleted event handler, for example "myFile1".

Requirements

Minimum supported client

 None supported

Minimum supported server

 None supported

Minimum supported phone

 Windows Phone 7

Namespace

Microsoft.Live

Assembly
Microsoft.Live.dll

See also

LiveConnectClient class


LiveConnectClient.BackgroundDownloadCompleted event

Raised after a file has been downloaded from Microsoft SkyDrive to Windows Phone isolated storage. The file should finish downloading even if the app that starts the file download quits or is suspended.

Syntax

C#
public event EventHandler<LiveOperationCompletedEventArgs> BackgroundDownloadCompleted

Event information

Delegate EventHandler<LiveOperationCompletedEventArgs>

Requirements

Minimum supported client

 None supported

Minimum supported server

 None supported

Minimum supported phone

 Windows Phone 7

Namespace

Microsoft.Live

Assembly
Microsoft.Live.dll

See also

LiveConnectClient class


LiveConnectClient.BackgroundDownloadProgressChanged event

Raised at indeterminate times while a file is downloading from Microsoft SkyDrive to Windows Phone isolated storage. The file should continue downloading even if the app that starts the file download quits or is suspended.

Syntax

C#
public event EventHandler<LiveDownloadProgressChangedEventArgs> BackgroundDownloadProgressChanged

Event information

Delegate EventHandler<LiveDownloadProgressChangedEventArgs>

Requirements

Minimum supported client

 None supported

Minimum supported server

 None supported

Minimum supported phone

 Windows Phone 7

Namespace

Microsoft.Live

Assembly
Microsoft.Live.dll

See also

LiveConnectClient class


LiveConnectClient.BackgroundUploadAsync methods

Performs an asynchronous background file upload using the Representational State Transfer (REST) API.

This member is overloaded. For complete information about this member, including syntax, usage, and examples, click a name in the overload list.

Overload list

Method | Description
BackgroundUploadAsync(String, Uri, OverwriteOption) | Begins uploading a file from Windows Phone isolated storage to Microsoft SkyDrive. The file upload should continue even if the app that starts the file upload quits or is suspended.
BackgroundUploadAsync(String, Uri, OverwriteOption, String) | Begins uploading a file from Windows Phone isolated storage to Microsoft SkyDrive. The file upload should continue even if the app that starts the file upload quits or is suspended.

Remarks

BackgroundUploadAsync is a helper function for making calls to the REST API. It supports all paths and methods in the REST API.

Requirements

Minimum supported client | None supported
Minimum supported server | None supported
Minimum supported phone | Windows Phone 7
Namespace | Microsoft.Live

See also

LiveConnectClient


LiveConnectClient.BackgroundUploadAsync(String, Uri, OverwriteOption) method

Begins uploading a file from Windows Phone isolated storage to Microsoft SkyDrive. The file upload should continue even if the app that starts the file upload quits or is suspended.

Syntax

C#
public BackgroundUploadAsync(
  string path,
  Uri uploadLocation,
  OverwriteOption option
)

Parameters

path

Type: String

The folder ID of the folder in SkyDrive to upload the file to, for example "folder.8c8ce076ca27823f.8C8CE076CA27823F!142".

uploadLocation

Type: Uri

The unique isolated storage path to where the file is to be uploaded from, for example "/shared/transfers/myFile2.txt".

option

Type: OverwriteOption

Specifies whether the file that's being uploaded to SkyDrive should overwrite an existing file with the same file name in that location.

Requirements

Minimum supported client

 None supported

Minimum supported server

 None supported

Minimum supported phone

 Windows Phone 7

Namespace

Microsoft.Live

Assembly
Microsoft.Live.dll

See also

LiveConnectClient class


LiveConnectClient.BackgroundUploadAsync(String, Uri, OverwriteOption, String) method

Begins uploading a file from Windows Phone isolated storage to Microsoft SkyDrive. The file upload should continue even if the app that starts the file upload quits or is suspended.

Syntax

C#
public BackgroundUploadAsync(
  string path,
  Uri uploadLocation,
  OverwriteOption option,
  string userState
)

Parameters

path

Type: String

The folder ID of the folder in SkyDrive to upload the file to, for example "folder.8c8ce076ca27823f.8C8CE076CA27823F!142".

uploadLocation

Type: Uri

The unique isolated storage path to where the file is to be uploaded from, for example "/shared/transfers/myFile2.txt".

option

Type: OverwriteOption

Specifies whether the file that's being uploaded to SkyDrive should overwrite an existing file with the same file name in that location.

userState

Type: String

A unique identifier for the file to be uploaded so that info about the file can be accessed in a call to the accompanying BackgroundUploadCompleted event handler, for example "myFile2".

Requirements

Minimum supported client

 None supported

Minimum supported server

 None supported

Minimum supported phone

 Windows Phone 7

Namespace

Microsoft.Live

Assembly
Microsoft.Live.dll

See also

LiveConnectClient class


LiveConnectClient.BackgroundUploadCompleted event

Raised after a file has been uploaded from Windows Phone isolated storage to Microsoft SkyDrive. The file should finish uploading even if the app that starts the file upload quits or is suspended.

Syntax

C#
public event EventHandler<LiveOperationCompletedEventArgs> BackgroundUploadCompleted

Event information

Delegate EventHandler<LiveOperationCompletedEventArgs>

Requirements

Minimum supported client

 None supported

Minimum supported server

 None supported

Minimum supported phone

 Windows Phone 7

Namespace

Microsoft.Live

Assembly
Microsoft.Live.dll

See also

LiveConnectClient class


LiveConnectClient.BackgroundUploadProgressChanged event

Raised at indeterminate times while a file is uploading from Windows Phone isolated storage to Microsoft SkyDrive. The file should continue uploading even if the app that starts the file upload quits or is suspended.

Syntax

C#
public event EventHandler<LiveUploadProgressChangedEventArgs> BackgroundUploadProgressChanged

Event information

Delegate EventHandler<LiveUploadProgressChangedEventArgs>

Requirements

Minimum supported client

 None supported

Minimum supported server

 None supported

Minimum supported phone

 Windows Phone 7

Namespace

Microsoft.Live

Assembly
Microsoft.Live.dll

See also

LiveConnectClient class


LiveConnectClient.CopyAsync methods

Performs an asynchronous copy operation using the Representational State Transfer (REST) API.

This member is overloaded. For complete information about this member, including syntax, usage, and examples, click a name in the overload list.

Overload list

Method | Description
CopyAsync(String, String) | Performs a copy of a file using the Representational State Transfer (REST) API, passing a string containing the path of the item to copy, and a string with the destination path.
CopyAsync(String, String, Object) | Performs a copy of a file using the Representational State Transfer (REST) API, passing a string containing the path of the item to copy, a string with the destination path, and the current user state.

Remarks

CopyAsync is a helper function for making calls to the REST API. It supports all paths and methods in the REST API.

Requirements

Minimum supported client | None supported
Minimum supported server | None supported
Minimum supported phone | Windows Phone 7
Namespace | Microsoft.Live

See also

LiveConnectClient


LiveConnectClient.CopyAsync(String, String) method

Performs a copy of a file using the Representational State Transfer (REST) API, passing a string containing the path of the item to copy, and a string with the destination path.

Syntax

C#
public CopyAsync(
  string path,
  string destination
)

Parameters

path

Type: String

The resource ID of the file to be copied.

destination

Type: String

The destination path to which the item is copied.

Remarks

CopyAsync is supported only for use with Microsoft SkyDrive files.

Requirements

Minimum supported client

 None supported

Minimum supported server

 None supported

Minimum supported phone

 Windows Phone 7

Namespace

Microsoft.Live

Assembly
Microsoft.Live.dll

See also

LiveConnectClient
CopyAsync(String, String, Object)


LiveConnectClient.CopyAsync(String, String, Object) method

Performs a copy of a file using the Representational State Transfer (REST) API, passing a string containing the path of the item to copy, a string with the destination path, and the current user state.

Syntax

C#
public CopyAsync(
  string path,
  string destination,
  object userState
)

Parameters

path

Type: String

The resource ID of the file to be copied.

destination

Type: String

The destination path to which the item is copied.

userState

Type: Object

The current userState object.

Remarks

CopyAsync is supported only for use with Microsoft SkyDrive files.

Requirements

Minimum supported client

 None supported

Minimum supported server

 None supported

Minimum supported phone

 Windows Phone 7

Namespace

Microsoft.Live

Assembly
Microsoft.Live.dll

See also

LiveConnectClient
CopyAsync(String, String)


LiveConnectClient.CopyCompleted event

Raised when a CopyAsync operation is completed.

Syntax

C#
public event EventHandler<LiveOperationCompletedEventArgs> CopyCompleted

Event information

Delegate EventHandler<LiveOperationCompletedEventArgs>

Requirements

Minimum supported client

 None supported

Minimum supported server

 None supported

Minimum supported phone

 Windows Phone 7

Namespace

Microsoft.Live

Assembly
Microsoft.Live.dll

See also

LiveConnectClient


LiveConnectClient.DeleteAsync methods

Performs an asynchronous delete of a file using the Representational State Transfer (REST) API.

This member is overloaded. For complete information about this member, including syntax, usage, and examples, click a name in the overload list.

Overload list

Method | Description
DeleteAsync(String) | Performs a delete of a file using the Representational State Transfer (REST) API for a given path.
DeleteAsync(String, Object) | Deletes a file using the Representational State Transfer (REST) API for a given path and user state.

Remarks

DeleteAsync supports all paths and methods in the REST API.

Requirements

Minimum supported client

 None supported

Minimum supported server

 None supported

Minimum supported phone

 Windows Phone 7

Namespace

Microsoft.Live

Assembly
Microsoft.Live.dll

See also

LiveConnectClient


LiveConnectClient.DeleteAsync(String) method

Performs a delete of a file using the Representational State Transfer (REST) API for a given path.

Syntax

C#
public DeleteAsync(
  string path
)

Parameters

path

Type: String

The relative URL to the resource to be deleted.

Remarks

DeleteAsync supports all paths and methods in the REST API.

Requirements

Minimum supported client

 None supported

Minimum supported server

 None supported

Minimum supported phone

 Windows Phone 7

Namespace

Microsoft.Live

Assembly
Microsoft.Live.dll

See also

LiveConnectClient
DeleteAsync(String, Object)


LiveConnectClient.DeleteAsync(String, Object) method

Deletes a file using the Representational State Transfer (REST) API for a given path and user state.

Syntax

C#
public DeleteAsync(
  string path,
  object userState
)

Parameters

path

Type: String

The relative URL to the resource to be deleted.

userState

Type: Object

The current user state.

Remarks

DeleteAsync supports all paths and methods in the REST API.

Requirements

Minimum supported client

 None supported

Minimum supported server

 None supported

Minimum supported phone

 Windows Phone 7

Namespace

Microsoft.Live

Assembly
Microsoft.Live.dll

See also

LiveConnectClient
DeleteAsync(String)


LiveConnectClient.DeleteCompleted event

Raised when a DeleteAsync operation is completed.

Syntax

C#
public event EventHandler<LiveOperationCompletedEventArgs> DeleteCompleted

Event information

Delegate EventHandler<LiveOperationCompletedEventArgs>

Requirements

Minimum supported client

 None supported

Minimum supported server

 None supported

Minimum supported phone

 Windows Phone 7

Namespace

Microsoft.Live

Assembly
Microsoft.Live.dll

See also

LiveConnectClient


LiveConnectClient.DownloadAsync methods

Performs an asynchronous download of a file and writes the file content to a stream provided by the app using the Representational State Transfer (REST) API.

This member is overloaded. For complete information about this member, including syntax, usage, and examples, click a name in the overload list.

Overload list

Method | Description
DownloadAsync(String) | Downloads a file with a given path.
DownloadAsync(String, Object) | Downloads a file with a given path and user state.

Remarks

DownloadAsync supports all paths and methods in the REST API.

Requirements

Minimum supported client

 None supported

Minimum supported server

 None supported

Minimum supported phone

 Windows Phone 7

Namespace

Microsoft.Live

Assembly
Microsoft.Live.dll

See also

LiveConnectClient


LiveConnectClient.DownloadAsync(String) method

Downloads a file with a given path.

Syntax

C#
public DownloadAsync(
  string path
)

Parameters

path

Type: String

The relative path to the item to be downloaded.

Remarks

DownloadAsync supports all paths and methods in the Representational State Transfer (REST) API.

Requirements

Minimum supported client

 None supported

Minimum supported server

 None supported

Minimum supported phone

 Windows Phone 7

Namespace

Microsoft.Live

Assembly
Microsoft.Live.dll

See also

LiveConnectClient
DownloadAsync methods


LiveConnectClient.DownloadAsync(String, Object) method

Downloads a file with a given path and user state.

Syntax

C#
public DownloadAsync(
  string path,
  object userState
)

Parameters

path

Type: String

The relative path to the item to be downloaded.

userState

Type: Object

Used to uniquely identify the call. The userState object is passed back to the user when the call is completed.

Remarks

DownloadAsync supports all paths and methods in the Representational State Transfer (REST) API.

Requirements

Minimum supported client

 None supported

Minimum supported server

 None supported

Minimum supported phone

 Windows Phone 7

Namespace

Microsoft.Live

Assembly
Microsoft.Live.dll

See also

LiveConnectClient
DownloadAsync methods


LiveConnectClient.DownloadCompleted event

Raised when a DownloadAsync operation is completed.

Syntax

C#
public event EventHandler<LiveDownloadCompletedEventArgs> DownloadCompleted

Event information

Delegate EventHandler<LiveDownloadCompletedEventArgs>

Requirements

Minimum supported client

 None supported

Minimum supported server

 None supported

Minimum supported phone

 Windows Phone 7

Namespace

Microsoft.Live

Assembly
Microsoft.Live.dll

See also

LiveConnectClient


LiveConnectClient.DownloadProgressChanged event

Raised every time a chunk of data is downloaded during a DownloadAsync operation.

Syntax

C#
public event EventHandler<LiveDownloadProgressChangedEventArgs> DownloadProgressChanged

Event information

Delegate EventHandler<LiveDownloadProgressChangedEventArgs>

Requirements

Minimum supported client

 None supported

Minimum supported server

 None supported

Minimum supported phone

 Windows Phone 7

Namespace

Microsoft.Live

Assembly
Microsoft.Live.dll

See also

LiveConnectClient


LiveConnectClient.GetAsync methods

Performs an asynchronous get of a file.

This member is overloaded. For complete information about this member, including syntax, usage, and examples, click a name in the overload list.

Overload list

Method | Description
GetAsync(String) | Performs a get of a file for a given file.
GetAsync(String, Object) | Performs a get of a file using a given path.

Remarks

GetAsync supports all paths and methods in the Representational State Transfer (REST) API.

Requirements

Minimum supported client | None supported
Minimum supported server | None supported
Minimum supported phone | Windows Phone 7
Namespace | Microsoft.Live

See also

LiveConnectClient


LiveConnectClient.GetAsync(String) method

Performs a get of a file for a given file.

Syntax

C#
public GetAsync(
  string path
)

Parameters

path

Type: String

The relative path to the item to be retrieved.

Remarks

GetAsync supports all paths and methods in the Representational State Transfer (REST) API.

Requirements

Minimum supported client

 None supported

Minimum supported server

 None supported

Minimum supported phone

 Windows Phone 7

Namespace

Microsoft.Live

Assembly
Microsoft.Live.dll

See also

LiveConnectClient
GetAsync(String, Object)


LiveConnectClient.GetAsync(String, Object) method

Performs a get of a file using a given path.

Syntax

C#
public GetAsync(
  string path,
  object userState
)

Parameters

path

Type: String

The relative path to the item to be retrieved.

userState

Type: Object

Used to uniquely identify the call. The userState object is passed back to the user when the call is completed.

Remarks

GetAsync supports all paths and methods in the Representational State Transfer (REST) API.

Requirements

Minimum supported client

 None supported

Minimum supported server

 None supported

Minimum supported phone

 Windows Phone 7

Namespace

Microsoft.Live

Assembly
Microsoft.Live.dll

See also

LiveConnectClient
GetAsync(string)


LiveConnectClient.GetCompleted event

Raised when a GetAsync operation is completed.

Syntax

C#
public event EventHandler<LiveOperationCompletedEventArgs> GetCompleted

Event information

Delegate EventHandler<LiveOperationCompletedEventArgs>

Requirements

Minimum supported client

 None supported

Minimum supported server

 None supported

Minimum supported phone

 Windows Phone 7

Namespace

Microsoft.Live

Assembly
Microsoft.Live.dll

See also

LiveConnectClient


LiveConnectClient.LiveConnectClient(LiveConnectSession) constructor

Initializes a new instance of the LiveConnectClient class.

Syntax

C#
public  LiveConnectClient(
  LiveConnectSession session
)

Parameters

session

Type: LiveConnectSession

The LiveConnectSession that contains all the access information for the service.

Return value

Requirements

Minimum supported client

 None supported

Minimum supported server

 None supported

Minimum supported phone

 Windows Phone 7

Namespace

Microsoft.Live

Assembly
Microsoft.Live.dll

See also

LiveConnectClient


LiveConnectClient.MoveAsync methods

Moves a file from one folder to another.

This member is overloaded. For complete information about this member, including syntax, usage, and examples, click a name in the overload list.

Overload list

Method | Description
MoveAsync(String, String) | Moves a file from one folder to another using the Representational State Transfer (REST) API.
MoveAsync(String, String, Object) | Moves a file from one folder to another using the Representational State Transfer (REST) API.

Requirements

Minimum supported client

 None supported

Minimum supported server

 None supported

Minimum supported phone

 Windows Phone 7

Namespace

Microsoft.Live

Assembly
Microsoft.Live.dll

See also

LiveConnectClient


LiveConnectClient.MoveAsync(String, String) method

Moves a file from one folder to another using the Representational State Transfer (REST) API.

Syntax

C#
public MoveAsync(
  string path,
  string destination
)

Parameters

path

Type: String

The relative path to the item to be moved.

destination

Type: String

The path to which to move the resource.

Remarks

MoveAsync is supported only with Microsoft SkyDrive files.

Requirements

Minimum supported client

 None supported

Minimum supported server

 None supported

Minimum supported phone

 Windows Phone 7

Namespace

Microsoft.Live

Assembly
Microsoft.Live.dll

See also

LiveConnectClient
MoveAsync(String, String, Object)


LiveConnectClient.MoveAsync(String, String, Object) method

Moves a file from one folder to another using the Representational State Transfer (REST) API.

Syntax

C#
public MoveAsync(
  string path,
  string destination,
  object userState
)

Parameters

path

Type: String

The relative path to the item to be moved.

destination

Type: String

The path to which to move the resource.

userState

Type: Object

The current user state.

Remarks

MoveAsync is supported only with Microsoft SkyDrive files.

Requirements

Minimum supported client

 None supported

Minimum supported server

 None supported

Minimum supported phone

 Windows Phone 7

Namespace

Microsoft.Live

Assembly
Microsoft.Live.dll

See also

LiveConnectClient
MoveAsync(String, String)


LiveConnectClient.MoveCompleted event

Raised when a MoveAsync operation is completed.

Syntax

C#
public event EventHandler<LiveOperationCompletedEventArgs> MoveCompleted

Event information

Delegate EventHandler<LiveOperationCompletedEventArgs>

Requirements

Minimum supported client

 None supported

Minimum supported server

 None supported

Minimum supported phone

 Windows Phone 7

Namespace

Microsoft.Live

Assembly
Microsoft.Live.dll

See also

LiveConnectClient


LiveConnectClient.PostAsync methods

Performs a post of a resource.

This member is overloaded. For complete information about this member, including syntax, usage, and examples, click a name in the overload list.

Overload list

Method | Description
PostAsync(String, String) | Performs a post of a resource for a given path and body.
PostAsync(String, String, Object) | Performs a post for a given path, body, and user state.
PostAsync(String, IDictionary<String, Object>) | Performs a post of a resource for a given path and body.
PostAsync(String, IDictionary<String, Object>, Object) | Performs a post for a given path, body, and user state.

Requirements

Minimum supported client

 None supported

Minimum supported server

 None supported

Minimum supported phone

 Windows Phone 7

Namespace

Microsoft.Live

Assembly
Microsoft.Live.dll

See also

LiveConnectClient


LiveConnectClient.PostAsync(String, String) method

Performs a post of a resource for a given path and body.

Syntax

C#
public PostAsync(
  string path,
  string body
)

Parameters

path

Type: String

The path to the resource collection where the object is to be created.

body

Type: String

The body that should be included in the API call.

Remarks

PostAsync supports all paths and methods in the Representational State Transfer (REST) API.

Requirements

Minimum supported client

 None supported

Minimum supported server

 None supported

Minimum supported phone

 Windows Phone 7

Namespace

Microsoft.Live

Assembly
Microsoft.Live.dll

See also

LiveConnectClient
PostAsync(String, IDictionary<String , Object>)
PostAsync(String, String, Object)
PostAsync(String, IDictionary<String , Object>, Object)


LiveConnectClient.PostAsync(String, IDictionary<String, Object>) method

Performs a post of a resource for a given path and body.

Syntax

C#
public PostAsync(
  string path,
  IDictionary<String, Object> body
)

Parameters

path

Type: String

The path to the resource collection where the object is to be created.

body

Type: IDictionary<String, Object>

The body that should be included in the API call.

Remarks

PostAsync supports all paths and methods in the Representational State Transfer (REST) API.

Requirements

Minimum supported client

 None supported

Minimum supported server

 None supported

Minimum supported phone

 Windows Phone 7

Namespace

Microsoft.Live

Assembly
Microsoft.Live.dll

See also

LiveConnectClient
PostAsync(String, String)
PostAsync(String, String, Object)
PostAsync(String, IDictionary<String , Object>, Object)


LiveConnectClient.PostAsync(String, String, Object) method

Performs a post for a given path, body, and user state.

Syntax

C#
public PostAsync(
  string path,
  string body,
  object userState
)

Parameters

path

Type: String

The path to the resource collection where the object is to be created.

body

Type: String

The body that should be included in the API call.

userState

Type: Object

Used to uniquely identify the call. The userState object is passed back to the user when the call is completed.

Remarks

PostAsync supports all paths and methods in the Representational State Transfer (REST) API.

Requirements

Minimum supported client

 None supported

Minimum supported server

 None supported

Minimum supported phone

 Windows Phone 7

Namespace

Microsoft.Live

Assembly
Microsoft.Live.dll

See also

LiveConnectClient
PostAsync(String, String)
PostAsync(String, IDictionary<String , Object>)
PostAsync(String, IDictionary<String , Object>, Object)


LiveConnectClient.PostAsync(String, IDictionary<String, Object>, Object) method

Performs a post for a given path, body, and user state.

Syntax

C#
public  PostAsync(
  string path,
  IDictionary<String, Object> body,
  object userState
)

Parameters

path

Type: String

The path to the resource collection where the object is to be created.

body

Type: IDictionary<String, Object>

The body that should be included in the API call.

userState

Type: Object

Used to uniquely identify the call. The userState object is passed back to the user when the call is completed.

Return value

Remarks

PostAsync supports all paths and methods in the Representational State Transfer (REST) API.

Requirements

Minimum supported client

 None supported

Minimum supported server

 None supported

Minimum supported phone

 Windows Phone 7

Namespace

Microsoft.Live

Assembly
Microsoft.Live.dll

See also

LiveConnectClient
PostAsync(String, String)
PostAsync(String, IDictionary<String , Object>)
PostAsync(String, String, Object)


LiveConnectClient.PostCompleted event

Raised when a PostAsync operation is completed.

Syntax

C#
public event EventHandler<LiveOperationCompletedEventArgs> PostCompleted

Event information

Delegate EventHandler<LiveOperationCompletedEventArgs>

Requirements

Minimum supported client

 None supported

Minimum supported server

 None supported

Minimum supported phone

 Windows Phone 7

Namespace

Microsoft.Live

Assembly
Microsoft.Live.dll

See also

LiveConnectClient


LiveConnectClient.PutAsync methods

Performs an asynchronous put that updates a resource.

This member is overloaded. For complete information about this member, including syntax, usage, and examples, click a name in the overload list.

Overload list

Method | Description
PutAsync(String, String) method | Performs an asynchronous put of a resource.
PutAsync(String, String, Object) method | Performs an asynchronous put for a given path and body.
PutAsync(String, IDictionary<String , Object>) method | Performs an asynchronous put of a resource for a given path and body.
PutAsync(String, IDictionary<String , Object>, Object) method | Performs an asynchronous put of a resource for a given path and body.

Requirements

Minimum supported client

 None supported

Minimum supported server

 None supported

Minimum supported phone

 Windows Phone 7

Namespace

Microsoft.Live

Assembly
Microsoft.Live.dll

See also

LiveConnectClient


LiveConnectClient.PutAsync(String, String) method

Performs an asynchronous put of a resource.

Syntax

C#
public PutAsync(
  string path,
  string body
)

Parameters

path

Type: String

The relative path to the affected item.

body

Type: String

The body that should be included in the API call.

Remarks

PutAsync supports all paths and methods in the Representational State Transfer (REST) API.

Requirements

Minimum supported client

 None supported

Minimum supported server

 None supported

Minimum supported phone

 Windows Phone 7

Namespace

Microsoft.Live

Assembly
Microsoft.Live.dll

See also

LiveConnectClient
PutAsync(String, IDictionary<String , Object>)
PutAsync(String, String, Object)
PutAsync(String, IDictionary<String , Object>, Object)


LiveConnectClient.PutAsync(String, IDictionary<String, Object>) method

Performs an asynchronous put of a resource for a given path and body.

Syntax

C#
public PutAsync(
  string path,
  IDictionary<String, Object> body
)

Parameters

path

Type: String

The relative path to the affected item.

body

Type: IDictionary<String, Object>

The body that should be included in the API call.

Remarks

PutAsync supports all paths and methods in the Representational State Transfer (REST) API.

Requirements

Minimum supported client

 None supported

Minimum supported server

 None supported

Minimum supported phone

 Windows Phone 7

Namespace

Microsoft.Live

Assembly
Microsoft.Live.dll

See also

LiveConnectClient
PutAsync(String, String)
PutAsync(String, String, Object)
PutAsync(String, IDictionary<String , Object>, Object)


LiveConnectClient.PutAsync(String, String, Object) method

Performs an asynchronous put for a given path and body.

Syntax

C#
public PutAsync(
  string path,
  string body,
  object userState
)

Parameters

path

Type: String

The relative path to the affected item.

body

Type: String

The body that should be included in the API call.

userState

Type: Object

Used to uniquely identify the call. The userState object is passed back to the user when the call is completed.

Remarks

PutAsync supports all paths and methods in the Representational State Transfer (REST) API.

Requirements

Minimum supported client

 None supported

Minimum supported server

 None supported

Minimum supported phone

 Windows Phone 7

Namespace

Microsoft.Live

Assembly
Microsoft.Live.dll

See also

LiveConnectClient
PutAsync(String, String)
PutAsync(String, IDictionary<String , Object>)
PutAsync(String, IDictionary<String , Object>, Object)


LiveConnectClient.PutAsync(String, IDictionary<String, Object>, Object) method

Performs an asynchronous put of a resource for a given path and body.

Syntax

C#
public PutAsync(
  string path,
  IDictionary<String, Object> body,
  object userState
)

Parameters

path

Type: String

The relative path to the affected item.

body

Type: IDictionary<String, Object>

The body that should be included in the API call.

userState

Type: Object

Used to uniquely identify the call. The userState object is passed back to the user when the call is completed.

Remarks

PutAsync supports all paths and methods in the Representational State Transfer (REST) API.

Requirements

Minimum supported client

 None supported

Minimum supported server

 None supported

Minimum supported phone

 Windows Phone 7

Namespace

Microsoft.Live

Assembly
Microsoft.Live.dll

See also

LiveConnectClient
PutAsync(String, String)
PutAsync(String, IDictionary<String , Object>)
PutAsync(String, String, Object)


LiveConnectClient.PutCompleted event

Raised when a PutAsync operation is completed.

Syntax

C#
public event EventHandler<LiveOperationCompletedEventArgs> PutCompleted

Event information

Delegate EventHandler<LiveOperationCompletedEventArgs>

Requirements

Minimum supported client

 None supported

Minimum supported server

 None supported

Minimum supported phone

 Windows Phone 7

Namespace

Microsoft.Live

Assembly
Microsoft.Live.dll

See also

LiveConnectClient


LiveConnectClient.Session property

Contains the current session data used by the LiveConnectClient class.

Syntax

C#
public LiveConnectSession Session { get; }

Property value

Type: LiveConnectSession

Session

Requirements

Minimum supported client

 None supported

Minimum supported server

 None supported

Minimum supported phone

 Windows Phone 7

Namespace

Microsoft.Live

Assembly
Microsoft.Live.dll

See also

LiveConnectClient


LiveConnectClient.UploadAsync methods

Performs an asynchronous upload.

This member is overloaded. For complete information about this member, including syntax, usage, and examples, click a name in the overload list.

Overload list

Method | Description
UploadAsync(String, String, Stream, OverwriteOption) method | Performs an asynchronous upload of a resource with a given path, file name, stream contents, user state, and the option to overwrite an existing file.
UploadAsync(String, String, Stream, OverwriteOption, Object) method | Performs an asynchronous upload of a resource with a given path, file name, stream contents, and user state.

Requirements

Minimum supported client

 None supported

Minimum supported server

 None supported

Minimum supported phone

 Windows Phone 7

Namespace

Microsoft.Live

Assembly
Microsoft.Live.dll

See also

LiveConnectClient


LiveConnectClient.UploadAsync(String, String, Stream, OverwriteOption) method

Performs an asynchronous upload of a resource with a given path, file name, stream contents, user state, and the option to overwrite an existing file.

Syntax

C#
public UploadAsync(
  string path,
  string fileName,
  Stream inputStream,
  OverwriteOption option
)

Parameters

path

Type: String

The destination path for the upload.

fileName

Type: String

The name of the file to be uploaded.

inputStream

Type: Stream

The stream to add to the body of the API request.

option

Type: OverwriteOption

Specifies whether the file that's being uploaded to SkyDrive should overwrite an existing file with the same file name in that location.

Remarks

UploadAsync supports all paths and methods in the Representational State Transfer (REST) API.

Requirements

Minimum supported client

 None supported

Minimum supported server

 None supported

Minimum supported phone

 Windows Phone 7

Namespace

Microsoft.Live

Assembly
Microsoft.Live.dll

See also

LiveConnectClient
UploadAsync methods


LiveConnectClient.UploadAsync(String, String, Stream, OverwriteOption, Object) method

Performs an asynchronous upload of a resource with a given path, file name, stream contents, and user state.

Syntax

C#
public UploadAsync(
  string path,
  string fileName,
  Stream inputStream,
  OverwriteOption option,
  object userState
)

Parameters

path

Type: String

The destination path for the upload.

fileName

Type: String

The name of the file to be uploaded.

inputStream

Type: Stream

The stream to add to the body of the API request.

option

Type: OverwriteOption

Specifies whether the file that's being uploaded to SkyDrive should overwrite an existing file with the same file name in that location.

userState

Type: Object

Used to uniquely identify the call. The userState object is passed back to the user when the call is completed.

Remarks

UploadAsync supports all paths and methods in the Representational State Transfer (REST) API.

Requirements

Minimum supported client

 None supported

Minimum supported server

 None supported

Minimum supported phone

 Windows Phone 7

Namespace

Microsoft.Live

Assembly
Microsoft.Live.dll

See also

LiveConnectClient
UploadAsync methods


LiveConnectClient.UploadCompleted event

Raised when an UploadAsync operation is complete.

Syntax

C#
public event EventHandler<LiveOperationCompletedEventArgs> UploadCompleted

Event information

Delegate EventHandler<LiveOperationCompletedEventArgs>

Requirements

Minimum supported client

 None supported

Minimum supported server

 None supported

Minimum supported phone

 Windows Phone 7

Namespace

Microsoft.Live

Assembly
Microsoft.Live.dll

See also

LiveConnectClient


LiveConnectClient.UploadProgressChanged event

Raised every time a chunk of data is uploaded during an UploadAsync operation.

Syntax

C#
public event EventHandler<LiveUploadProgressChangedEventArgs> UploadProgressChanged

Event information

Delegate EventHandler<LiveUploadProgressChangedEventArgs>

Requirements

Minimum supported client

 None supported

Minimum supported server

 None supported

Minimum supported phone

 Windows Phone 7

Namespace

Microsoft.Live

Assembly
Microsoft.Live.dll

See also

LiveConnectClient


LiveConnectException class

Used to indicate when an exception has occurred during the connection process.

Syntax

C#
public class LiveConnectException : Exception

Attributes

None

Members

The LiveConnectException class has these types of members:

  • Constructors
  • Methods
  • Properties

Constructors

The LiveConnectException class has these constructors.

Constructor | Description
LiveConnectException() method | Initializes a new instance of the LiveConnectException class.
LiveConnectException(String, String) method | Initializes a new instance of the LiveConnectException class.
LiveConnectException(String, String, Exception) method | Initializes a new instance of the LiveConnectException class.

Methods

The LiveConnectException class has these methods. It also inherits methods from the Object class.

Method | Description
ToString() | Returns a string that represents the current object.

Properties

The LiveConnectException class has these properties.

Property | Access type | Description
ErrorCode property | Read-only | The error code that is returned from the operation.

Requirements

Minimum supported client

 Windows 8

Minimum supported server

 None supported

Minimum supported phone

 Windows Phone 7

Namespace

Microsoft.Live

Assembly
Microsoft.Live.dll


LiveConnectException.ErrorCode property

The error code that is returned from the operation.

Syntax

C#
public System.String ErrorCode { get; }

Property value

Type: System.String

ErrorCode

Requirements

Minimum supported client

 Windows 8

Minimum supported server

 None supported

Minimum supported phone

 Windows Phone 7

Namespace

Microsoft.Live

Assembly
Microsoft.Live.dll

See also

LiveConnectException


LiveConnectException.LiveConnectException constructors

Initializes a new instance of the LiveConnectException class.

Overload list

Constructor | Description
LiveConnectException() | Initializes a new instance of the LiveConnectException class.
LiveConnectException(String, String) | Initializes a new instance of the LiveConnectException class.
LiveConnectException(String, String, Exception) | Initializes a new instance of the LiveConnectException class.

Requirements

Minimum supported client

 Windows 8

Minimum supported server

 None supported

Minimum supported phone

 Windows Phone 7

Namespace

Microsoft.Live

Assembly
Microsoft.Live.dll

See also

LiveConnectException


LiveConnectException.LiveConnectException() constructor

Initializes a new instance of the LiveConnectException class.

Syntax

C#
public  LiveConnectException()

Parameters

This constructor has no parameters.

Requirements

Minimum supported client

 Windows 8

Minimum supported server

 None supported

Minimum supported phone

 Windows Phone 7

Namespace

Microsoft.Live

Assembly
Microsoft.Live.dll

See also

LiveConnectException
LiveConnectException(String, String)
LiveConnectException(String, String, Exception)


LiveConnectException.LiveConnectException(String, String) constructor

Initializes a new instance of the LiveConnectException class.

Syntax

C#
public  LiveConnectException(
  string errorCode,
  string message
)

Parameters

errorCode

Type: String

The error code returned from the operation.

message

Type: String

The exception message to display.

Requirements

Minimum supported client

 Windows 8

Minimum supported server

 None supported

Namespace

Live

Assembly
Live.dll

See also

LiveConnectException
LiveConnectException()
LiveConnectException(String, String, Exception)


LiveConnectException.LiveConnectException(String, String, Exception) constructor

Initializes a new instance of the LiveConnectException class.

Syntax

C#
public  LiveConnectException(
  string errorCode,
  string message,
  Exception innerException
)

Parameters

errorCode

Type: String

The error code returned from the operation.

message

Type: String

The exception message to display.

innerException

Type: Exception

The inner exception text to display.

Requirements

Minimum supported client

 Windows 8

Minimum supported server

 None supported

Namespace

Live

Assembly
Live.dll

See also

LiveConnectException
LiveConnectException()
LiveConnectException(String, String)


LiveConnectException.ToString method

Returns a string that represents the current object.

Syntax

C#
public System.String ToString()

Parameters

This method has no parameters.

Return value

Requirements

Minimum supported client

 Windows 8

Minimum supported server

 None supported

Minimum supported phone

 Windows Phone 7

Namespace

Microsoft.Live

Assembly
Microsoft.Live.dll

See also

LiveConnectException


LiveConnectSession class

Used to access the current session.

Syntax

C#
public class LiveConnectSession

Attributes

None

Members

The LiveConnectSession class has these types of members:

  • Properties

Properties

The LiveConnectSession class has these properties.

Property | Access type | Description
AccessToken property | Read-only | The access token for a signed-in and connected user.
AuthenticationToken property | Read-only | The authentication token for a signed-in and connected user.

Requirements

Minimum supported client

 Windows 8

Minimum supported server

 None supported

Namespace

Microsoft.Live

Assembly
Microsoft.Live.dll


LiveConnectSession.AccessToken property

The access token for a signed-in and connected user.

Syntax

C#
public System.String AccessToken { get; }

Property value

Type: System.String

AccessToken

Requirements

Minimum supported client

 Windows 8

Minimum supported server

 None supported

Namespace

Microsoft.Live

Assembly
Microsoft.Live.dll

See also

LiveConnectSession


LiveConnectSession.AuthenticationToken property

The authentication token for a signed-in and connected user.

Syntax

C#
public System.String AuthenticationToken { get; }

Property value

Type: System.String

AuthenticationToken

Requirements

Minimum supported client

 Windows 8

Minimum supported server

 None supported

Namespace

Microsoft.Live

Assembly
Microsoft.Live.dll

See also

LiveConnectSession


LiveConnectSession class

Used to access the current session.

Syntax

C#
public class LiveConnectSession

Attributes

None

Members

The LiveConnectSession class has these types of members:

  • Properties

Properties

The LiveConnectSession class has these properties.

Property | Access type | Description
AccessToken property | Read-only | The access token for a signed-in and connected user.
AuthenticationToken property | Read-only | The authentication token for a signed-in and connected user.
Expires property | Read-only | The exact time when the session expires. This time is expressed in the number of seconds since 1 January, 1970.
RefreshToken property | Read-only | Provides a refresh token that is specific to both the user and the app, which can be used to refresh the access token.
Scopes property | Read-only | If the user has consented to one or more permissions, the list of consented scopes is included here. This includes consent that is given on the initial login.

Requirements

Minimum supported client

 None supported

Minimum supported server

 None supported

Minimum supported phone

 Windows Phone 7

Namespace

Microsoft.Live

Assembly
Microsoft.Live.dll


LiveConnectSession.AccessToken property

The access token for a signed-in and connected user.

Syntax

C#
public System.String AccessToken { get; }

Property value

Type: System.String

AccessToken

Requirements

Minimum supported client

 None supported

Minimum supported server

 None supported

Minimum supported phone

 Windows Phone 7

Namespace

Microsoft.Live

Assembly
Microsoft.Live.dll

See also

LiveConnectSession


LiveConnectSession.AuthenticationToken property

The authentication token for a signed-in and connected user.

Syntax

C#
public System.String AuthenticationToken { get; }

Property value

Type: System.String

AuthenticationToken

Requirements

Minimum supported client

 None supported

Minimum supported server

 None supported

Minimum supported phone

 Windows Phone 7

Namespace

Microsoft.Live

Assembly
Microsoft.Live.dll

See also

LiveConnectSession


LiveConnectSession.Expires property

The exact time when the session expires. This time is expressed in the number of seconds since 1 January, 1970.

Syntax

C#
public System.DateTimeOffset Expires { get; }

Property value

Type: System.DateTimeOffset

Expires

Requirements

Minimum supported client

 None supported

Minimum supported server

 None supported

Minimum supported phone

 Windows Phone 7

Namespace

Microsoft.Live

Assembly
Microsoft.Live.dll

See also

LiveConnectSession


LiveConnectSession.RefreshToken property

Provides a refresh token that is specific to both the user and the app, which can be used to refresh the access token.

Syntax

C#
public string RefreshToken { get; }

Property value

Type: String

RefreshToken

Requirements

Minimum supported client

 None supported

Minimum supported server

 None supported

Minimum supported phone

 Windows Phone 7

Namespace

Microsoft.Live

Assembly
Microsoft.Live.dll

See also

LiveConnectSession


LiveConnectSession.Scopes property

If the user has consented to one or more permissions, the list of consented scopes is included here. This includes consent that is given on the initial login. If this is an incremental permission request and the value of scopes is null, then the user has rejected the permission request. Note that if a user rejects a permission request, this is also explicitly returned in the error value. This object is never null.

Syntax

C#
public IEnumerable<String> Scopes { get; }

Property value

Type: IEnumerable<String>

Scopes

Requirements

Minimum supported client

 None supported

Minimum supported server

 None supported

Minimum supported phone

 Windows Phone 7

Namespace

Microsoft.Live

Assembly
Microsoft.Live.dll

See also

LiveConnectSession


LiveConnectSessionStatus enumeration

Indicates the status of the session.

Syntax

C#
public enum LiveConnectSessionStatus

Attributes

None

Members

The LiveConnectSessionStatus enumeration has these members.

Member | Value | Description
Connected | LiveConnectSessionStatus.Connected | Indicates that the session is connected.
NotConnected | LiveConnectSessionStatus.NotConnected | Indicates that the session is not connected.
Unknown | LiveConnectSessionStatus.Unknown | Indicates that the session status is not known.

Requirements

Minimum supported client

 Windows 8

Minimum supported server

 None supported

Minimum supported phone

 Windows Phone 7

Namespace

Microsoft.Live

Assembly
Microsoft.Live.dll


LiveDownloadCompletedEventArgs class

Raised when a file download operation is completed.

Syntax

C#
public class LiveDownloadCompletedEventArgs : AsyncCompletedEventArgs

Attributes

None

Members

The LiveDownloadCompletedEventArgs class has these types of members:

  • Methods
  • Properties

Methods

The LiveDownloadCompletedEventArgs class has these methods. It also inherits methods from the Object class.

Method | Description
LiveDownloadCompletedEventArgs(Exception, Boolean, Object) method | Creates and initializes a new instance of the LiveDownloadCompletedEventArgs class, specifying any error that occurred, whether the operation was cancelled, and an optional, user-supplied state object.
LiveDownloadCompletedEventArgs(IO.Stream, Object) method | Creates and initializes a new instance of the LiveDownloadCompletedEventArgs class, specifying the contents of a file download operation and an optional, user-supplied state object.

Properties

The LiveDownloadCompletedEventArgs class has these properties.

Property | Access type | Description
Result property | Read-only | Gets the contents of a file download operation.

Requirements

Minimum supported client

 None supported

Minimum supported server

 None supported

Minimum supported phone

 Windows Phone 7

Namespace

Microsoft.Live

Assembly
Microsoft.Live.dll


LiveDownloadCompletedEventArgs.LiveDownloadCompletedEventArgs constructors

Creates and initializes a new instance of the LiveDownloadCompletedEventArgs class.

Overload list

Constructor | Description
LiveDownloadCompletedEventArgs(IO.Stream, Object) | Creates and initializes a new instance of the LiveDownloadCompletedEventArgs class, specifying the contents of a file download operation and an optional, user-supplied state object.
LiveDownloadCompletedEventArgs(Exception, Boolean, Object) | Creates and initializes a new instance of the LiveDownloadCompletedEventArgs class, specifying any error that occurred, whether the operation was cancelled, and an optional, user-supplied state object.

Requirements

Minimum supported client

 None supported

Minimum supported server

 None supported

Minimum supported phone

 Windows Phone 7

Namespace

Microsoft.Live

Assembly
Microsoft.Live.dll

See also

LiveDownloadCompletedEventArgs


LiveDownloadCompletedEventArgs.LiveDownloadCompletedEventArgs(Exception, Boolean, Object) constructor

Creates and initializes a new instance of the LiveDownloadCompletedEventArgs class, specifying any error that occurred, whether the operation was cancelled, and an optional, user-supplied state object.

Syntax

C#
public  LiveDownloadCompletedEventArgs(
  Exception error,
  bool cancelled,
  object userState
)

Parameters

error

Type: Exception

Any error that occurred during the asynchronous operation.

cancelled

Type: Boolean

A value that indicates whether the asynchronous operation was cancelled.

userState

Type: Object

The optional, user-supplied state object that is used to identify the task that raised this event.

Requirements

Minimum supported client

 None supported

Minimum supported server

 None supported

Minimum supported phone

 Windows Phone 7

Namespace

Microsoft.Live

Assembly
Microsoft.Live.dll

See also

LiveDownloadCompletedEventArgs
LiveDownloadCompletedEventArgs(IO.Stream, Object)


LiveDownloadCompletedEventArgs.LiveDownloadCompletedEventArgs(IO.Stream, Object) constructor

Creates and initializes a new instance of the LiveDownloadCompletedEventArgs class, specifying the contents of a file download operation and an optional, user-supplied state object.

Syntax

C#
public  LiveDownloadCompletedEventArgs(
  IO.Stream result,
  object userState
)

Parameters

result

Type: IO.Stream

The contents of a file download operation.

userState

Type: Object

The optional, user-supplied state object that is used to identify the task that raised this event.

Requirements

Minimum supported client

 None supported

Minimum supported server

 None supported

Minimum supported phone

 Windows Phone 7

Namespace

Microsoft.Live

Assembly
Microsoft.Live.dll

See also

LiveDownloadCompletedEventArgs
LiveOperationCompletedEventArgs(Exception, Boolean, Object)


LiveDownloadCompletedEventArgs.Result property

Gets the contents of a file download operation.

Syntax

C#
public IO.Stream Result { get; }

Property value

Type: IO.Stream

The contents of the file download operation.

Requirements

Minimum supported client

 None supported

Minimum supported server

 None supported

Minimum supported phone

 Windows Phone 7

Namespace

Microsoft.Live

Assembly
Microsoft.Live.dll

See also

LiveDownloadCompletedEventArgs


LiveDownloadOperationResult class

Represents the results of a file download operation.

Syntax

C#
public class LiveDownloadOperationResult

Attributes

None

Members

The LiveDownloadOperationResult class has these types of members:

  • Constructors
  • Methods
  • Properties

Constructors

The LiveDownloadOperationResult class has these constructors.

Constructor | Description
LiveDownloadOperationResult(IInputStream) | Initializes a new instance of the LiveDownloadOperationResult class backed by a stream.
LiveDownloadOperationResult(IStorageFile) | Initializes a new instance of the LiveDownloadOperationResult class backed by a file.

Methods

The LiveDownloadOperationResult class has these methods. It also inherits methods from the Object class.

Method | Description
GetRandomAccessStreamAsync | Gets the results of a file download operation as a random access stream.

Properties

The LiveDownloadOperationResult class has these properties.

Property | Access type | Description
File | Read-only | Gets the results of a file download operation as a file.
Stream | Read-only | Gets the results of a file download operation as a stream.

Requirements

Minimum supported client

 Windows 8

Minimum supported server

 None supported

Namespace

Microsoft.Live

Assembly
Microsoft.Live.dll


LiveDownloadOperationResult.GetRandomAccessStreamAsync method

Gets the results of a file download operation as a random access stream.

Syntax

C#
public Task<Windows.Storage.Streams.IRandomAccessStream> GetRandomAccessStreamAsync()

Parameters

This method has no parameters.

Return value

Type: Task<Windows.Storage.Streams.IRandomAccessStream>

The task-aware random access stream.

Requirements

Minimum supported client

 Windows 8

Minimum supported server

 None supported

Namespace

Microsoft.Live

Assembly
Microsoft.Live.dll

See also

LiveDownloadOperationResult class


LiveDownloadOperationResult.LiveDownloadOperationResult constructors

Initializes a new instance of the LiveDownloadOperationResult class.

Overload list

Constructor | Description
LiveDownloadOperationResult(Stream) | Gets the results of a file download operation as a stream.
LiveDownloadOperationResult(IStorageFile) | Initializes a new instance of the LiveDownloadOperationResult class backed by a file.

Requirements

Minimum supported client

 Windows 8

Minimum supported server

 None supported

Namespace

Microsoft.Live

Assembly
Microsoft.Live.dll

See also

LiveDownloadOperationResult class


LiveDownloadOperationResult.LiveDownloadOperationResult( IStorageFile) constructor

Initializes a new instance of the LiveDownloadOperationResult class backed by a file.

Syntax

C#
public LiveDownloadOperationResult LiveDownloadOperationResult(
      IStorageFile file
)

Parameters

file

Type: IStorageFile

The file.

Return value

Requirements

Minimum supported client

 Windows 8

Minimum supported server

 None supported

Namespace

Microsoft.Live

Assembly
Microsoft.Live.dll

See also

LiveDownloadOperationResult
LiveDownloadOperationResult constructors
LiveDownloadOperationResult(IInputStream) constructor


LiveDownloadOperationResult.LiveDownloadOperationResult(IInputStream) constructor

Initializes a new instance of the LiveDownloadOperationResult class backed by a stream.

Syntax

C#
public LiveDownloadOperationResult LiveDownloadOperationResult(
  IInputStream stream
)

Parameters

stream

Type: IInputStream

The stream.

Return value

Requirements

Minimum supported client

 Windows 8

Minimum supported server

 None supported

Namespace

Microsoft.Live

Assembly
Microsoft.Live.dll

See also

LiveDownloadOperationResult
LiveDownloadOperationResult constructors
LiveDownloadOperationResult(IStorageFile) constructor


LiveDownloadOperationResult.File property

Gets the results of a file download operation as a file.

Syntax

C#
public IStorageFile File { get; }

Property value

Type: IStorageFile

The file.

Requirements

Minimum supported client

 Windows 8

Minimum supported server

 None supported

Namespace

Microsoft.Live

Assembly
Microsoft.Live.dll

See also

LiveDownloadOperationResult class


LiveDownloadOperationResult.Stream property

Gets the results of a file download operation as a stream.

Syntax

C#
public IInputStream Stream { get; }

Property value

Type: IInputStream

The stream.

Requirements

Minimum supported client

 Windows 8

Minimum supported server

 None supported

Namespace

Microsoft.Live

Assembly
Microsoft.Live.dll

See also

LiveDownloadOperationResult class


LiveDownloadOperationResult class

Represents the result of a Microsoft SkyDrive file download request.

Syntax

C#
public class LiveDownloadOperationResult

Attributes

None

Members

The LiveDownloadOperationResult class has these types of members:

  • Constructors
  • Properties

Constructors

The LiveDownloadOperationResult class has these constructors.

Constructor | Description
LiveDownloadOperationResult(Stream, Object) | Initializes an object that can access the results of a Microsoft SkyDrive file download request.

Properties

The LiveDownloadOperationResult class has these properties.

Property | Access type | Description
Stream | Read-only | Gets the downloaded file, represented as a file stream.

Requirements

Minimum supported client

 None supported

Minimum supported server

 None supported

Minimum supported phone

 Windows Phone 7

Namespace

Microsoft.Live

Assembly
Microsoft.Live.dll

See also

LiveConnectClient class


LiveDownloadOperationResult.LiveDownloadOperationResult(Stream, Object) constructor

Initializes an object that can access the results of a Microsoft SkyDrive file download request.

Syntax

C#
public LiveDownloadOperationResult LiveDownloadOperationResult(
  Stream stream,
  object userState
)

Parameters

stream

Type: Stream

The downloaded file, represented as a file stream.

userState

Type: Object

Any app-supplied info that was supplied to help identify the task that raised this event.

Return value

Type: LiveDownloadOperationResult

An initialized instance of the LiveDownloadOperationResult class.

Requirements

Minimum supported client

 None supported

Minimum supported server

 None supported

Minimum supported phone

 Windows Phone 7

Namespace

Microsoft.Live

Assembly
Microsoft.Live.dll

See also

LiveDownloadOperationResult class


LiveDownloadOperationResult.Stream property

Gets the downloaded file, represented as a file stream.

Syntax

C#
public Stream Stream { get; }

Property value

Type: Stream

The downloaded file, represented as a file stream.

Requirements

Minimum supported client

 None supported

Minimum supported server

 None supported

Minimum supported phone

 Windows Phone 7

Namespace

Microsoft.Live

Assembly
Microsoft.Live.dll

See also

LiveDownloadOperationResult class


LiveDownloadProgressChangedEventArgs class

Raised every time a chunk of data is downloaded during a download operation.

Syntax

C#
public class LiveDownloadProgressChangedEventArgs : ProgressChangedEventArgs

Attributes

None

Members

The LiveDownloadProgressChangedEventArgs class has these types of members:

  • Constructors
  • Properties

Constructors

The LiveDownloadProgressChangedEventArgs class has these constructors.

Constructor | Description
LiveDownloadProgressChangedEventArgs() method | Initializes a new instance of the LiveDownloadProgressChanged class.

Properties

The LiveDownloadProgressChangedEventArgs class has these properties.

Property | Access type | Description
BytesReceived property | Read-only | Gets the bytes received.
TotalBytesToReceive property | Read-only | Gets the total number of bytes in a download operation.

Requirements

Minimum supported client

 None supported

Minimum supported server

 None supported

Minimum supported phone

 Windows Phone 7

Namespace

Microsoft.Live

Assembly
Microsoft.Live.dll


LiveDownloadProgressChangedEventArgs.LiveDownloadProgressChangedEventArgs constructor

Initializes a new instance of the LiveDownloadProgressChanged class.

Syntax

C#
public LiveDownloadProgressChangedEventArgs()

Parameters

This constructor has no parameters.

Requirements

Minimum supported client

 None supported

Minimum supported server

 None supported

Minimum supported phone

 Windows Phone 7

Namespace

Microsoft.Live

Assembly
Microsoft.Live.dll

See also

LiveDownloadProgressChangedEventArgs


LiveDownloadProgressChangedEventArgs.BytesReceived property

Gets the bytes received.

Syntax

C#
public long BytesReceived { get; }

Property value

Type: Int64

BytesReceived

Requirements

Minimum supported client

 None supported

Minimum supported server

 None supported

Minimum supported phone

 Windows Phone 7

Namespace

Microsoft.Live

Assembly
Microsoft.Live.dll

See also

LiveDownloadProgressChangedEventArgs


LiveDownloadProgressChangedEventArgs.TotalBytesToReceive property

Gets the total number of bytes in a download operation.

Syntax

C#
public long TotalBytesToReceive { get; }

Property value

Type: Int64

TotalBytesToReceive

Requirements

Minimum supported client

 None supported

Minimum supported server

 None supported

Minimum supported phone

 Windows Phone 7

Namespace

Microsoft.Live

Assembly
Microsoft.Live.dll

See also

LiveDownloadProgressChangedEventArgs


LiveLoginResult class

Represents a live login.

Syntax

C#
public class LiveLoginResult

Attributes

None

Members

The LiveLoginResult class has these types of members:

  • Constructors
  • Properties

Constructors

The LiveLoginResult class has these constructors.

Constructor | Description
LiveLoginResult(LiveConnectSessionStatus, LiveConnectSession) constructor | Initializes a new instance of LiveLoginResult.

Properties

The LiveLoginResult class has these properties.

Property | Access type | Description
Session | Read-only | The current session for the connected user.
Status | Read-only | Returns the LiveConnectSessionStatus object, which contains current session status for the signed-in user.

Requirements

Minimum supported client

 Windows 8

Minimum supported server

 None supported

Minimum supported phone

 Windows Phone 7

Namespace

Microsoft.Live

Assembly
Microsoft.Live.dll


LiveLoginResult.LiveLoginResult(LiveConnectSessionStatus, LiveConnectSession) constructor

Initializes a new instance of LiveLoginResult.

Syntax

C#
public LoginCompletedEventArgs LiveLoginResult(
  LiveConnectSessionStatus status,
  LiveConnectSession session
)

Parameters

status

Type: LiveConnectSessionStatus

The current user state.

session

Type: LiveConnectSession

The LiveConnectSession object to use.

Return value

Requirements

Minimum supported client

 Windows 8

Minimum supported server

 None supported

Namespace

Microsoft.Live

Assembly
Microsoft.Live.dll

See also

LiveLoginResult


LiveLoginResult.Session property

The current session for the connected user.

Syntax

C#
public LiveConnectSession Session { get; }

Property value

Type: LiveConnectSession

The current session.

Requirements

Minimum supported client

 Windows 8

Minimum supported server

 None supported

Minimum supported phone

 Windows Phone 7

Namespace

Microsoft.Live

Assembly
Microsoft.Live.dll

See also

LiveLoginResult


LiveLoginResult.Status property

Returns the LiveConnectSessionStatus object, which contains current session status for the signed-in user.

Syntax

C#
public LiveConnectSessionStatus Status { get; }

Property value

Type: LiveConnectSessionStatus

The session status.

Requirements

Minimum supported client

 Windows 8

Minimum supported server

 None supported

Minimum supported phone

 Windows Phone 7

Namespace

Microsoft.Live

Assembly
Microsoft.Live.dll

See also

LiveLoginResult


LiveOperationCompletedEventArgs class

Contains event arguments for the events raised when an operation is completed.

Syntax

C#
public class LiveOperationCompletedEventArgs

Attributes

None

Members

The LiveOperationCompletedEventArgs class has these types of members:

  • Constructors
  • Properties

Constructors

The LiveOperationCompletedEventArgs class has these constructors.

Constructor | Description
LiveOperationCompletedEventArgs.LiveOperationCompletedEventArgs(Collections.Generic.IDictionary<String, Object>, String, Object) method | Initializes a new instance of the LiveOperationCompletedEventArgs class.
LiveOperationCompletedEventArgs.LiveOperationCompletedEventArgs(Exception, Boolean, Object) method | Initializes a new instance of the LiveOperationCompletedEventArgs class.

Properties

The LiveOperationCompletedEventArgs class has these properties.

Property | Access type | Description
LiveOperationCompletedEventArgs.RawResult property | Read-only | The raw result of the operation in the requested format.
LiveOperationCompletedEventArgs.Result property | Read-only | The result of the requesting operation.

Requirements

Minimum supported client

 None supported

Minimum supported server

 None supported

Minimum supported phone

 Windows Phone 7

Namespace

Microsoft.Live

Assembly
Microsoft.Live.dll


LiveOperationCompletedEventArgs.LiveOperationCompletedEventArgs constructors

Initializes a new instance of the LiveOperationCompletedEventArgs class.

This member is overloaded. For complete information about this member, including syntax, usage, and examples, click a name in the overload list.

Overload list

Constructor | Description
LiveOperationCompletedEventArgs(Exception, Boolean, Object) | Initializes a new instance of the LiveOperationCompletedEventArgs class.
LiveOperationCompletedEventArgs(IDictionary<string, object>, string, object) | Initializes a new instance of the LiveOperationCompletedEventArgs class.

Requirements

Minimum supported client

 None supported

Minimum supported server

 None supported

Minimum supported phone

 Windows Phone 7

Namespace

Microsoft.Live

Assembly
Microsoft.Live.dll

See also

LiveOperationCompletedEventArgs


LiveOperationCompletedEventArgs.LiveOperationCompletedEventArgs(Exception, Boolean, Object) constructor

Initializes a new instance of the LiveOperationCompletedEventArgs class.

Syntax

C#
public LiveOperationCompletedEventArgs LiveOperationCompletedEventArgs(
  Exception exception,
  bool cancelled,
  object userState
)

Parameters

exception

Type: Exception

The exception object to pass.

cancelled

Type: Boolean

Indicates whether the operation was cancelled.

userState

Type: Object

The current user state.

Return value

Requirements

Minimum supported client

 None supported

Minimum supported server

 None supported

Minimum supported phone

 Windows Phone 7

Namespace

Live

Assembly
Live.dll

See also

LiveOperationCompletedEventArgs
LiveOperationCompletedEventArgs.LiveOperationCompletedEventArgs(IDictionary<String, Object>, String, Object)


LiveOperationCompletedEventArgs.LiveOperationCompletedEventArgs(IDictionary<String, Object>, String, Object) constructor

Initializes a new instance of the LiveOperationCompletedEventArgs class.

Syntax

C#
public LiveOperationCompletedEventArgs LiveOperationCompletedEventArgs(
  IDictionary<String, Object> result,
  string rawResult,
  object userState
)

Parameters

result

Type: IDictionary<String, Object>

An IDictionary that contains the results.

rawResult

Type: String

A string that contains the raw results.

userState

Type: Object

The current user state.

Return value

Requirements

Minimum supported client

 None supported

Minimum supported server

 None supported

Minimum supported phone

 Windows Phone 7

Namespace

Live

Assembly
Live.dll

See also

LiveOperationCompletedEventArgs
LiveOperationCompletedEventArgs(Exception, Boolean, Object)


LiveOperationCompletedEventArgs.RawResult property

The raw result of the operation in the requested format.

Syntax

C#
public string RawResult { get; }

Property value

Type: String

RawResult

Requirements

Minimum supported client

 None supported

Minimum supported server

 None supported

Minimum supported phone

 Windows Phone 7

Namespace

Microsoft.Live

Assembly
Microsoft.Live.dll

See also

LiveOperationCompletedEventArgs


LiveOperationCompletedEventArgs.Result property

The result of the requesting operation.

Syntax

C#
public IDictionary<String, Object> Result { get; }

Property value

Type: IDictionary<String, Object>

Result

Requirements

Minimum supported client

 None supported

Minimum supported server

 None supported

Minimum supported phone

 Windows Phone 7

Namespace

Microsoft.Live

Assembly
Microsoft.Live.dll

See also

LiveOperationCompletedEventArgs


LiveOperationProgress class

Represents the progress of a file upload or download request.

Syntax

C#
public class LiveOperationProgress

Attributes

None

Members

The LiveOperationProgress class has these types of members:

  • Constructors
  • Properties

Constructors

The LiveOperationProgress class has these constructors.

Constructor | Description
LiveOperationProgress Constructor | Initializes a new instance of the LiveOperationProgress class.

Properties

The LiveOperationProgress class has these properties.

Property | Access type | Description
BytesTransferred Property | Read-only | The number of bytes transferred so far.
ProgressPercentage Property | Read-only | The percentage of total bytes transferred so far.
TotalBytes Property | Read-only | The total number of bytes to transfer.

Requirements

Minimum supported client

 Windows 8

Minimum supported server

 None supported

Namespace

Microsoft.Live

Assembly
Microsoft.Live.dll


LiveOperationProgress.BytesTransferred property

The number of bytes transferred so far.

Syntax

C#
public long BytesTransferred { get; }

Property value

Type: long

The number of bytes.

Requirements

Minimum supported client

 Windows 8

Minimum supported server

 None supported

Namespace

Microsoft.Live

Assembly
Microsoft.Live.dll

See also

LiveOperationProgress


LiveOperationProgress.LiveOperationProgress(long, long) constructor

Initializes a new instance of the LiveOperationProgress class.

Syntax

C#
public LiveOperationProgress LiveOperationProgress(
  long bytesTransferred,
  long TotalBytes
)

Parameters

bytesTransferred

Type: long

The number of bytes transferred so far.

TotalBytes

Type: long

The total bytes to transfer.

Return value

Requirements

Minimum supported client

 Windows 8

Minimum supported server

 None supported

Namespace

Live

Assembly
Live.dll

See also

LiveOperationProgress


LiveOperationProgress.ProgressPercentage property

The percentage of total bytes transferred so far.

Syntax

C#
public double ProgressPercentage { get; }

Property value

Type: double

The percentage of total bytes.

Requirements

Minimum supported client

 Windows 8

Minimum supported server

 None supported

Namespace

Microsoft.Live

Assembly
Microsoft.Live.dll

See also

LiveOperationProgress


LiveOperationProgress.TotalBytes property

The total number of bytes to transfer.

Syntax

C#
public long TotalBytes { get; }

Property value

Type: long

The total number of bytes.

Requirements

Minimum supported client

 Windows 8

Minimum supported server

 None supported

Namespace

Microsoft.Live

Assembly
Microsoft.Live.dll

See also

LiveOperationProgress


LiveOperationResult class

Represents the result of the operation.

Syntax

C#
public class LiveOperationResult

Attributes

None

Members

The LiveOperationResult class has these types of members:

  • Constructors
  • Properties

Constructors

The LiveOperationResult class has these constructors.

Constructor | Description
LiveOperationResult(IDictionary<String, Object>, String) | Initializes a new instance of the LiveOperationResult class with the bytes sent, total bytes to send, and user state.

Properties

The LiveOperationResult class has these properties.

Property | Access type | Description
RawResult | Read-only | The raw result of the operation in the requested format.
Result | Read-only | The result of the requesting operation.

Requirements

Minimum supported client

 Windows 8

Minimum supported server

 None supported

Minimum supported phone

 Windows Phone 7

Namespace

Microsoft.Live

Assembly
Microsoft.Live.dll


LiveOperationResult.LiveOperationResult constructor

Initializes a new instance of the LiveOperationResult class with the bytes sent, total bytes to send, and user state.

Syntax

C#
public LiveOperationResult(
  IDictionary<String ,Object> result,
  string rawResult
)

Parameters

result

Type: IDictionary<String ,Object>

The result of the requesting operation.

rawResult

Type: String

The raw result of the operation in the requested format.

Requirements

Minimum supported client

 Windows 8

Minimum supported server

 None supported

Minimum supported phone

 Windows Phone 7

Namespace

Microsoft.Live

Assembly
Microsoft.Live.dll

See also

LiveOperationResult


LiveOperationResult.RawResult property

The raw result of the operation in the requested format.

Syntax

C#
public string RawResult { get; }

Property value

Type: String

The raw result.

Requirements

Minimum supported client

 Windows 8

Minimum supported server

 None supported

Minimum supported phone

 Windows Phone 7

Namespace

Microsoft.Live

Assembly
Microsoft.Live.dll

See also

LiveOperationResult


LiveOperationResult.Result property

The result of the requesting operation.

Syntax

C#
public IDictionary<String ,Object> Result { get; }

Property value

Type: IDictionary<String ,Object>

The result.

Requirements

Minimum supported client

 Windows 8

Minimum supported server

 None supported

Minimum supported phone

 Windows Phone 7

Namespace

Microsoft.Live

Assembly
Microsoft.Live.dll

See also

LiveOperationResult
LiveOperationCompletedEventArgs


LiveUploadProgressChangedEventArgs class

Raised every time a chunk of data is uploaded during an upload operation.

Syntax

C#
public class LiveUploadProgressChangedEventArgs

Attributes

None

Members

The LiveUploadProgressChangedEventArgs class has these types of members:

  • Constructors
  • Properties

Constructors

The LiveUploadProgressChangedEventArgs class has these constructors.

Constructor | Description
LiveUploadProgressChangedEventArgs constructor | Initializes a new instance of the LiveUploadProgressChangedEventArgs class with the bytes sent, total bytes to send, and user state.

Properties

The LiveUploadProgressChangedEventArgs class has these properties.

Property | Access type | Description
BytesSent property | Read-only | Gets the bytes sent.
TotalBytesToSend property | Read-only | Gets the total number of bytes in an upload operation.

Requirements

Minimum supported client

 None supported

Minimum supported server

 None supported

Minimum supported phone

 Windows Phone 7

Namespace

Microsoft.Live

Assembly
Microsoft.Live.dll


LiveUploadProgressChangedEventArgs.LiveUploadProgressChangedEventArgs constructor

Initializes a new instance of the LiveUploadProgressChangedEventArgs class with the bytes sent, total bytes to send, and user state.

Syntax

C#
public LiveUploadProgressChangedEventArgs(
  long bytesSent,
  long totalBytesToSend,
  object userState
)

Parameters

bytesSent

Type: long

The number of bytes sent.

totalBytesToSend

Type: long

The total number of bytes to send.

userState

Type: object

The user state.

Requirements

Minimum supported client

 None supported

Minimum supported server

 None supported

Minimum supported phone

 Windows Phone 7

Namespace

Microsoft.Live

Assembly
Microsoft.Live.dll

See also

LiveUploadProgressChangedEventArgs


LiveUploadProgressChangedEventArgs.BytesSent property

Gets the bytes sent.

Syntax

C#
public long BytesSent { get; }

Property value

Type: Int64

BytesSent

Requirements

Minimum supported client

 None supported

Minimum supported server

 None supported

Minimum supported phone

 Windows Phone 7

Namespace

Microsoft.Live

Assembly
Microsoft.Live.dll

See also

LiveUploadProgressChangedEventArgs


LiveUploadProgressChangedEventArgs.TotalBytesToSend property

Gets the total number of bytes in an upload operation.

Syntax

C#
public long TotalBytesToSend { get; }

Property value

Type: Int64

TotalBytesToSend

Requirements

Minimum supported client

 None supported

Minimum supported server

 None supported

Minimum supported phone

 Windows Phone 7

Namespace

Microsoft.Live

Assembly
Microsoft.Live.dll

See also

LiveUploadProgressChangedEventArgs


LoginCompletedEventArgs class

Contains event arguments for the events raised when login is completed.

Syntax

C#
public class LoginCompletedEventArgs

Attributes

None

Members

The LoginCompletedEventArgs class has these types of members:

  • Constructors
  • Properties

Constructors

The LoginCompletedEventArgs class has these constructors.

Constructor | Description
LoginCompletedEventArgs(Exception, Boolean, Object) | Initializes a new instance of LoginCompletedEventArgs.
LoginCompletedEventArgs(LiveConnectSession, Object) | Initializes a new instance of LoginCompletedEventArgs.

Properties

The LoginCompletedEventArgs class has these properties.

Property | Access type | Description
Session | Read-only | Returns the LiveConnectSession object, which contains login and scope information, and the token information for the signed-in user.
Status | Read-only | Returns the LiveConnectSessionStatus object, which contains current session status for the signed-in user.

Requirements

Minimum supported client

 None supported

Minimum supported server

 None supported

Minimum supported phone

 Windows Phone 7

Namespace

Microsoft.Live

Assembly
Microsoft.Live.dll


LoginCompletedEventArgs.LoginCompletedEventArgs constructors

Initializes a new instance of LoginCompletedEventArgs.

This member is overloaded. For complete information about this member, including syntax, usage, and examples, click a name in the overload list.

Overload list

Constructor | Description
LoginCompletedEventArgs(Exception, Boolean, Object) constructor | Initializes a new instance of LoginCompletedEventArgs.
LoginCompletedEventArgs(LiveConnectSession, Object) constructor | Initializes a new instance of LoginCompletedEventArgs.

Requirements

Minimum supported client

 None supported

Minimum supported server

 None supported

Minimum supported phone

 Windows Phone 7

Namespace

Microsoft.Live

Assembly
Microsoft.Live.dll

See also

LoginCompletedEventArgs


LoginCompletedEventArgs.LoginCompletedEventArgs(Exception, Boolean, Object) constructor

Initializes a new instance of LoginCompletedEventArgs.

Syntax

C#
public LoginCompletedEventArgs LoginCompletedEventArgs(
  Exception error,
  bool cancelled,
  object userState
)

Parameters

error

Type: Exception

The exception object to return if an error occurs.

cancelled

Type: Boolean

Indicates whether the operation was cancelled.

userState

Type: Object

The current user state object.

Return value

Requirements

Minimum supported client

 None supported

Minimum supported server

 None supported

Minimum supported phone

 Windows Phone 7

Namespace

Microsoft.Live

Assembly
Microsoft.Live.dll

See also

LoginCompletedEventArgs
LoginCompletedEventArgs(LiveConnectSession, Object)


LoginCompletedEventArgs.LoginCompletedEventArgs(LiveConnectSession, Object) constructor

Initializes a new instance of LoginCompletedEventArgs.

Syntax

C#
public LoginCompletedEventArgs LoginCompletedEventArgs(
  LiveConnectSession session,
  object userState
)

Parameters

session

Type: LiveConnectSession

The LiveConnectSession object to use.

userState

Type: Object

The current user state.

Return value

Requirements

Minimum supported client

 None supported

Minimum supported server

 None supported

Minimum supported phone

 Windows Phone 7

Namespace

Microsoft.Live

Assembly
Microsoft.Live.dll

See also

LoginCompletedEventArgs
LoginCompletedEventArgs(Exception, Boolean, Object)


LoginCompletedEventArgs.Session property

Returns the LiveConnectSession object, which contains login and scope information, and the token information for the signed-in user.

Syntax

C#
public LiveConnectSession Session { get; }

Property value

Type: LiveConnectSession

Session

Requirements

Minimum supported client

 None supported

Minimum supported server

 None supported

Minimum supported phone

 Windows Phone 7

Namespace

Microsoft.Live

Assembly
Microsoft.Live.dll

See also

LoginCompletedEventArgs


LoginCompletedEventArgs.Status property

Returns the LiveConnectSessionStatus object, which contains current session status for the signed-in user.

Syntax

C#
public LiveConnectSessionStatus Status { get; }

Property value

Type: LiveConnectSessionStatus

Status

Requirements

Minimum supported client

 None supported

Minimum supported server

 None supported

Minimum supported phone

 Windows Phone 7

Namespace

Microsoft.Live

Assembly
Microsoft.Live.dll

See also

LoginCompletedEventArgs


OverwriteOption enumeration

Indicates whether an incoming file that's being uploaded to Microsoft SkyDrive should overwrite an existing file with the same file name in that location.

Syntax

C#
public enum OverwriteOption

Attributes

None

Members

The OverwriteOption enumeration has these members.

Member | Value | Description
DoNotOverwrite | OverwriteOption.DoNotOverwrite | Do not overwrite the existing file.
Overwrite | OverwriteOption.Overwrite | Overwrite the existing file with the incoming file.
Rename | OverwriteOption.Rename | Do not overwrite the existing file. Instead, SkyDrive will assign the incoming file a new file name as it's being downloaded. Note The file renaming pattern that SkyDrive uses may produce unpredictable file names.

Requirements

Minimum supported client

 Windows 8

Minimum supported server

 None supported

Minimum supported phone

 Windows Phone 7

Namespace

Microsoft.Live

Assembly
Microsoft.Live.dll


Microsoft.Live.ThemeType enumeration

Specifies the theme type.

Syntax

C#
public enum ThemeType

Attributes

None

Members

The Microsoft.Live.ThemeType enumeration has these members.

Member | Value | Description
Dark | ThemeType.Dark | Specifies the Dark theme.
Default | ThemeType.Default | Specifies the default theme.
Light | ThemeType.Light | Specifies the Light theme.

Remarks

The theme influences the color of the branding image of the control. If you use the Dark theme, the branding image will be white. If you use the Light theme, the branding image will be black.

If you use a black background for your app, choose the Dark theme. If you use a light background, choose the Light theme.

Requirements

Minimum supported client

 Windows 8

Minimum supported server

 None supported

Namespace

Microsoft.Live

Assembly
Microsoft.Live.dll


Microsoft.Live.Controls namespace

Represents controls to access Live Connect features.

Note All of the following members apply to both Windows 8 and Windows Phone unless otherwise noted.

Members

The Microsoft.Live.Controls namespace has these types of members:

  • Classes
  • Enumerations
  • Events

Classes

The Microsoft.Live.Controls namespace has these classes.

Class | Description
SignInButton class (Windows 8) | A button that can be placed in an app to initiate the process of connecting the app and the user's Microsoft account.
SignInButton class (Windows Phone) | A button that can be placed in an app to initiate the process of connecting the app and the user's Microsoft account.

Enumerations

The Microsoft.Live.Controls namespace has these enumerations.

Enumeration | Description
BrandingType enumeration | Contains the values for the branding types that can be displayed.
ButtonTextType enumeration | The text values that can be displayed in the control.

Events

The Microsoft.Live.Controls namespace has these events.

Event | Description
LiveConnectSessionChangedEventArgs event | Raised every time the session changes.


BrandingType enumeration

Contains the values for the branding types that can be displayed. If "None" is specified, then no icon is displayed.

Syntax

C#
public enum BrandingType

Attributes

()

Members

The BrandingType enumeration has these members.

Member | Value | Description
Hotmail | Hotmail | The Hotmail "envelope" icon.
Messenger | Messenger | The Messenger "buddy" icon.
Skydrive | Skydrive | The SkyDrive "cloud" icon.
Windows | Windows | The Live Connect "flag" icon. This is the default value.

Requirements

Minimum supported client

 Windows 8

Minimum supported server

 None supported

Minimum supported phone

 Windows Phone 7

Namespace

Microsoft.Live.Controls

Assembly
Microsoft.Live.Controls.dll


ButtonTextType enumeration

The text values that can be displayed in the control.

Syntax

C#
public enum ButtonTextType

Attributes

None

Members

The ButtonTextType enumeration has these members.

Member | Value | Description
Connect | Sign in text: Connect; Sign out text: Sign out |
Custom | Sign in text: (app-defined); Sign out text: (app-defined) | Text for the control is taken from the SignInText and SignOutText properties defined on the site. If no values are defined, the default value is used.
Login | Sign in text: Login; Sign out text: Logout |
Signin | Sign in text: Sign in; Sign out text: Sign out | The default value.

Requirements

Minimum supported client

 Windows 8

Minimum supported server

 None supported

Minimum supported phone

 Windows Phone 7

Namespace

Microsoft.Live.Controls

Assembly
Microsoft.Live.Controls.dll


LiveConnectSessionChangedEventArgs class

Raised every time the session changes.

Syntax

C#
public class LiveDownloadSessionChangedEventArgs

Attributes

None

Members

The LiveDownloadSessionChangedEventArgs class has these types of members:

  • Constructors
  • Properties

Constructors

The LiveDownloadSessionChangedEventArgs class has these constructors.

Constructor | Description
LiveConnectSessionChangedEventArgs(LiveConnectSession) constructor | Initializes a new instance of LiveConnectSessionChangedEventArgs.
LiveConnectSessionChangedEventArgs(System.Exception) constructor | Initializes a new instance of LiveConnectSessionChangedEventArgs.

Properties

The LiveDownloadSessionChangedEventArgs class has these properties.

Property | Access type | Description
Error property | Read-only | An Exception instance.
Session property | Read-only | The LiveConnectSession instance.
Status property | Read-only | The LiveConnectSessionStatus for a session.

Requirements

Minimum supported client

 Windows 8

Minimum supported server

 None supported

Minimum supported phone

 Windows Phone 7

Namespace

Microsoft.Live.Controls

Assembly
Microsoft.Live.Controls.dll


LiveConnectSessionChangedEventArgs.LiveConnectSessionChangedEventArgs constructors

Raised every time the session changes.

Overload list

Constructor | Description
LiveConnectSessionChangedEventArgs(Exception) constructor | Initializes a new instance of LiveConnectSessionChangedEventArgs.
LiveConnectSessionChangedEventArgs(LiveConnectSession) constructor | Initializes a new instance of LiveConnectSessionChangedEventArgs.

Requirements

Minimum supported client

 Windows 8

Minimum supported server

 None supported

Minimum supported phone

 Windows Phone 7

Namespace

Microsoft.Live.Controls

Assembly
Microsoft.Live.dll

See also

LiveConnectSessionChangedEventArgs


LiveConnectSessionChangedEventArgs.LiveConnectSessionChangedEventArgs(LiveConnectSession) constructor

Initializes a new instance of LiveConnectSessionChangedEventArgs.

Syntax

C#
LiveConnectSessionChangedEventArgs LiveConnectSessionChangedEventArgs(
  LiveConnectSession newSession
)

Parameters

newSession

Type: LiveConnectSession

The new session instance.

Return value

Type: LiveConnectSessionChangedEventArgs

An initialized instance of the class.

Requirements

Minimum supported client

 Windows 8

Minimum supported server

 None supported

Minimum supported phone

 Windows Phone 7

Namespace

Microsoft.Live.Controls

Assembly
Microsoft.Live.dll

See also

LiveConnectSessionChangedEventArgs
LiveConnectSessionChangedEventArgs(System.Exception)


LiveConnectSessionChangedEventArgs.LiveConnectSessionChangedEventArgs(Exception) constructor

Initializes a new instance of LiveConnectSessionChangedEventArgs.

Syntax

C#
LiveConnectSessionChangedEventArgs LiveConnectSessionChangedEventArgs(
  Exception error
)

Parameters

error

Type: Exception

The error to display.

Return value

Type: LiveConnectSessionChangedEventArgs

An initialized instance of the class.

Requirements

Minimum supported client

 Windows 8

Minimum supported server

 None supported

Minimum supported phone

 Windows Phone 7

Namespace

Microsoft.Live.Controls

Assembly
Microsoft.Live.dll

See also

LiveConnectSessionChangedEventArgs
LiveConnectSessionChangedEventArgs(LiveConnectSession)


LiveConnectSessionChangedEventArgs.Error property

An Exception instance.

Syntax

C#
public System.Exception Error { get; }

Property value

Type: System.Exception

The exception to display.

See also

LiveConnectSessionChangedEventArgs


LiveConnectSessionChangedEventArgs.Session property

The LiveConnectSession instance.

Syntax

C#
public LiveConnectSession Session { get; }

Property value

Type: LiveConnectSession

The LiveConnectSession.

See also

LiveConnectSessionChangedEventArgs


LiveConnectSessionChangedEventArgs.Status property

The LiveConnectSessionStatus for a session.

Syntax

C#
public LiveConnectSessionStatus Status { get; }

Property value

Type: LiveConnectSessionStatus

The LiveConnectSessionStatus.

Requirements

Minimum supported client

 Windows 8

Minimum supported server

 None supported

Minimum supported phone

 Windows Phone 7

Namespace

Microsoft.Live

Assembly
Microsoft.Live.dll

See also

LiveConnectSessionChangedEventArgs


SignInButton class

A button that can be placed in an app to initiate the process of connecting the app and the user's Microsoft account. The button can be in one of two states:

  • Sign in: Either there is no user signed in, or the signed-in user has not given permission to the app. The button shows a localized string that indicates to the user that they can sign in.
  • Sign out: There is a connected user. The button shows a localized string that indicates to the user that they can sign out.

Syntax

C#
public class SignInButton

Attributes

None

Members

The SignInButton class has these types of members:

  • Constructors
  • Events
  • Properties

Constructors

The SignInButton class has these constructors.

Constructor | Description
SignInButton() constructor | Creates a new instance of the SignInButton class.

Events

The SignInButton class has these events.

Event | Description
SessionChanged event | Raises change notifications when the value of the Session property is changed.

Properties

The SignInButton class has these properties.

Property | Access type | Description
Branding property | Read/write | Specifies the type of branding to display on the sign-in button. The brand is the icon and visual theme that is displayed on the button, which relates to one of the following products: Hotmail, Windows Live Messenger, Microsoft SkyDrive, or Live Connect. The brands are defined by the BrandingType enumeration.
ButtonTextProperty property | Read/write | Reserved for system use. Do not use.
Scopes property | Read/write | A list of OAuth scopes that is used in Live sign in. The value of this property cannot include the value offline_access.
ScopesProperty property | Read/write | A dependency property identifier that indicates the OAuth scopes that are used in Live sign in, as specified by the value of the Scopes property.
Session property | Read-only | Identifies the session and specified scope for an authenticated user who is signed in from a particular app.
SignInText property | Read/write | The text to display on the sign-in button before the user signs in. This property is used only if the value of TextType is set to Custom; otherwise, it is ignored.
SignInTextProperty property | Read/write | A dependency property identifier that indicates the text to display on the sign-in button before the user signs in, as specified by the value of the SignInText property.
SignOutText property | Read/write | The text to display on the sign-in button after the user has signed out. This property is used only if the value of TextType is set to Custom; otherwise, it is ignored.
SignOutTextProperty property | Read/write | A dependency property identifier that indicates the text to display on the sign-in button after the user has signed out, as specified by the value of the SignOutText property.
TextType property | Read/write | Specifies the sign-in button text. For each TextType value specified, there is a separate sign-in text and sign-out text.
Theme property | Read/write | Specifies the sign-in button theme.

Remarks

The sign-in coding patterns that are appropriate for Windows Store apps using C# are described in the Guidelines for the Microsoft account sign-in experience.

Requirements

Minimum supported client

 Windows 8

Minimum supported server

 None supported

Namespace

Microsoft.Live.Controls

Assembly
Microsoft.Live.Controls.dll


SignInButton.Branding property

Specifies the type of branding to display on the sign-in button. The brand is the icon and visual theme that is displayed on the button, which relates to one of the following products: Hotmail, Windows Live Messenger, Microsoft SkyDrive, or Live Connect. The brands are defined by the BrandingType enumeration.

Syntax

C#
public BrandingType Branding { get; set; }

Property value

Type: BrandingType

An enumeration that defines the branding themes that can be displayed on the sign-in button.

Remarks

The sign-in coding patterns that are appropriate for Windows Store apps using C# are described in the Guidelines for the Microsoft account sign-in experience.

Requirements

Minimum supported client

 Windows 8

Minimum supported server

 None supported

Namespace

Microsoft.Live.Controls

Assembly
Microsoft.Live.Controls.dll

See also

SignInButton


SignInButton.ButtonTextProperty property

Reserved for system use. Do not use.

Syntax

C#
public DependencyProperty ButtonTextProperty { get; }

Property value

Type: DependencyProperty

The button text property.

Remarks

The sign-in coding patterns that are appropriate for Windows Store apps using C# are described in the Guidelines for the Microsoft account sign-in experience.

Requirements

Minimum supported client

 None supported

Minimum supported server

 None supported

Namespace

Microsoft.Live.Controls

Assembly
Microsoft.Live.Controls.dll

See also

SignInButton


SignInButton.Scopes property

A list of OAuth scopes that is used in Live sign in. The value of this property cannot include the value offline_access. Scopes specify the type of resource data that an app can request from an authenticated user.

Scopes is a dependency property that is backed by ScopesProperty.

Syntax

C#
public string Scopes { get; set; }

Property value

Type: string

A string that specifies the set of scopes for the sign-in process.

Remarks

The sign-in coding patterns that are appropriate for Windows Store apps using C# are described in the Guidelines for the Microsoft account sign-in experience.

Requirements

Minimum supported client

 Windows 8

Minimum supported server

 None supported

Namespace

Microsoft.Live.Controls

Assembly
Microsoft.Live.Controls.dll

See also

SignInButton


SignInButton.ScopesProperty property

A dependency property identifier that indicates the OAuth scopes that are used in Live sign in, as specified by the value of the Scopes property.

Syntax

C#
public DependencyProperty ScopesProperty { get; set; }

Property value

Type: DependencyProperty

A dependency property identifier, which can be set through data binding, styling, and inheritance.

Remarks

The sign-in coding patterns that are appropriate for Windows Store apps using C# are described in the Guidelines for the Microsoft account sign-in experience.

Requirements

Minimum supported client

 Windows 8

Minimum supported server

 None supported

Namespace

Microsoft.Live.Controls

Assembly
Microsoft.Live.Controls.dll

See also

SignInButton


SignInButton.Session property

Identifies the session and specified scope for an authenticated user who is signed in from a particular app.

Syntax

C#
public LiveConnectSession Session { get; }

Property value

Type: LiveConnectSession

The session object.

Remarks

The sign-in coding patterns that are appropriate for Windows Store apps using C# are described in the Guidelines for the Microsoft account sign-in experience.

Requirements

Minimum supported client

 Windows 8

Minimum supported server

 None supported

Namespace

Microsoft.Live.Controls

Assembly
Microsoft.Live.Controls.dll

See also

SignInButton


SignInButton.SessionChanged event

Raises change notifications when the value of the Session property is changed.

Syntax

C#
public event EventHandler<LiveConnectSessionChangedEventArgs> SessionChanged

Event information

Delegate EventHandler<LiveConnectSessionChangedEventArgs>

Remarks

The sign-in coding patterns that are appropriate for Windows Store apps using C# are described in the Guidelines for the Microsoft account sign-in experience.

Requirements

Minimum supported client

 Windows 8

Minimum supported server

 None supported

Namespace

Microsoft.Live.Controls

Assembly
Microsoft.Live.dll

See also

SignInButton


SignInButton.SignInButton constructor

Creates a new instance of the SignInButton class.

Syntax

C#
public SignInButton()

Parameters

This constructor has no parameters.

Remarks

The sign-in coding patterns that are appropriate for Windows Store apps using C# are described in the Guidelines for the Microsoft account sign-in experience.

Requirements

Minimum supported client

 Windows 8

Minimum supported server

 None supported

Namespace

Microsoft.Live.Controls

Assembly
Microsoft.Live.Controls.dll

See also

SignInButton
InitializeComponent


SignInButton.SignInText property

The text to display on the sign-in button before the user signs in. This property is used only if the value of TextType is set to Custom; otherwise, it is ignored.

SignInText is a dependency property that is backed by SignInTextProperty.

Syntax

C#
public string SignInText { get; set; }

Property value

Type: string

A string that represents the button's sign-in text.

Remarks

The sign-in coding patterns that are appropriate for Windows Store apps using C# are described in the Guidelines for the Microsoft account sign-in experience.

Requirements

Minimum supported client

 Windows 8

Minimum supported server

 None supported

Namespace

Microsoft.Live.Controls

Assembly
Microsoft.Live.Controls.dll

See also

SignInButton
SignOutText
TextType


SignInButton.SignInTextProperty property

A dependency property identifier that indicates the text to display on the sign-in button before the user signs in, as specified by the value of the SignInText property.

Syntax

C#
public DependencyProperty SignInTextProperty { get; set; }

Property value

Type: DependencyProperty

A dependency property identifier, which can be set through data binding, styling, and inheritance.

Remarks

The sign-in coding patterns that are appropriate for Windows Store apps using C# are described in the Guidelines for the Microsoft account sign-in experience.

Requirements

Minimum supported client

 Windows 8

Minimum supported server

 None supported

Namespace

Microsoft.Live.Controls

Assembly
Microsoft.Live.Controls.dll

See also

SignInButton
SignInText


SignInButton.SignOutText property

The text to display on the sign-in button after the user has signed out. This property is used only if the value of TextType is set to Custom; otherwise, it is ignored.

SignOutText is a dependency property that is backed by SignOutTextProperty.

Syntax

C#
public string SignOutText { get; set; }

Property value

Type: string

A string that represents the button's sign-out text.

Remarks

The sign-in coding patterns that are appropriate for Windows Store apps using C# are described in the Guidelines for the Microsoft account sign-in experience.

Requirements

Minimum supported client

 Windows 8

Minimum supported server

 None supported

Namespace

Microsoft.Live.Controls

Assembly
Microsoft.Live.Controls.dll

See also

SignInButton
SignInText
TextType


SignInButton.SignOutTextProperty property

A dependency property identifier that indicates the text to display on the sign-in button after the user has signed out, as specified by the value of the SignOutText property.

Syntax

C#
public DependencyProperty SignOutTextProperty { get; set; }

Property value

Type: DependencyProperty

A dependency property identifier, which can be set through data binding, styling, and inheritance.

Remarks

The sign-in coding patterns that are appropriate for Windows Store apps using C# are described in the Guidelines for the Microsoft account sign-in experience.

Requirements

Minimum supported client

 Windows 8

Minimum supported server

 None supported

Namespace

Microsoft.Live.Controls

Assembly
Microsoft.Live.Controls.dll

See also

SignInButton
SignOutText


SignInButton.TextType property

Specifies the sign-in button text. For each TextType value specified, there is a separate sign-in text and sign-out text. The values can be Signin (the default), Login, Connect, or Custom (for user-defined text).

TextType is a dependency property that is backed by ButtonTextType.

Value | Sign in text | Sign out text | Description
Signin | Sign in | Sign out | This is the default value.
Login | Log in | Log out |
Connect | Connect | Sign out |
Custom | (user-defined text) | (user-defined text) | The custom text string is defined on the website. If the website does not specify the custom text string, the default text is used, according to the value of TextType.

Syntax

C#
public ButtonTextType TextType { get; set; }

Property value

Type: ButtonTextType

An enumeration that defines the sign-in button text type.

Remarks

The sign-in coding patterns that are appropriate for Windows Store apps using C# are described in the Guidelines for the Microsoft account sign-in experience.

Requirements

Minimum supported client

 Windows 8

Minimum supported server

 None supported

Namespace

Microsoft.Live.Controls

Assembly
Microsoft.Live.Controls.dll

See also

SignInButton
SignInText
SignOutText


SignInButton.Theme property

Specifies the sign-in button theme.

Syntax

C#
public ThemeType Theme { get; set; }

Property value

Type: ThemeType

An enumeration that defines the sign-in button theme type.

Remarks

The sign-in coding patterns that are appropriate for Windows Store apps using C# are described in the Guidelines for the Microsoft account sign-in experience.

Requirements

Minimum supported client

 Windows 8

Minimum supported server

 None supported

Namespace

Microsoft.Live.Controls

Assembly
Microsoft.Live.Controls.dll

See also

SignInButton


SignInButton class

A button that can be placed in an app to initiate the process of connecting the app and the user's Microsoft account. The button can be in one of two states:

  • Sign in: Either there is no user signed in, or the signed-in user has not given permission to the app. The button shows a localized string that indicates to the user that they can sign in.
  • Sign out: There is a connected user. The button shows a localized string that indicates to the user that they can sign out.

Syntax

C#
public class SignInButton

Attributes

None

Members

The SignInButton class has these types of members:

  • Constructors
  • Events
  • Methods
  • Properties

Constructors

The SignInButton class has these constructors.

Constructor | Description
SignInButton() constructor | Creates a new instance of the SignInButton class.

Events

The SignInButton class has these events.

Event | Description
SessionChanged event | Raises change notifications when the value of the Session property is changed.

Methods

The SignInButton class has these methods. It also inherits methods from the Object class.

Method | Description
InitializeComponent() method | Reserved for system use. Do not use.

Properties

The SignInButton class has these properties.

Property | Access type | Description
Branding property | Read/write | Specifies the type of branding to display on the sign-in button. The brand is the icon and visual theme that is displayed on the button, which relates to one of the following products: Hotmail, Windows Live Messenger, Microsoft SkyDrive, or Live Connect. The brands are defined by the BrandingType enumeration.
BrandingProperty property | Read/write | A dependency property identifier that indicates the type of branding to display on the sign-in button, as specified by the value of the Branding property.
ButtonTextTypeProperty property | Read/write | A dependency property identifier that indicates the type of text displayed on the sign-in button, as specified by the value of the TextType property.
ClientId property | Read/write | Specifies the client ID for the registered app.
ClientIdProperty property | Read/write | A dependency property identifier that indicates the client ID for the registered app, as specified by the value of the ClientId property.
Scopes property | Read/write | A list of OAuth scopes that is used in Live sign in. The value of this property cannot include the value offline_access.
ScopesProperty property | Read/write | A dependency property identifier that indicates the OAuth scopes that are used in Live sign in, as specified by the value of the Scopes property.
Session property | Read-only | Identifies the session and specified scope for an authenticated user who is signed in from a particular app.
SignInText property | Read/write | The text to display on the sign-in button before the user signs in. This property is used only if the value of TextType is set to Custom; otherwise, it is ignored.
SignInTextProperty property | Read/write | A dependency property identifier that indicates the text to display on the sign-in button before the user signs in, as specified by the value of the SignInText property.
SignOutText property | Read/write | The text to display on the sign-in button after the user has signed out. This property is used only if the value of TextType is set to Custom; otherwise, it is ignored.
SignOutTextProperty property | Read/write | A dependency property identifier that indicates the text to display on the sign-in button after the user has signed out, as specified by the value of the SignOutText property.
TextType property | Read/write | Specifies the sign-in button text. For each TextType value specified, there is a separate sign-in text and sign-out text.

Requirements

Minimum supported client

 None supported

Minimum supported server

 None supported

Minimum supported phone

 Windows Phone 7

Namespace

Microsoft.Live.Controls

Assembly
Microsoft.Live.Controls.dll


SignInButton.Branding property

Specifies the type of branding to display on the sign-in button. The brand is the icon and visual theme that is displayed on the button, which relates to one of the following products: Hotmail, Windows Live Messenger, Microsoft SkyDrive, or Live Connect. The brands are defined by the BrandingType enumeration.

Branding is a dependency property that is backed by BrandingProperty.

Syntax

C#
public BrandingType Branding { get; set; }

Property value

Type: BrandingType

An enumeration that defines the branding themes that can be displayed on the sign-in button.

Requirements

Minimum supported client

 None supported

Minimum supported server

 None supported

Minimum supported phone

 Windows Phone 7

Namespace

Microsoft.Live.Controls

Assembly
Microsoft.Live.Controls.dll

See also

SignInButton
BrandingProperty property
BrandingType enumeration


SignInButton.BrandingProperty property

A dependency property identifier that indicates the type of branding to display on the sign-in button, as specified by the value of the Branding property.

Syntax

C#
public DependencyProperty BrandingProperty { get; set; }

Property value

Type: DependencyProperty

A dependency property identifier, which can be set through data binding, styling, and inheritance.

Requirements

Minimum supported client

 None supported

Minimum supported server

 None supported

Minimum supported phone

 Windows Phone 7

Namespace

Microsoft.Live.Controls

Assembly
Microsoft.Live.Controls.dll

See also

SignInButton
Branding


SignInButton.ButtonTextProperty property

Reserved for system use. Do not use.

Syntax

C#
public DependencyProperty ButtonTextProperty { get; }

Property value

Type: DependencyProperty

The button text property .

Requirements

Minimum supported client

 None supported

Minimum supported server

 None supported

Minimum supported phone

 Windows Phone 7

Namespace

Microsoft.Live.Controls

Assembly
Microsoft.Live.Controls.dll

See also

SignInButton


SignInButton.ButtonTextTypeProperty property

A dependency property identifier that indicates the type of text displayed on the sign-in button, as specified by the value of the TextType property.

Syntax

C#
public DependencyProperty ButtonTextTypeProperty { get; set; }

Property value

Type: DependencyProperty

A dependency property identifier, which can be set through data binding, styling, and inheritance.

Requirements

Minimum supported client

 None supported

Minimum supported server

 None supported

Minimum supported phone

 Windows Phone 7

Namespace

Microsoft.Live.Controls

Assembly
Microsoft.Live.Controls.dll

See also

SignInButton
TextType


SignInButton.ClientId property

Specifies the client ID for the registered app.

ClientId is a dependency property that is backed by ClientIdProperty. This property is available only for Windows Phone.

Syntax

C#
public string ClientId { get; set; }

Property value

Type: String

A string that represents the app's client ID.

Requirements

Minimum supported client

 None supported

Minimum supported server

 None supported

Minimum supported phone

 Windows Phone 7

Namespace

Microsoft.Live.Controls

Assembly
Microsoft.Live.Controls.dll

See also

SignInButton


SignInButton.ClientIdProperty property

A dependency property identifier that indicates the client ID for the registered app, as specified by the value of the ClientId property. This property is available only for Windows Phone.

Syntax

C#
public DependencyProperty ClientIdProperty { get; set; }

Property value

Type: DependencyProperty

A dependency property identifier, which can be set through data binding, styling, and inheritance.

Requirements

Minimum supported client

 None supported

Minimum supported server

 None supported

Minimum supported phone

 Windows Phone 7

Namespace

Microsoft.Live.Controls

Assembly
Microsoft.Live.Controls.dll

See also

SignInButton
ClientId


SignInButton.InitializeComponent method

Reserved for system use. Do not use.

Syntax

C#
public InitializeComponent()

Parameters

This method has no parameters.

Requirements

Minimum supported client

 None supported

Minimum supported server

 None supported

Minimum supported phone

 Windows Phone 7

Namespace

Microsoft.Live.Controls

Assembly
Microsoft.Live.Controls.dll

See also

SignInButton


SignInButton.OpacityMaskBrushProperty property

Reserved for system use. Do not use.

Syntax

C#
public DependencyProperty OpacityMaskBrushProperty { get; }

Property value

Type: DependencyProperty

The button opacity mask brush property.

Requirements

Minimum supported client

 None supported

Minimum supported server

 None supported

Minimum supported phone

 Windows Phone 7

Namespace

Microsoft.Live.Controls

Assembly
Microsoft.Live.Controls.dll

See also

SignInButton


SignInButton.Scopes property

A list of OAuth scopes that is used in Live sign in. The value of this property cannot include the value offline_access. Scopes specify the type of resource data that an app can request from an authenticated user.

Scopes is a dependency property that is backed by ScopesProperty.

Syntax

C#
public string Scopes { get; set; }

Property value

Type: string

A string that specifies the set of scopes for the sign-in process.

Requirements

Minimum supported client

 None supported

Minimum supported server

 None supported

Minimum supported phone

 Windows Phone 7

Namespace

Microsoft.Live.Controls

Assembly
Microsoft.Live.Controls.dll

See also

SignInButton


SignInButton.ScopesProperty property

A dependency property identifier that indicates the OAuth scopes that are used in Live sign in, as specified by the value of the Scopes property.

Syntax

C#
public DependencyProperty ScopesProperty { get; set; }

Property value

Type: DependencyProperty

A dependency property identifier, which can be set through data binding, styling, and inheritance.

Requirements

Minimum supported client

 None supported

Minimum supported server

 None supported

Minimum supported phone

 Windows Phone 7

Namespace

Microsoft.Live.Controls

Assembly
Microsoft.Live.Controls.dll

See also

SignInButton
Scopes


SignInButton.Session property

Identifies the session and specified scope for an authenticated user who is signed in from a particular app.

Syntax

C#
public LiveConnectSession Session { get; }

Property value

Type: LiveConnectSession

The session object.

Requirements

Minimum supported client

 None supported

Minimum supported server

 None supported

Minimum supported phone

 Windows Phone 7

Namespace

Microsoft.Live.Controls

Assembly
Microsoft.Live.Controls.dll

See also

SignInButton


SignInButton.SessionChanged event

Raises change notifications when the value of the Session property is changed.

Syntax

C#
public event EventHandler<LiveConnectSessionChangedEventArgs> SessionChanged

Event information

Delegate EventHandler<LiveConnectSessionChangedEventArgs>

Requirements

Minimum supported client

 None supported

Minimum supported server

 None supported

Minimum supported phone

 Windows Phone 7

Namespace

Microsoft.Live.Controls

Assembly
Microsoft.Live.dll

See also

SignInButton


SignInButton.SignInButton constructor

Creates a new instance of the SignInButton class.

Syntax

C#
public SignInButton()

Parameters

This constructor has no parameters.

Requirements

Minimum supported client

 None supported

Minimum supported server

 None supported

Minimum supported phone

 Windows Phone 7

Namespace

Microsoft.Live.Controls

Assembly
Microsoft.Live.Controls.dll

See also

SignInButton
InitializeComponent


SignInButton.SignInText property

The text to display on the sign-in button before the user signs in. This property is used only if the value of TextType is set to Custom; otherwise, it is ignored.

SignInText is a dependency property that is backed by SignInTextProperty.

Syntax

C#
public string SignInText { get; set; }

Property value

Type: string

A string that represents the button's sign-in text.

Requirements

Minimum supported client

 None supported

Minimum supported server

 None supported

Minimum supported phone

 Windows Phone 7

Namespace

Microsoft.Live.Controls

Assembly
Microsoft.Live.Controls.dll

See also

SignInButton
SignOutText
TextType


SignInButton.SignInTextProperty property

A dependency property identifier that indicates the text to display on the sign-in button before the user signs in, as specified by the value of the SignInText property.

Syntax

C#
public DependencyProperty SignInTextProperty { get; set; }

Property value

Type: DependencyProperty

A dependency property identifier, which can be set through data binding, styling, and inheritance.

Requirements

Minimum supported client

 None supported

Minimum supported server

 None supported

Minimum supported phone

 Windows Phone 7

Namespace

Microsoft.Live.Controls

Assembly
Microsoft.Live.Controls.dll

See also

SignInButton
SignInText


SignInButton.SignOutText property

The text to display on the sign-in button after the user has signed out. This property is used only if the value of TextType is set to Custom; otherwise, it is ignored.

SignOutText is a dependency property that is backed by SignOutTextProperty.

Syntax

C#
public string SignOutText { get; set; }

Property value

Type: string

A string that represents the button's sign-out text.

Requirements

Minimum supported client

 None supported

Minimum supported server

 None supported

Minimum supported phone

 Windows Phone 7

Namespace

Microsoft.Live.Controls

Assembly
Microsoft.Live.Controls.dll

See also

SignInButton
SignInText
TextType


SignInButton.SignOutTextProperty property

A dependency property identifier that indicates the text to display on the sign-in button after the user has signed out, as specified by the value of the SignOutText property.

Syntax

C#
public DependencyProperty SignOutTextProperty { get; set; }

Property value

Type: DependencyProperty

A dependency property identifier, which can be set through data binding, styling, and inheritance.

Requirements

Minimum supported client

 None supported

Minimum supported server

 None supported

Minimum supported phone

 Windows Phone 7

Namespace

Microsoft.Live.Controls

Assembly
Microsoft.Live.Controls.dll

See also

SignInButton
SignOutText


SignInButton.TextType property

Specifies the sign-in button text. For each TextType value specified, there is a separate sign-in text and sign-out text. The values can be Signin (the default), Login, Connect, or Custom (for user-defined text).

TextType is a dependency property that is backed by ButtonTextTypeProperty.

Value | Sign in text | Sign out text | Description
Signin | Sign in | Sign out | This is the default value.
Login | Log in | Log out |
Connect | Connect | Sign out |
Custom | (user-defined text) | (user-defined text) | The custom text string is defined on the website. If the website does not specify the custom text string, the default text is used, according to the value of TextType.

Syntax

C#
public ButtonTextType TextType { get; set; }

Property value

Type: ButtonTextType

An enumeration that defines the sign-in button text type.

Requirements

Minimum supported client

 None supported

Minimum supported server

 None supported

Minimum supported phone

 Windows Phone 7

Namespace

Microsoft.Live.Controls

Assembly
Microsoft.Live.Controls.dll

See also

SignInButton
SignInText
SignOutText


iOS API

Provides a set of enumerations, interfaces, and protocols to simplify calling the Live Connect Representational State Transfer (REST) APIs from iOS apps.

Enumerations

Name | Description
LiveConnectSessionStatus | Specifies the status of an operation.
LiveUploadOverwriteOption | Specifies the overwrite behavior for an incoming file that's uploaded to Microsoft SkyDrive when a file with the same name already exists in the same upload location.

Classes

Name | Description
LiveConnectClient | Represents a client object that helps the app to access Live Connect on behalf of the user.
LiveConnectSession | Represents the current Live Connect session.
LiveDownloadOperation | Represents data returned from a download call to the Live Connect Representational State Transfer (REST) API.
LiveOperation | Represents an operation that sends a request to Live Connect Representational State Transfer (REST) API.
LiveOperationProgress | Represents an operation progress object that encapsulates the progress information of a running operation.

Protocols

Name | Description
LiveAuthDelegate | Handles callback methods for LiveConnectClient init, logout, and login methods.
LiveDownloadOperationDelegate | Represents the protocol that captures callback handling methods for SkyDrive downloads.
LiveOperationDelegate | Represents the protocol that captures a Live Connect access operation related to callback handling methods.
LiveUploadOperationDelegate | Represents the protocol that captures callback handling methods for SkyDrive upload operations.


LiveAuthDelegate protocol

Handles callback methods for LiveConnectClient init, logout, and login methods.

Signature

@protocol LiveAuthDelegate <NSObject>

Methods

Name | Description
authCompleted:session:userState method | Invoked when the operation completes successfully.
authFailed:userState method | Invoked when the method call fails.

Defined in

LiveAuthDelegate.h

See also

iOS API


LiveAuthDelegate authCompleted:session:userState method

Handles callback methods for LiveConnectClient init, login, and logout methods.

Signature

- (void) authCompleted:(LiveConnectSessionStatus) status
               session:(LiveConnectSession *) session
             userState:(id) userState

Parameters

Name | Datatype | Description
status | LiveConnectSessionStatus | A LiveConnectSessionStatus value that indicates the user current session status. If the Library detects that the user has already consented to the app for the required scopes, the status is "LiveAuthConnected". Otherwise, "LiveAuthNotConnected" or "LiveAuthUnknown" are returned.
session | LiveConnectSession | The current user session (LiveConnectSession) instance will be received, if the user is known by the library as connected (LiveAuthConnected). If the user status is not known as connected (LiveAuthConnected), nil value will be received.
userState | id | An object passed in by the caller to track asynchronous calling context.

Returns

Nothing.

Defined in

LiveAuthDelegate.h

See also

LiveAuthDelegate protocol


LiveAuthDelegate authFailed:userState method

Invoked when the method call fails.

Signature

- (void) authFailed: (NSError *) error
          userState: (id)userState;

Parameters

Name | Datatype | Description
error | NSError * | The error.
userState | id | An arbitrary object that is used to determine the caller of the method.

Returns

Nothing.

Defined in

LiveAuthDelegate.h

See also

LiveAuthDelegate protocol


LiveConnectClient class

Represents a client object that helps the app to access Live Connect on behalf of the user. LiveConnectClient provides two groups of methods: authentication/authorization methods, and data access methods. The authentication/authorization methods include init* methods, login* methods and logout* methods. The data access methods include get* methods, delete* methods, post* methods, put* methods, copy* methods, move* methods, upload* methods and download* methods.

Signature

@interface LiveConnectClient : NSObject

Properties

Name | Description
LiveConnectClient session property | Gets the Live Connect session for this LiveConnectClient.

Methods

Name | Description
LiveConnectClient copyFromPath:toDestination:delegate method | Performs an asynchronous copy of a file with a given path and destination to a different folder on the user's SkyDrive account. The method also has the option of specifying a LiveOperationDelegate.
LiveConnectClient copyFromPath:toDestination:delegate:userState method | Performs an asynchronous copy of a file with a given path and destination to a different folder on the user's SkyDrive account. The method also has the option of specifying a LiveOperationDelegate and user state.
LiveConnectClient deleteWithPath:delegate method | Performs an asynchronous delete of a file with a given path. The method also has the option of specifying a LiveOperationDelegate.
LiveConnectClient deleteWithPath:delegate:userState method | Performs an asynchronous delete of a file with a given path. The method also has the option of specifying a LiveOperationDelegate and user state.
LiveConnectClient downloadFromPath:delegate method | Performs an asynchronous download of a file with a given path from the user's SkyDrive account. The method also has the option of specifying a LiveDownloadOperationDelegate.
LiveConnectClient downloadFromPath:delegate:userState method | Performs an asynchronous download of a file with a given path from the user's SkyDrive account. The method also has the option of specifying a LiveDownloadOperationDelegate and a user state.
LiveConnectClient getWithPath:delegate method | Performs an asynchronous get of a file with a given path from the user's SkyDrive account. The method also has the option of specifying a LiveOperationDelegate.
LiveConnectClient getWithPath:delegate:userState method | Performs an asynchronous get of a file with a given path from the user's SkyDrive account. The method also has the option of specifying a LiveOperationDelegate and a user state.
LiveConnectClient initWithClientId:delegate method | Performs an asynchronous initialize of a new instance of the LiveConnectClient class with a client ID, and optionally, a LiveAuthDelegate.
LiveConnectClient initWithClientId:delegate:userState method | Performs an asynchronous initialize of a new instance of the LiveConnectClient class with a client ID, and optionally, a LiveAuthDelegate and user state.
LiveConnectClient initWithClientId:scopes:delegate method | Performs an asynchronous initialize of a new instance of the LiveConnectClient class with a client ID, scopes, and optionally, a LiveAuthDelegate.
LiveConnectClient initWithClientId:scopes:delegate:userState method | Performs an asynchronous initialize of a new instance of the LiveConnectClient class with a client ID, scopes, and optionally, a LiveAuthDelegate and a user state.
LiveConnectClient login:delegate method | Performs an asynchronous login by presenting a modal window and showing login and authorization forms so that the user can login with his/her Microsoft account and authorize the app to access the Live Connect services on his/her behalf. This method optionally provides an LiveAuthDelegate.
LiveConnectClient login:delegate:userState method | Performs an asynchronous login by presenting a modal window and showing login and authorization forms so that the user can login with his/her Microsoft account and authorize the app to access the Live Connect services on his/her behalf. This method optionally provides an LiveAuthDelegate and user state.
LiveConnectClient login:scopes:delegate method | Performs an asynchronous login by presenting a modal window and showing login and authorization forms so that the user can login with his/her Microsoft account and authorize the app to access the Live Connect services on his/her behalf. This method optionally provides scopes and a LiveAuthDelegate.
LiveConnectClient login:scopes:delegate:userState method | Performs an asynchronous login by presenting a modal window and showing login and authorization forms so that the user can login with his/her Microsoft account and authorize the app to access the Live Connect services on his/her behalf. This method optionally provides an LiveAuthDelegate and user state.
LiveConnectClient logout method | Performs an asynchronous logout of the user from the app.
LiveConnectClient logoutWithDelegate:userState method | Performs an asynchronous logout of the user from the app with an optional LiveAuthDelegate and user state.
LiveConnectClient moveFromPath:toDestination:delegate method | Performs an asynchronous move of a resource to a different folder on the user's SkyDrive account for a given path, destination, and optionally, a LiveOperationDelegate.
LiveConnectClient moveFromPath:toDestination:delegate:userState method | Performs an asynchronous move of a resource to a different folder on the user's SkyDrive account for a given path, destination, and optionally, a LiveOperationDelegate and user state.
LiveConnectClient postWithPath:dictBody:delegate method | Performs an asynchronous post for a given path, a message request body, and optionally, a LiveOperationDelegate.
LiveConnectClient postWithPath:dictBody:delegate:userState method | Performs an asynchronous post for a given path, a message request body, and optionally, a LiveOperationDelegate and user state.
LiveConnectClient postWithPath:jsonBody:delegate method | Performs an asynchronous post for a given path, a JSON message request body, and optionally, a LiveOperationDelegate.
LiveConnectClient postWithPath:jsonBody:delegate:userState method | Performs an asynchronous post for a given path, a JSON message request body, and optionally, a LiveOperationDelegate and user state.
LiveConnectClient putWithPath:dictBody:delegate method | Performs an asynchronous PUT that updates a resource with a given path, message request body, and optionally, a LiveOperationDelegate. If the resource does not exist, it creates a new one.
LiveConnectClient putWithPath:dictBody:delegate:userState method | Performs an asynchronous PUT that updates a resource with a given path, message request body, and optionally, a LiveOperationDelegate and user state. If the resource does not exist, it creates a new one.
LiveConnectClient putWithPath:jsonBody:delegate method | Performs an asynchronous PUT that updates a resource with a given path, JSON message request body, and optionally, a LiveOperationDelegate. If the resource does not exist, it creates a new one.
LiveConnectClient putWithPath:jsonBody:delegate:userState method | Performs an asynchronous PUT that updates a resource with a given path, JSON message request body, and optionally, a LiveOperationDelegate and user state. If the resource does not exist, it creates a new one.
LiveConnectClient uploadToPath:fileName:data:delegate method | Performs an asynchronous upload of a resource to a user's SkyDrive account. This method uses a given path, file name, file data, and optionally, a LiveUploadOperationDelegate.
LiveConnectClient uploadToPath:fileName:data:overwrite:delegate:userState method | Performs an asynchronous upload of a resource to a user's SkyDrive account. This method uses a given path, file name, file data, and optionally, a LiveUploadOperationDelegate, user state, and an option to overwrite an existing file.
LiveConnectClient uploadToPath:fileName:inputStream:delegate method | Performs an asynchronous upload of a resource to a user's SkyDrive account. This method uses a given path, file name, input stream, and optionally, a LiveUploadOperationDelegate.
LiveConnectClient uploadToPath:fileName:inputStream:overwrite:delegate:userState method | Performs an asynchronous upload of a resource to a user's SkyDrive account. This method uses a given path, file name, input stream, and optionally, a LiveUploadOperationDelegate, user state, and an option to overwrite an existing file.

Defined in

LiveConnectClient.h

See also

iOS API


LiveConnectClient copyFromPath:toDestination:delegate method

Performs an asynchronous copy of a file with a given path and destination to a different folder on the user's Microsoft SkyDrive account. The method also has the option of specifying a LiveOperationDelegate.

Signature

- (LiveOperation *) copyFromPath:(NSString *)path
                   toDestination:(NSString *)destination
                        delegate:(id <LiveOperationDelegate>)delegate;

Parameters

Name | Datatype | Description
path | NSString | Required. The path or object ID of the resource to copy.
destination | NSString | Required. The object ID of the destination folder for the resource being copied.
delegate | id <LiveOperationDelegate> | Optional. An instance of a class that implements the LiveOperationDelegate protocol.

Returns

Type: LiveOperation

The asynchronous operation that is used to track the asynchronous Representational State Transfer (REST) API request and get response data once the operation completes.

Defined in

LiveConnectClient.h

Remarks

This is a helper function that makes calls using HTTP COPY to the Live Connect Representational State Transfer (REST) API.

See also

LiveConnectClient class


LiveConnectClient copyFromPath:toDestination:delegate:userState method

Performs an asynchronous copy of a file with a given path and destination to a different folder on the user's Microsoft SkyDrive account. The method also has the option of specifying a LiveOperationDelegate and user state.

Signature

- (LiveOperation *) copyFromPath:(NSString *)path
                   toDestination:(NSString *)destination
                        delegate:(id <LiveOperationDelegate>)delegate
                       userState:(id)userState;

Parameters

Name | Datatype | Description
path | NSString | Required. The path or object ID of the resource to copy.
destination | NSString | Required. The object ID of the destination folder for the resource being copied.
delegate | id <LiveOperationDelegate> | Optional. An instance of a class that implements the LiveOperationDelegate protocol.
userState | id | Optional. An object that is used to track the asynchronous state. The userState object is found in the userState property of the LiveOperation instance that is passed as a parameter when a LiveOperationDelegate protocol method is invoked.

Returns

Type: LiveOperation

The asynchronous operation that is used to track the asynchronous Representational State Transfer (REST) API request and get response data once the operation completes.

Defined in

LiveConnectClient.h

Remarks

This is a helper function that makes calls using HTTP COPY to the Live Connect Representational State Transfer (REST) API.

See also

LiveConnectClient class


LiveConnectClient deleteWithPath:delegate method

Performs an asynchronous delete of a file with a given path. The method also has the option of specifying a LiveOperationDelegate.

Signature

- (LiveOperation *) deleteWithPath:(NSString *)path
                          delegate:(id <LiveOperationDelegate>)delegate;

Parameters

Name | Datatype | Description
path | NSString | Required. The path or object ID of the resource to delete.
delegate | id <LiveOperationDelegate> | Optional. An instance of a class that implements the LiveOperationDelegate protocol.

Returns

Type: LiveOperation

The asynchronous operation that is used to track the asynchronous Representational State Transfer (REST) API request and get response data once the operation completes.

Defined in

LiveConnectClient.h

Remarks

This is a helper function that makes calls using HTTP DELETE to the Live Connect Representational State Transfer (REST) API.

See also

LiveConnectClient class


LiveConnectClient deleteWithPath:delegate:userState method

Performs an asynchronous delete of a file with a given path. The method also has the option of specifying a LiveOperationDelegate and user state.

Signature

- (LiveOperation *) deleteWithPath:(NSString *)path
                          delegate:(id <LiveOperationDelegate>)delegate
                         userState:(id)userState;

Parameters

Name | Datatype | Description
path | NSString | Required. The path or object ID of the resource to delete.
delegate | id <LiveOperationDelegate> | Optional. An instance of a class that implements the LiveOperationDelegate protocol.
userState | id | Optional. An object that is used to track the asynchronous state. The userState object is found in the userState property of the LiveOperation instance that is passed as a parameter when a LiveOperationDelegate protocol method is invoked.

Returns

Type: LiveOperation

The asynchronous operation that is used to track the asynchronous Representational State Transfer (REST) API request and get response data once the operation completes.

Defined in

LiveConnectClient.h

Remarks

This is a helper function that makes calls using HTTP DELETE to the Live Connect Representational State Transfer (REST) API.

See also

LiveConnectClient class


LiveConnectClient downloadFromPath:delegate method

Performs an asynchronous download of a file with a given path from the user's Microsoft SkyDrive account. The method also has the option of specifying a LiveDownloadOperationDelegate.

Signature

- (LiveDownloadOperation *) downloadFromPath:(NSString *)path
                                    delegate:(id <LiveDownloadOperationDelegate>)delegate;

Parameters

Name | Datatype | Description
path | NSString | Required. The path or object ID of the resource to download.
delegate | id <LiveDownloadOperationDelegate> | Optional. An instance of a class that implements the LiveDownloadOperationDelegate protocol.

Returns

Type: LiveDownloadOperation

The asynchronous operation that is used to track the asynchronous download request from the SkyDrive service and get response data once the operation completes.

Defined in

LiveConnectClient.h

See also

LiveConnectClient class


LiveConnectClient downloadFromPath:delegate:userState method

Performs an asynchronous download of a file with a given path from the user's Microsoft SkyDrive account. The method also has the option of specifying a LiveDownloadOperationDelegate and a user state.

Signature

- (LiveDownloadOperation *) downloadFromPath:(NSString *)path
                                    delegate:(id <LiveDownloadOperationDelegate>)delegate
                                   userState:(id)userState;

Parameters

Name | Datatype | Description
path | NSString | Required. The path or object ID of the resource to download.
delegate | id <LiveDownloadOperationDelegate> | Optional. An instance of a class that implements the LiveDownloadOperationDelegate protocol.
userState | id | Optional. An object that is used to track the asynchronous state. The userState object is found in the userState property of the LiveDownloadOperation instance that is passed as a parameter when a LiveDownloadOperationDelegate protocol method is invoked.

Returns

Type: LiveDownloadOperation

The asynchronous operation that is used to track the asynchronous download request from the SkyDrive service and get response data once the operation completes.

Defined in

LiveConnectClient.h

See also

LiveConnectClient class


LiveConnectClient getWithPath:delegate method

Performs an asynchronous get of a file with a given path from the user's Microsoft SkyDrive account. The method also has the option of specifying a LiveOperationDelegate.

Signature

- (LiveOperation *) getWithPath:(NSString *)path
                       delegate:(id <LiveOperationDelegate>)delegate;

Parameters

Name | Datatype | Description
path | NSString | Required. The path or object ID of the resource to send a GET request.
delegate | id <LiveOperationDelegate> | Optional. An instance of a class that implements the LiveOperationDelegate protocol.

Returns

Type: LiveOperation

The asynchronous operation that is used to track the asynchronous Representational State Transfer (REST) API request and get response data once the operation completes.

Defined in

LiveConnectClient.h

Remarks

This is a helper function that makes calls using HTTP GET to the Live Connect Representational State Transfer (REST) API.

See also

LiveConnectClient class


LiveConnectClient getWithPath:delegate:userState method

Performs an asynchronous get of a file with a given path from the user's Microsoft SkyDrive account. The method also has the option of specifying a LiveOperationDelegate and a user state.

Signature

- (LiveOperation *) getWithPath:(NSString *)path
                       delegate:(id <LiveOperationDelegate>)delegate
                      userState:(id)userState;

Parameters

Name | Datatype | Description
path | NSString | Required. The path or object ID of the resource to send a GET request.
delegate | id <LiveOperationDelegate> | Optional. An instance of a class that implements the LiveOperationDelegate protocol.
userState | id | Optional. An object that is used to track the asynchronous state. The userState object is found in the userState property of the LiveOperation instance that is passed as a parameter when a LiveOperationDelegate protocol method is invoked.

Returns

Type: LiveOperation

The asynchronous operation that is used to track the asynchronous Representational State Transfer (REST) API request and get response data once the operation completes.

Defined in

LiveConnectClient.h

Remarks

This is a helper function that makes calls using HTTP GET to the Live Connect Representational State Transfer (REST) API.

See also

LiveConnectClient class


LiveConnectClient initWithClientId:delegate method

Performs an asynchronous initialize of a new instance of the LiveConnectClient class with a client ID, and optionally, a LiveAuthDelegate.

Signature

- (id) initWithClientId:(NSString *)clientId
               delegate:(id<LiveAuthDelegate>)delegate;

Parameters

Name | Datatype | Description
clientId | NSString | Required. The client ID value of the app when registered on https://manage.dev.live.com.
delegate | id<LiveAuthDelegate> | Optional. An app class instance that implements the LiveAuthDelegate protocol.

Returns

Nothing.

Defined in

LiveConnectClient.h

Remarks

An instance of the LiveConnectClient class must be initialized before other methods can be invoked. Invoking any methods other than init* on an uninitialized instance results in an exception. If an init* method is used on an instance of the LiveConnectClient class that is already initialized, it is silently ignored.

The initialization process retrieves the user authentication session using a refresh token that persisted in the device, if available.

See also

LiveConnectClient class


LiveConnectClient initWithClientId:delegate:userState method

Performs an asynchronous initialize of a new instance of the LiveConnectClient class with a client ID, and optionally, a LiveAuthDelegate and user state.

Signature

- (id) initWithClientId:(NSString *)clientId
               delegate:(id<LiveAuthDelegate>)delegate
              userState:(id)userState;

Parameters

Name | Datatype | Description
clientId | NSString | Required. The client ID value of the app when registered on https://manage.dev.live.com.
delegate | id<LiveAuthDelegate> | Optional. An app class instance that implements the LiveAuthDelegate protocol.
userState | id | Optional. An object that is used to track the asynchronous state. The userState object is found in the userState property of the LiveOperation instance that is passed as a parameter when a LiveOperationDelegate protocol method is invoked. Optional. An app class instance that implements the LiveAuthDelegate protocol.

Returns

Nothing.

Defined in

LiveConnectClient.h

Remarks

An instance of the LiveConnectClient class must be initialized before other methods can be invoked. Invoking any methods other than init* on an uninitialized instance results in an exception. If an init* method is used on an instance of the LiveConnectClient class that is already initialized, it is silently ignored.

The initialization process retrieves the user authentication session using a refresh token that persisted in the device, if available.

See also

LiveConnectClient class


LiveConnectClient initWithClientId:scopes:delegate method

Performs an asynchronous initialize of a new instance of the LiveConnectClient class with a client ID, scopes, and optionally, a LiveAuthDelegate.

Signature

- (id) initWithClientId:(NSString *)clientId
                 scopes:(NSArray *)scopes
               delegate:(id<LiveAuthDelegate>)delegate;

Parameters

Name | Datatype | Description
clientId | NSString | Required. The client ID value of the app when registered on https://manage.dev.live.com.
scopes | NSArray | Optional. An array of scope values that determines the initialization scopes. Note The app may retrieve the app session during the initialization process. The scopes value is passed to the Live authentication server, which returns a user session with an access token if the authenticated user has already given consent for the scopes passed in to the app. Otherwise, the server rejects the request to send back authentication session data.
delegate | id<LiveAuthDelegate> | Optional. An app class instance that implements the LiveAuthDelegate protocol.

Returns

Nothing.

Defined in

LiveConnectClient.h

Remarks

An instance of the LiveConnectClient class must be initialized before other methods can be invoked. Invoking any methods other than init* on an uninitialized instance results in an exception. If an init* method is used on an instance of the LiveConnectClient class that is already initialized, it is silently ignored.

The initialization process retrieves the user authentication session using a refresh token that persisted in the device, if available.

See also

LiveConnectClient class


LiveConnectClient initWithClientId:scopes:delegate:userState method

Performs an asynchronous initialize of a new instance of the LiveConnectClient class with a client ID, a scopes, and optionally, a LiveAuthDelegate and a user state.

Signature

- (id) initWithClientId:(NSString *)clientId
                 scopes:(NSArray *)scopes
               delegate:(id<LiveAuthDelegate>)delegate
              userState:(id)userState;

Parameters

Name | Datatype | Description
clientId | NSString | Required. The client ID value of the app when registered on https://manage.dev.live.com.
scopes | NSArray | Optional. An array of scope values that determines the initialization scopes. Note The app may retrieve the app session during the initialization process. The scopes value is passed to the Live authentication server, which returns a user session with an access token if the authenticated user has already given consent for the scopes passed in to the app. Otherwise, the server rejects the request to send back authentication session data.
delegate | id<LiveAuthDelegate> | Optional. An app class instance that implements the LiveAuthDelegate protocol.
userState | id | Optional. An object that is used to track the asynchronous state. The userState object is passed as a userState parameter when any LiveAuthDelegate protocol method is invoked. Optional. An app class instance that implements the LiveAuthDelegate protocol.

Returns

Nothing.

Defined in

LiveConnectClient.h

Remarks

An instance of the LiveConnectClient class must be initialized before other methods can be invoked. Invoking any methods other than init* on an uninitialized instance results in an exception. If an init* method is used on an instance of the LiveConnectClient class that is already initialized, it is silently ignored.

The initialization process retrieves the user authentication session using a refresh token that persisted in the device, if available.

See also

LiveConnectClient class


LiveConnectClient login:delegate method

Performs an asynchronous login by presenting a modal window and showing login and authorization forms so that the user can log in using a Microsoft account and authorize the app to access the Live Connect services on the user's behalf. This method optionally provides an LiveAuthDelegate.

Signature

- (void) login:(UIViewController *)currentViewController
      delegate:(id<LiveAuthDelegate>)delegate;

Parameters

Name | Datatype | Description
currentViewController | UIViewController | Required. The current UIViewController that presents the login UI in a modal window.
delegate | id<LiveAuthDelegate> | Optional. An app class instance that implements the LiveAuthDelegate protocol.

Returns

Nothing.

Defined in

LiveConnectClient.h

Remarks

If the current user session already satisfies the scopes specified in the parameter, the delegate method authCompleted:session:userState is invoked right away. At any time, only one login* method can be invoked. If there is a pending login* process ongoing, a call to a login* method receives an exception.

See also

LiveConnectClient class


LiveConnectClient login:delegate:userState method

Performs an asynchronous login by presenting a modal window and showing login and authorization forms so that the user can log in using a Microsoft account and authorize the app to access the Live Connect services on the user's behalf. This method optionally provides an LiveAuthDelegate and user state.

Signature

- (void) login:(UIViewController *)currentViewController
      delegate:(id<LiveAuthDelegate>)delegate
     userState:(id)userState;

Parameters

Name | Datatype | Description
currentViewController | UIViewController | Required. The current UIViewController that presents the login UI in a modal window.
delegate | id<LiveAuthDelegate> | Optional. An app class instance that implements the LiveAuthDelegate protocol.
userState | id | Optional. An object that is used to track the asynchronous state. The userState object is passed as a userState parameter when any LiveAuthDelegate protocol method is invoked. Optional. An app class instance that implements the LiveAuthDelegate protocol.

Returns

Nothing.

Defined in

LiveConnectClient.h

Remarks

If the current user session already satisfies the scopes specified in the parameter, the delegate method authCompleted:session:userState is invoked right away. At any time, only one login* method can be invoked. If there is a pending login* process ongoing, a call to a login* method receives an exception.

See also

LiveConnectClient class


LiveConnectClient login:scopes:delegate method

Performs an asynchronous login by presenting a modal window and showing login and authorization forms so that the user can log in using a Microsoft account and authorize the app to access the Live Connect services on the user's behalf. This method optionally provides scopes and a LiveAuthDelegate.

Signature

- (void) login:(UIViewController *)currentViewController
        scopes:(NSArray *)scopes
      delegate:(id<LiveAuthDelegate>)delegate;

Parameters

Name | Datatype | Description
currentViewController | UIViewController | Required. The current UIViewController that presents the login UI in a modal window.
scopes | NSArray | Optional. An array of scope values that determines the initialization scopes. Note The app may retrieve the app session during the initialization process. The scopes value is passed to the Live authentication server, which returns a user session with an access token if the authenticated user has already given consent for the scopes passed in to the app. Otherwise, the server rejects the request to send back authentication session data.
delegate | id<LiveAuthDelegate> | Optional. An app class instance that implements the LiveAuthDelegate protocol.

Returns

Nothing.

Defined in

LiveConnectClient.h

Remarks

If the current user session already satisfies the scopes specified in the parameter, the delegate method authCompleted:session:userState is invoked right away. At any time, only one login* method can be invoked. If there is a pending login* process ongoing, a call to a login* method receives an exception.

See also

LiveConnectClient class


LiveConnectClient login:scopes:delegate:userState method

Performs an asynchronous login by presenting a modal window and showing login and authorization forms so that the user can log in using a Microsoft account and authorize the app to access the Live Connect services on the user's behalf. This method optionally provides an LiveAuthDelegate and user state.

Signature

- (void) login:(UIViewController *)currentViewController
        scopes:(NSArray *)scopes
      delegate:(id<LiveAuthDelegate>)delegate
     userState:(id)userState;

Parameters

Name | Datatype | Description
currentViewController | UIViewController | Required. The current UIViewController that presents the login UI in a modal window.
scopes | NSArray | Optional. An array of scope values that determines the initialization scopes. Note The app may retrieve the app session during the initialization process. The scopes value is passed to the Live authentication server, which returns a user session with an access token if the authenticated user has already given consent for the scopes passed in to the app. Otherwise, the server rejects the request to send back authentication session data.
delegate | id<LiveAuthDelegate> | Optional. An app class instance that implements the LiveAuthDelegate protocol.
userState | id | Optional. An object that is used to track the asynchronous state. The userState object is passed as a userState parameter when any LiveAuthDelegate protocol method is invoked. Optional. An app class instance that implements the LiveAuthDelegate protocol.

Returns

Nothing.

Defined in

LiveConnectClient.h

Remarks

If the current user session already satisfies the scopes specified in the parameter, the delegate method authCompleted:session:userState is invoked right away. At any time, only one login* method can be invoked. If there is a pending login* process ongoing, a call to a login* method receives an exception.

See also

LiveConnectClient class


LiveConnectClient logout method

Performs an asynchronous logout of the user from the app.

Signature

- (void) logout;

Parameters

This method has no parameters.

Returns

Nothing.

Defined in

LiveConnectClient.h

See also

LiveConnectClient class


LiveConnectClient logoutWithDelegate:userState method

Performs an asynchronous logout of the user from the app with an optional LiveAuthDelegate and user state.

Signature

- (void) logoutWithDelegate:(id<LiveAuthDelegate>)delegate
                  userState:(id)userState;

Parameters

Name | Datatype | Description
delegate | id<LiveAuthDelegate> | Optional. An app class instance that implements the LiveAuthDelegate protocol.
userState | id | Optional. An object that is used to track the asynchronous state. The userState object is passed as a userState parameter when any LiveAuthDelegate protocol method is invoked. Optional. An app class instance that implements the LiveAuthDelegate protocol.

Returns

Nothing.

Defined in

LiveConnectClient.h

See also

LiveConnectClient class


LiveConnectClient moveFromPath:toDestination:delegate method

Performs an asynchronous move of a resource to a different folder on the user's Microsoft SkyDrive account for a given path, destination, and optionally, a LiveOperationDelegate.

Signature

- (LiveOperation *) moveFromPath:(NSString *)path
                   toDestination:(NSString *)destination
                        delegate:(id <LiveOperationDelegate>)delegate;

Parameters

Name | Datatype | Description
path | NSString | Required. The path or object ID of the resource to move.
destination | NSString | Required. The object ID of the destination folder for the resource being moved.
delegate | id <LiveOperationDelegate> | Optional. An instance of a class that implements the LiveOperationDelegate protocol.

Returns

Type: LiveOperation

The asynchronous operation that is used to track the asynchronous Representational State Transfer (REST) API request and get response data once the operation completes.

Defined in

LiveConnectClient.h

Remarks

This method uses an HTTP MOVE call to the Live Connect Representational State Transfer (REST) API.

See also

LiveConnectClient class


LiveConnectClient moveFromPath:toDestination:delegate:userState method

Performs an asynchronous move of a resource to a different folder on the user's Microsoft SkyDrive account for a given path, destination, and optionally, a LiveOperationDelegate and user state.

Signature

- (LiveOperation *) moveFromPath:(NSString *)path
                   toDestination:(NSString *)destination
                        delegate:(id <LiveOperationDelegate>)delegate
                       userState:(id)userState;

Parameters

Name | Datatype | Description
path | NSString | Required. The path or object ID of the resource to move.
destination | NSString | Required. The object ID of the destination folder for the resource being moved.
delegate | id <LiveOperationDelegate> | Optional. An instance of a class that implements the LiveOperationDelegate protocol.
userState | id | Optional. An object that is used to track the asynchronous state. The userState object is found in the userState property of the LiveOperation instance that is passed as a parameter when a LiveOperationDelegate protocol method is invoked.

Returns

Type: LiveOperation

The asynchronous operation that is used to track the asynchronous Representational State Transfer (REST) API request and get response data once the operation completes.

Defined in

LiveConnectClient.h

Remarks

This method uses an HTTP MOVE call to the Live Connect Representational State Transfer (REST) API.

See also

LiveConnectClient class


LiveConnectClient postWithPath:dictBody:delegate method

Performs an asynchronous post for a given path, a message request body, and optionally, a LiveOperationDelegate. The post adds a new resource to a collection.

Signature

- (LiveOperation *) postWithPath:(NSString *)path
                        dictBody:(NSDictionary *)dictBody
                        delegate:(id <LiveOperationDelegate>)delegate;

Parameters

Name | Datatype | Description
path | NSString | Required. The SkyDrive path to which to send a POST request.
dictBody | NSDictionary | Required. An NSDictionary instance that includes the request body attributes.
delegate | id <LiveOperationDelegate> | Optional. An instance of a class that implements the LiveOperationDelegate protocol.

Returns

Type: LiveOperation

The asynchronous operation that is used to track the asynchronous Representational State Transfer (REST) API request and get response data once the operation completes.

Defined in

LiveConnectClient.h

Remarks

This method uses an HTTP POST call to the Live Connect Representational State Transfer (REST) API.

See also

LiveConnectClient class


LiveConnectClient postWithPath:dictBody:delegate:userState method

Performs an asynchronous post for a given path, a message request body, and optionally, a LiveOperationDelegate and user state. The post adds a new resource to a collection.

Signature

- (LiveOperation *) postWithPath:(NSString *)path
                        dictBody:(NSDictionary *)dictBody
                        delegate:(id <LiveOperationDelegate>)delegate
                       userState:(id)userState;

Parameters

Name | Datatype | Description
path | NSString | Required. The SkyDrive path to which to send a POST request.
dictBody | NSDictionary | Required. An NSDictionary instance that includes the request body attributes.
delegate | id <LiveOperationDelegate> | Optional. An instance of a class that implements the LiveOperationDelegate protocol.
userState | id | Optional. An object that is used to track the asynchronous state. The userState object is found in the userState property of the LiveOperation instance that is passed as a parameter when a LiveOperationDelegate protocol method is invoked.

Returns

Type: LiveOperation

The asynchronous operation that is used to track the asynchronous Representational State Transfer (REST) API request and get response data once the operation completes.

The representation of the data returned from the Live Connect Representational State Transfer (REST) API.

Defined in

LiveConnectClient.h

Remarks

This method uses an HTTP POST call to the Live Connect Representational State Transfer (REST) API.

See also

LiveConnectClient class


LiveConnectClient postWithPath:jsonBody:delegate method

Performs an asynchronous post for a given path, a JavaScript Object Notation (JSON) message request body, and optionally, a LiveOperationDelegate. The post adds a new resource to a collection.

Signature

- (LiveOperation *) postWithPath:(NSString *)path
                        jsonBody:(NSString *)jsonBody
                        delegate:(id <LiveOperationDelegate>)delegate;

Parameters

Name | Datatype | Description
path | NSString | Required. The SkyDrive path to which to send a POST request.
jsonBody | NSString | Required. A NSString instance that includes the request body in JSON format.
delegate | id <LiveOperationDelegate> | Optional. An instance of a class that implements the LiveOperationDelegate protocol.

Returns

Type: LiveOperation

The asynchronous operation that is used to track the asynchronous Representational State Transfer (REST) API request and get response data once the operation completes.

Defined in

LiveConnectClient.h

Remarks

This method uses an HTTP POST call to the Live Connect Representational State Transfer (REST) API.

See also

LiveConnectClient class


LiveConnectClient postWithPath:jsonBody:delegate:userState method

Performs an asynchronous post for a given path, a JavaScript Object Notation (JSON) message request body, and optionally, a LiveOperationDelegate and user state. The post adds a new resource to a collection.

Signature

- (LiveOperation *) postWithPath:(NSString *)path
                        jsonBody:(NSString *)jsonBody
                        delegate:(id <LiveOperationDelegate>)delegate
                       userState:(id)userState;

Parameters

Name | Datatype | Description
path | NSString | Required. The SkyDrive path to which to send a POST request.
jsonBody | NSString | Required. A NSString instance that includes the request body in JSON format.
delegate | id <LiveOperationDelegate> | Optional. An instance of a class that implements the LiveOperationDelegate protocol.
userState | id | Optional. An object that is used to track the asynchronous state. The userState object is found in the userState property of the LiveOperation instance that is passed as a parameter when a LiveOperationDelegate protocol method is invoked.

Returns

Type: LiveOperation

The asynchronous operation that is used to track the asynchronous Representational State Transfer (REST) API request and get response data once the operation completes.

Defined in

LiveConnectClient.h

Remarks

This method uses an HTTP POST call to the Live Connect Representational State Transfer (REST) API.

See also

LiveConnectClient class


LiveConnectClient putWithPath:dictBody:delegate method

Performs an asynchronous PUT that updates a resource with a given path, message request body, and optionally, a LiveOperationDelegate. If the resource does not exist, it creates a new one.

Signature

- (LiveOperation *) putWithPath:(NSString *)path
                       dictBody:(NSDictionary *)dictBody
                       delegate:(id <LiveOperationDelegate>)delegate;

Parameters

Name | Datatype | Description
path | NSString | Required. The path or object ID of the resource to send a PUT request.
dictBody | NSDictionary | Required. An NSDictionary instance that includes the request body attributes.
delegate | id <LiveOperationDelegate> | Optional. An instance of a class that implements the LiveOperationDelegate protocol.

Returns

Type: LiveOperation

The asynchronous operation that is used to track the asynchronous Representational State Transfer (REST) API request and get response data once the operation completes.

Defined in

LiveConnectClient.h

Remarks

This method uses an HTTP PUT call to the Live Connect Representational State Transfer (REST) API.

See also

LiveConnectClient class


LiveConnectClient putWithPath:dictBody:delegate:userState method

Performs an asynchronous PUT that updates a resource with a given path, message request body, and optionally, a LiveOperationDelegate and user state. If the resource does not exist, it creates a new one.

Signature

- (LiveOperation *) putWithPath:(NSString *)path
                       dictBody:(NSDictionary *)dictBody
                       delegate:(id <LiveOperationDelegate>)delegate
                      userState:(id)userState;

Parameters

Name | Datatype | Description
path | NSString | Required. The path or object ID of the resource to send a PUT request.
dictBody | NSDictionary | Required. An NSDictionary instance that includes the request body attributes.
delegate | id <LiveOperationDelegate> | Optional. An instance of a class that implements the LiveOperationDelegate protocol.
userState | id | Optional. An object that is used to track the asynchronous state. The userState object is found in the userState property of the LiveOperation instance that is passed as a parameter when a LiveOperationDelegate protocol method is invoked.

Returns

Type: LiveOperation

The asynchronous operation that is used to track the asynchronous Representational State Transfer (REST) API request and get response data once the operation completes.

Defined in

LiveConnectClient.h

Remarks

This method uses an HTTP PUT call to the Live Connect Representational State Transfer (REST) API.

See also

LiveConnectClient class


LiveConnectClient putWithPath:jsonBody:delegate method

Performs an asynchronous PUT that updates a resource with a given path, JavaScript Object Notation (JSON) message request body, and optionally, a LiveOperationDelegate. If the resource does not exist, it creates a new one.

Signature

- (LiveOperation *) putWithPath:(NSString *)path
                       jsonBody:(NSString *)jsonBody
                       delegate:(id <LiveOperationDelegate>)delegate;

Parameters

Name | Datatype | Description
path | NSString | Required. The path or object ID of the resource to send a PUT request.
jsonBody | NSString | Required. A NSString instance that includes the request body in JSON format.
delegate | id <LiveOperationDelegate> | Optional. An instance of a class that implements the LiveOperationDelegate protocol.

Returns

Type: LiveOperation

The asynchronous operation that is used to track the asynchronous Representational State Transfer (REST) API request and get response data once the operation completes.

Defined in

LiveConnectClient.h

Remarks

This method uses an HTTP PUT call to the Live Connect Representational State Transfer (REST) API.

See also

LiveConnectClient class


LiveConnectClient putWithPath:jsonBody:delegate:userState method

Performs an asynchronous PUT that updates a resource with a given path, JavaScript Object Notation (JSON) message request body, and optionally, a LiveOperationDelegate and user state. If the resource does not exist, it creates a new one.

Signature

- (LiveOperation *) putWithPath:(NSString *)path
                       jsonBody:(NSString *)jsonBody
                       delegate:(id <LiveOperationDelegate>)delegate
                      userState:(id)userState;

Parameters

Name | Datatype | Description
path | NSString | Required. The path or object ID of the resource to send a PUT request.
jsonBody | NSString | Required. A NSString instance that includes the request body in JSON format.
delegate | id <LiveOperationDelegate> | Optional. An instance of a class that implements the LiveOperationDelegate protocol.
userState | id | Optional. An object that is used to track the asynchronous state. The userState object is found in the userState property of the LiveOperation instance that is passed as a parameter when a LiveOperationDelegate protocol method is invoked.

Returns

Type: LiveOperation

The asynchronous operation that is used to track the asynchronous Representational State Transfer (REST) API request and get response data once the operation completes.

Defined in

LiveConnectClient.h

Remarks

This method uses an HTTP PUT call to the Live Connect Representational State Transfer (REST) API.

See also

LiveConnectClient class


LiveConnectClient session property

Gets the Live Connect session for this LiveConnectClient.

Signature

@property(nonatomic, readonly) LiveConnectSession *session;

Property Values

Name | Datatype | Description
session | LiveConnectSession | The name for this LiveConnectSession.

Returns

Nothing.

Defined in

LiveConnectClient.h

Remarks

Invoked when the operation completes successfully.

See also

LiveConnectClient class


LiveConnectClient uploadToPath:fileName:data:delegate method

Performs an asynchronous upload of a resource to a user's Microsoft SkyDrive account. This method uses a given path, file name, file data, and optionally, a LiveUploadOperationDelegate.

Signature

- (LiveOperation *) uploadToPath:(NSString *)path
                        fileName:(NSString *)fileName
                            data:(NSData *)data
                        delegate:(id <LiveUploadOperationDelegate>)delegate;

Parameters

Name | Datatype | Description
path | NSString | Required. The path or object ID of the folder to upload the file to.
fileName | NSString | Required. The file name to use for the file being uploaded on SkyDrive.
data | NSData | Required. The NSData instance that contains the data to upload.
delegate | id <LiveUploadOperationDelegate> | Optional. An instance of a class that implements the LiveUploadOperationDelegate protocol.

Returns

Type: LiveOperation

The asynchronous operation that is used to track the asynchronous Representational State Transfer (REST) API request and get response data once the operation completes.

Defined in

LiveConnectClient.h

See also

LiveConnectClient class


LiveConnectClient uploadToPath:fileName:data:overwrite:delegate:userState method

Performs an asynchronous upload of a resource to a user's Microsoft SkyDrive account. This method uses a given path, file name, file data, and optionally, a LiveUploadOperationDelegate, user state, and an option to overwrite an existing file.

Signature

- (LiveOperation *) uploadToPath:(NSString *)path
                        fileName:(NSString *)fileName
                            data:(NSData *)data
                       overwrite:(LiveUploadOverwriteOption)overwrite
                        delegate:(id <LiveUploadOperationDelegate>)delegate
                       userState:(id)userState;

Parameters

Name | Datatype | Description
path | NSString | Required. The path or object ID of the folder to upload the file to.
fileName | NSString | Required. The file name to use for the file being uploaded on SkyDrive.
data | NSData | Required. The NSData instance that contains the data to upload.
overwrite | LiveUploadOverwriteOption | Optional. A value that indicates what should happen if a file that's being uploaded tries to overwrite a file with the same name in the upload location.
delegate | id <LiveUploadOperationDelegate> | Optional. An instance of a class that implements the LiveUploadOperationDelegate protocol.
userState | id | Optional. An object that is used to track the asynchronous state. The userState object is found in the userState property of the LiveOperation instance that is passed as a parameter when a LiveUploadOperationDelegate protocol method is invoked.

Returns

Type: LiveOperation

The asynchronous operation that is used to track the asynchronous Representational State Transfer (REST) API request and get response data once the operation completes.

Defined in

LiveConnectClient.h

See also

LiveConnectClient class


LiveConnectClient uploadToPath:fileName:inputStream:delegate method

Performs an asynchronous upload of a resource to a user's Microsoft SkyDrive account. This method uses a given path, file name, input stream, and optionally, a LiveUploadOperationDelegate.

Signature

- (LiveOperation *) uploadToPath:(NSString *)path
                        fileName:(NSString *)fileName
                     inputStream:(NSInputStream *)inputStream
                        delegate:(id <LiveUploadOperationDelegate>)delegate;

Parameters

Name | Datatype | Description
path | NSString | Required. The path or object ID of the folder to upload the file to.
fileName | NSString | Required. The file name to use for the file being uploaded on SkyDrive.
inputStream | NSInputStream | Required. The NSInputStream that is the source of the data to read and upload.
delegate | id <LiveUploadOperationDelegate> | Optional. An instance of a class that implements the LiveUploadOperationDelegate protocol.

Returns

Type: LiveOperation

The asynchronous operation that is used to track the asynchronous Representational State Transfer (REST) API request and get response data once the operation completes.

Defined in

LiveConnectClient.h

See also

LiveConnectClient class


LiveConnectClient uploadToPath:fileName:inputStream:overwrite:delegate:userState method

Performs an asynchronous upload of a resource to a user's Microsoft SkyDrive account. This method uses a given path, file name, input stream, and optionally, a LiveUploadOperationDelegate, user state, and an option to overwrite an existing file.

Signature

- (LiveOperation *) uploadToPath:(NSString *)path
                        fileName:(NSString *)fileName
                     inputStream:(NSInputStream *)inputStream
                       overwrite:(LiveUploadOverwriteOption)overwrite
                        delegate:(id <LiveUploadOperationDelegate>)delegate
                       userState:(id)userState;

Parameters

Name | Datatype | Description
path | NSString | Required. The path or object ID of the folder to upload the file to.
fileName | NSString | Required. The file name to use for the file being uploaded on SkyDrive.
inputStream | NSInputStream | Required. The NSInputStream that is the source of the data to read and upload.
overwrite | LiveUploadOverwriteOption | Optional. A value that indicates what should happen if a file that's being uploaded tries to overwrite a file with the same name in the upload location.
delegate | id <LiveUploadOperationDelegate> | Optional. An instance of a class that implements the LiveUploadOperationDelegate protocol.
userState | id | Optional. An object that is used to track the asynchronous state. The userState object is found in the userState property of the LiveOperation instance that is passed as a parameter when a LiveUploadOperationDelegate protocol method is invoked.

Returns

Type: LiveOperation

The asynchronous operation that is used to track the asynchronous Representational State Transfer (REST) API request and get response data once the operation completes.

Defined in

LiveConnectClient.h

See also

LiveConnectClient class


LiveConnectSession class

Represents the current Live Connect session.

Signature

@interface LiveConnectSession : NSObject

Properties

Name | Description
accessToken | Gets the access token for a user that is signed in and connected.
authenticationToken | Gets the user specific token so that the app can validate the user.
expires | Gets the date that the Live Connect session expires.
refreshToken | Gets a user specific refresh token that the app can use to refresh the access token.
scopes | Gets the user scopes for this Live Connect session.

Defined in

LiveAuthDelegate.h

See also

iOS API


LiveConnectSession accessToken property

Gets the access token for a user that is signed in and connected.

Signature

@property (nonatomic, readonly) NSString *accessToken;

Property Values

Name | Datatype | Description
accessToken | NSString | The access token.

Defined in

LiveConnectSession.h

See also

LiveConnectSession class


LiveConnectSession authenticationToken property

Gets the user specific token so that the app can validate the user.

Signature

@property (nonatomic, readonly) NSString *authenticationToken;

Property Values

Name | Datatype | Description
authenticationToken | NSString | The authentication token.

Defined in

LiveConnectSession.h

See also

LiveConnectSession class


LiveConnectSession expires property

Gets the date that the Live Connect session expires.

Signature

@property (nonatomic, readonly) NSDate *expires;

Property Values

Name | Datatype | Description
expires | NSDate | An NSDate instance indicating when the session expires.

Defined in

LiveConnectSession.h

See also

LiveConnectSession class


LiveConnectSession refreshToken property

Gets a user specific refresh token that the app can use to refresh the access token.

Signature

@property (nonatomic, readonly) NSString *refreshToken;

Property Values

Name | Datatype | Description
refreshToken | NSString | The refresh token.

Defined in

LiveConnectSession.h

See also

LiveConnectSession class


LiveConnectSession scopes property

Gets the user scopes for this Live Connect session.

Signature

@property (nonatomic, readonly) NSArray *scopes;

Property Values

Name | Datatype | Description
scopes | NSArray | An array of scope values that the user has consented to.

Defined in

LiveConnectSession.h

See also

LiveConnectSession class


LiveConnectSessionStatus enumeration

Specifies the status of an operation.

Signature

typedef enum LiveConnectSessionStatus;

Members

Member | Value | Description
LiveAuthUnknown | 0 | The user is unknown.
LiveAuthConnected | 1 | The user has consented to the scopes requested by the app.
LiveAuthNotConnected | 2 | The user has not consented to the scopes requested by the app.

Defined in

LiveConnectSessionStatus.h

See also

iOS API
LiveAuthDelegate authCompleted:session:userState method


LiveDownloadOperation class

Represents data returned from a download call to the Live Connect Representational State Transfer (REST) API.

Signature

@interface LiveDownloadOperation : LiveOperation

Properties

Name | Description
data | The NSData instance that holds downloaded data.

Defined in

LiveDownloadOperation.h

See also

iOS API


LiveDownloadOperation data property

The NSData instance that holds downloaded data.

Signature

@property (nonatomic, readonly) NSData *data;

Property Values

Name | Datatype | Description
data | NSData | The NSData instance containing downloaded content.

Defined in

LiveDownloadOperation.h

See also

LiveDownloadOperation class


LiveDownloadOperationDelegate protocol

Represents the protocol that captures callback handling methods for Microsoft SkyDrive downloads.

Signature

@protocol LiveDownloadOperationDelegate <NSObject>

Methods

Name | Description
liveOperationSucceeded method | Invoked when the operation is successful.
liveOperationFailed:operation method | Invoked when the download operation fails.
liveOperationProgress:data:operation method | Invoked when there is a download progress event raised.

Defined in

LiveDownloadOperationDelegate.h

See also

iOS API


LiveDownloadOperationDelegate liveOperationSucceeded method

Invoked when the operation is successful.

Signature

- (void) liveOperationSucceeded:(LiveDownloadOperation *)operation

Parameters

Name | Datatype | Description
operation | LiveDownloadOperation | The LiveDownloadOperation that is successful.

Returns

Nothing.

Defined in

LiveDownloadOperationDelegate.h

See also

LiveDownloadOperationDelegate protocol


LiveDownloadOperationDelegate liveOperationFailed:operation method

Invoked when the download operation fails.

Signature

- (void) liveOperationFailed:(NSError *)error
                  operation:(LiveDownloadOperation *)operation

Parameters

Name | Datatype | Description
error | NSError | The error returned by the download operation call.
operation | LiveDownloadOperation | The LiveDownloadOperation that fails.

Returns

Nothing.

Defined in

LiveDownloadOperationDelegate.h

See also

LiveDownloadOperationDelegate protocol


LiveDownloadOperationDelegate liveOperationProgress:data:operation method

Invoked when there is a download progress event raised.

Signature

- (void) liveDownloadOperationProgressed:(LiveOperationProgress *)progress
                                    data:(NSData *)receivedData
                               operation:(LiveDownloadOperation *)operation

Parameters

Name | Datatype | Description
progress | LiveOperationProgress | The progress of the download as tracked by the LiveOperationProgress object.
receivedData | NSData | The bytes of data that have been received so far.
operation | LiveDownloadOperation | The LiveDownloadOperation that is being tracked.

Returns

Nothing.

Defined in

LiveDownloadOperationDelegate.h

See also

LiveDownloadOperationDelegate protocol


LiveOperation class

Represents an operation that sends a request to Live Connect Representational State Transfer (REST) API.

Signature

@interface LiveOperation : NSObject

Methods

Name | Description
cancel method | Cancels the current operation.

Properties

Name | Description
delegate property | The delegate instance that handles the operation callbacks.
method property | Gets the type of HTTP method used to make the call.
path property | The path of the request.
rawResult property | The text received from the Live Connect Representational State Transfer (REST) API response.
result property | The parsed result received from the Live Connect Representational State Transfer (REST) API response.
userState property | The userState object passed in when the original method was invoked on the LiveConnectClient instance.

Defined in

LiveOperation.h

See also

iOS API


liveOperation cancel method

Cancels the current operation.

Signature

- (void) cancel;

Parameters

This method has no parameters.

Returns

Nothing.

Defined in

LiveOperation.h

See also

LiveOperation class


liveOperation delegate property

The delegate instance that handles the operation callbacks.

Signature

@property (nonatomic, assign) id delegate

Property Values

Name | Datatype | Description
delegate | id | The reference to the delegate instance.

Defined in

LiveOperation.h

See also

LiveOperation class


LiveOperation method property

Gets the type of HTTP method used to make the call.

Signature

@property (nonatomic, readonly) NSString *method

Property Values

Name | Datatype | Description
method | NSString | The name of the method.

Defined in

LiveOperation.h

See also

LiveOperation class


LiveOperation path property

The path of the request.

Signature

@property (nonatomic, readonly) NSString *path

Property Values

Name | Datatype | Description
path | NSString | The path of the request.

Defined in

LiveOperation.h

See also

LiveOperation class


LiveOperation rawResult property

The text received from the Live Connect Representational State Transfer (REST) API response.

Signature

@property (nonatomic, readonly) NSString *rawResult

Property Values

Name | Datatype | Description
rawResult | NSString | The text for the raw result.

Defined in

LiveOperation.h

See also

LiveOperation class


LiveOperation result property

The parsed result received from the Live Connect Representational State Transfer (REST) API response.

Signature

@property (nonatomic, readonly) NSDictionary *result

Property Values

Name | Datatype | Description
result | NSDictionary | The result.

Defined in

LiveOperation.h

See also

LiveOperation class


LiveOperation userState property

The userState object passed in when the original method was invoked on the LiveConnectClient instance.

Signature

@property (nonatomic, readonly) id userState

Property Values

Name | Datatype | Description
userState | id | The reference to the user state.

Defined in

LiveOperation.h

See also

LiveOperation class


LiveOperationDelegate protocol

Represents the protocol that captures a Live Connect access operation related to callback handling methods.

Signature

@protocol LiveOperationDelegate <NSObject>

Methods

Name | Description
liveOperationFailed method | Invoked when the operation fails.
liveOperationSucceeded method | Invoked when the operation is successful.

Defined in

LiveOperationDelegate.h

See also

iOS API


LiveOperationDelegate liveOperationFailed method

Invoked when the operation fails.

Signature

- (void) liveOperationFailed:(NSError *)error
                   operation:(LiveOperation*)operation

Parameters

Name | Datatype | Description
error | NSError | The error returned by the operation call.
operation | LiveOperation | The LiveOperation object.

Returns

Nothing.

Defined in

LiveOperationDelegate.h

LiveOperation.h

See also

LiveOperationDelegate protocol


LiveOperationDelegate liveOperationSucceeded method

Invoked when the operation is successful.

Signature

- (void) liveOperationSucceeded:(LiveOperation *)operation

Parameters

Name | Datatype | Description
operation | LiveOperation | The LiveOperation object.

Returns

Nothing.

Defined in

LiveOperationDelegate.h

See also

LiveOperationDelegate protocol


LiveOperationProgress class

Represents an operation progress object that encapsulates the progress information of a running operation.

Signature

@interface LiveOperationProgress : NSObject

Properties

Name | Description
bytesTransferred property | The number of bytes already transferred.
progressPercentage property | The percentage rate of bytes already transferred.
totalBytes property | The total number of bytes to transfer.

Defined in

LiveOperationProgress.h

See also

iOS API


LiveOperationProgress bytesTransferred property

The number of bytes already transferred.

Signature

@property (nonatomic, readonly) NSUInteger bytesTransferred

Property Values

Name | Datatype | Description
bytesTransferred | NSUInteger | The number of bytes transferred.

Defined in

LiveOperationProgress.h

See also

LiveOperationProgress class


LiveOperationProgress progressPercentage property

The percentage rate of bytes already transferred.

Signature

@property (nonatomic, readonly) double progressPercentage

Property Values

Name | Datatype | Description
progressPercentage | double | The percentage of bytes transferred.

Defined in

LiveOperationProgress.h

See also

LiveOperationProgress class


LiveOperationProgress totalBytes property

The total number of bytes to transfer.

Signature

@property (nonatomic, readonly) NSUInteger totalBytes;

Property Values

Name | Datatype | Description
totalBytes | NSUInteger | The total bytes transferred.

Defined in

LiveOperationProgress.h

See also

LiveOperationProgress class


LiveUploadOperationDelegate protocol

Represents the protocol that captures callback handling methods for Microsoft SkyDrive upload operations.

Signature

@protocol LiveUploadOperationDelegate <NSObject>

Methods

Name | Description
liveOperationSucceeded method | Invoked when the operation was successful.
liveOperationFailed method | Invoked when the operation fails.
liveUploadOperationProgressed method | Invoked when an upload progress event is raised.

Defined in

LiveUploadOperationDelegate.h

See also

iOS API


LiveUploadOperationDelegate liveOperationSucceeded method

Invoked when the operation was successful.

Signature

- (void) liveOperationSucceeded:(LiveOperation *)operation

Property Values

Name | Datatype | Description
operation | LiveOperation | The LiveOperation being tracked.

Defined in

LiveUploadOperationDelegate.h

See also

LiveUploadOperationDelegate protocol


LiveUploadOperationDelegate liveOperationFailed method

Invoked when the operation fails.

Signature

- (void) liveOperationFailed:(NSError *)error
                   operation:(LiveOperation *)operation;

Property Values

Name | Datatype | Description
error | NSError | The error returned by the operation call.
operation | LiveOperation | The LiveOperation being tracked.

Defined in

LiveUploadOperationDelegate.h

See also

LiveUploadOperationDelegate protocol


LiveUploadOperationDelegate liveUploadOperationProgressed method

Invoked when an upload progress event is raised.

Signature

- (void) liveUploadOperationProgressed:(LiveOperationProgress *)progress
                             operation:(LiveOperation *)operation

Property Values

Name | Datatype | Description
progress | LiveOperationProgress | The progress of the download as tracked by the LiveOperationProgress object.
operation | LiveOperation | The LiveOperation being tracked.

Defined in

LiveUploadOperationDelegate.h

See also

LiveUploadOperationDelegate protocol


LiveUploadOverwriteOption enumeration

Specifies the overwrite behavior for an incoming file that's uploaded to Microsoft SkyDrive when a file with the same name already exists in the same upload location.

Signature

typedef enum LiveUploadOverwriteOption

Members

Member | Value | Description
LiveUploadOverwrite | 0 | Overwrite the existing file with the incoming file.
LiveUploadDoNotOverwrite | 1 | Do not overwrite the existing file.
LiveUploadRename | 2 | Do not overwrite the existing file. Instead, SkyDrive will assign the incoming file a new file name as it's being downloaded. Note The file renaming pattern that SkyDrive uses may produce unpredictable file names.

Defined in

LiveUploadOverwriteOption.h

See also

iOS API


Android API

Provides a set of packages to simplify calling the Live Connect Representational State Transfer (REST) APIs from Android apps.

Packages

Name | Description
com.microsoft.live | Provides a set of classes, enumerations, and interfaces to simplify calling the Live Connect Representational State Transfer (REST) APIs from Android apps.


com.microsoft.live package

Provides a set of classes, enumerations, and interfaces to simplify calling the Live Connect Representational State Transfer (REST) API from Android apps.

Classes

Name | Description
LiveAuthClient | Retrieves a LiveConnectSession that can be used by a LiveConnectClient to make requests to the Live Connect API.
LiveAuthException | Indicates that an exception occurred during the Auth process.
LiveConnectClient | Makes client requests over the Live Connect Representational State Transfer (REST) API.
LiveConnectSession | Represents a Live Connect session.
LiveDownloadOperation | Represents data returned from a download call to the Live Connect Representational State Transfer (REST) API.
LiveOperation | Represents data returned from the Live Connect Representational State Transfer (REST) services.
LiveOperationException | Represents errors that occur when making requests to the Representational State Transfer (REST) API.

Enumerations

Name | Description
LiveStatus | Specifies the status of an operation.
OverwriteOption | Specifies the overwrite behavior for an incoming file that's uploaded to SkyDrive when a file with the same name already exists in the same upload location.

Interfaces

Name | Description
LiveAuthListener | Handles callback methods for LiveAuthClient init, login, and logout methods
LiveDownloadOperationListener | Represents any functionality related to downloads that works with the Live Connect Representational State Transfer (REST) API.
LiveOperationListener | Called when an operation finishes or has an error.
LiveUploadOperationListener | Represents any functionality related to uploads that works with the Live Connect Representational State Transfer (REST) API.


LiveAuthClient class

Retrieves a LiveConnectSession that can be used by a LiveConnectClient to make requests to the Live Connect API.

Signature

public class LiveAuthClient

Constructors

Name | Description
LiveAuthClient(Context, String) | Creates a new LiveAuthClient and initializes its member variables for the app context and client ID.

Methods

Name | Description
getActivity | Returns the Activity used by this LiveAuthClient.
getClientId | Returns the client ID of the Live Connect app.
initialize(Iterable<String>, LiveAuthListener) | Initializes a new LiveConnectSession with the given scopes and a LiveAuthListener.
initialize(Iterable<String>, LiveAuthListener, Object) | Initializes a new LiveConnectSession with the given scopes, a LiveAuthListener, and the user state.
initialize(LiveAuthListener) | Initializes a new LiveConnectSession with a LiveAuthListener.
initialize(LiveAuthListener, Object) | Initializes a new LiveConnectSession with a LiveAuthListener and user state.
login(Activity, Iterable<String>, LiveAuthListener) | Logs in a user with the given scopes, activity, and a LiveAuthListener.
LiveAuthClient.login(Activity, Iterable<String>, LiveAuthListener, Object) | Logs in a user with the given scopes, activity, a LiveAuthListener, and the user state.
logout(LiveAuthListener) | Logs out the given user and clears the user state from the library (such as cookies).
logout(LiveAuthListener, Object) | Logs out the given user and clears the user state from the library (such as cookies).

Defined in

LiveAuthClient.java

Package

com.microsoft.live

See also

com.microsoft.live package


LiveAuthClient(Context, String) constructor

Creates a new LiveAuthClient and initializes its member variables for the app context and client ID.

Signature

public LiveAuthClient(Context context, String clientId)

Parameters

Name | Datatype | Description
context | Context | Context of the app used to save any refresh_token.
clientId | String | The client ID of the Live Connect app this LiveAuthClient uses for login.

Returns

LiveAuthClient

Defined in

LiveAuthClient.java

See also

LiveAuthClient class


LiveAuthClient.getActivity method

Returns the Activity used by this LiveAuthClient.

Signature

public Activity getActivity()

Parameters

This method has no parameters.

Returns

The Android Activity.

Defined in

LiveAuthClient.java

See also

LiveAuthClient class


LiveAuthClient.getClientId method

Returns the client ID of the Live Connect app.

Signature

public String getClientId()

Parameters

This method has no parameters.

Returns

The client ID.

Defined in

LiveAuthClient.java

See also

LiveAuthClient class


LiveAuthClient.initialize(Iterable<String>, LiveAuthListener) method

Initializes a new LiveConnectSession with the given scopes and a LiveAuthListener.

Signature

public void initialize(Iterable<String> scopes, LiveAuthListener listener)

Parameters

Name | Datatype | Description
scopes | Iterable<String> | The scopes to use for initializing the LiveConnectSession. See Scopes and Permissions for a list of scopes and explanations.
listener | LiveAuthListener | The listener to call after completion or error during the initialization process.

Returns

Nothing.

Defined in

LiveAuthClient.java

Remarks

The LiveConnectSession is returned by calling LiveAuthListener.onAuthComplete(LiveStatus, LiveConnectSession, Object). Otherwise, the LiveAuthListener.onAuthError(LiveAuthException, Object) is called. These methods are called on the main/UI thread.

If the wl.offline_access scope is used, a refresh_token is stored in the SharedPreferences for a given Activity. This initialize uses the last successfully used scopes from either a login or initialize operation.

See also

LiveAuthClient class


LiveAuthClient.initialize(Iterable<String>, LiveAuthListener, Object) method

Initializes a new LiveConnectSession with the given scopes, a LiveAuthListener, and the user state.

Signature

public void initialize(Iterable<String> scopes, LiveAuthListener listener, Object userState)

Parameters

Name | Datatype | Description
scopes | Iterable<String> | The scopes to use for initializing the LiveConnectSession. See Scopes and Permissions for a list of scopes and explanations.
listener | LiveAuthListener | The listener to call after completion or error during the logout process.
userState | Object | An arbitrary object that is used to determine the caller of the method.

Returns

Nothing.

Defined in

LiveAuthClient.java

Remarks

The LiveConnectSession is returned by calling LiveAuthListener.onAuthComplete(LiveStatus, LiveConnectSession, Object). Otherwise, the LiveAuthListener.onAuthError(LiveAuthException, Object) is called. These methods are called on the main/UI thread.

If the wl.offline_access scope is used, a refresh_token is stored in the SharedPreferences for a given Activity. This initialize uses the last successfully used scopes from either a login or initialize operation.

See also

LiveAuthClient class


LiveAuthClient.Initialize(LiveAuthListener) method

Initializes a new LiveConnectSession with a LiveAuthListener.

Signature

public void initialize(LiveAuthListener listener)

Parameters

Name | Datatype | Description
listener | LiveAuthListener | The listener to call after completion or error during the logout process.

Defined in

LiveAuthClient.java

Remarks

The LiveConnectSession is returned by calling LiveAuthListener.onAuthComplete(LiveStatus, LiveConnectSession, Object). Otherwise, the LiveAuthListener.onAuthError(LiveAuthException, Object) is called. These methods are called on the main/UI thread.

If the wl.offline_access scope is used, a refresh_token is stored in the SharedPreferences for a given Activity. This initialize uses the last successfully used scopes from either a login or initialize operation.

See also

LiveAuthClient class


LiveAuthClient.initialize(LiveAuthListener, Object) method

Initializes a new LiveConnectSession with a LiveAuthListener and user state.

Signature

public void initialize(LiveAuthListener listener, Object userState)

Parameters

Name | Datatype | Description
listener | LiveAuthListener | The listener to call after completion or error during the logout process.
userState | Object | An arbitrary object that is used to determine the caller of the method.

Defined in

LiveAuthClient.java

Remarks

The LiveConnectSession is returned by calling LiveAuthListener.onAuthComplete(LiveStatus, LiveConnectSession, Object). Otherwise, the LiveAuthListener.onAuthError(LiveAuthException, Object) is called. These methods are called on the main/UI thread.

If the wl.offline_access scope is used, a refresh_token is stored in the SharedPreferences for a given Activity. This initialize uses the last successfully used scopes from either a login or initialize operation.

See also

LiveAuthClient class


LiveAuthClient.login(Activity, Iterable<String>, LiveAuthListener) method

Logs in a user with the given scopes, activity, and a LiveAuthListener.

Signature

public void login(Activity activity, Iterable<String> scopes, LiveAuthListener listener)

Parameters

Name | Datatype | Description
activity | activity | The instance to use for displaying the Login dialog.
scopes | Iterable<String> | The scopes to use for initializing the LiveConnectSession. See Scopes and Permissions for a list of scopes and explanations.
listener | LiveAuthListener | The listener to call after completion or error during the logout process.

Returns

Nothing.

Exceptions

IllegalStateException if there is a pending login request.

Defined in

LiveAuthClient.java

Remarks

The login method displays a Dialog that prompts the user for a username and password, and asks for consent to use the given scopes. A LiveConnectSession is returned by calling LiveAuthListener.onAuthComplete(LiveStatus, LiveConnectSession, Object). Otherwise, the LiveAuthListener.onAuthError(LiveAuthException, Object) is called. These methods are called on the main/UI thread.

See also

LiveAuthClient class


LiveAuthClient.login(Activity, Iterable<String>, LiveAuthListener, Object) method

Logs in a user with the given scopes, activity, a LiveAuthListener, and the user state.

Signature

public void login(Activity activity,
                      Iterable<String> scopes,
                      LiveAuthListener listener,
                      Object userState)

Parameters

Name | Datatype | Description
activity | activity | The instance to use for displaying the Login dialog.
scopes | Iterable<String> | The scopes to use for initializing the LiveConnectSession. See Scopes and Permissions for a list of scopes and explanations.
listener | LiveAuthListener | The listener to call after completion or error during the logout process.
userState | Object | An arbitrary object that is used to determine the caller of the method.

Returns

Nothing.

Exceptions

IllegalStateException if there is a pending login request.

Defined in

LiveAuthClient.java

Remarks

The login method displays a Dialog that prompts the user for a username and password, and asks for consent to use the given scopes. A LiveConnectSession is returned by calling LiveAuthListener.onAuthComplete(LiveStatus, LiveConnectSession, Object). Otherwise, the LiveAuthListener.onAuthError(LiveAuthException, Object) is called. These methods are called on the main/UI thread.

See also

LiveAuthClient class


LiveAuthClient.logout(LiveAuthListener) method

Logs out the given user and clears the user state from the library (such as cookies).

Signature

public void logout(LiveAuthListener listener)

Parameters

Name | Datatype | Description
listener | LiveAuthListener | The listener to call after completion or error during the logout process.

Returns

Nothing.

Defined in

LiveAuthClient.java

Remarks

This method clears the previously created LiveConnectSession. LiveAuthListener.onAuthComplete(LiveStatus, LiveConnectSession, Object) is called on completion. Otherwise, LiveAuthListener.onAuthError(LiveAuthException, Object) is called.

See also

LiveAuthClient class


LiveAuthClient.logout(LiveAuthListener, Object) method

Logs out the given user and clears the user state from the library (such as cookies).

Signature

public void logout(LiveAuthListener listener, Object userState)

Parameters

Name | Datatype | Description
listener | LiveAuthListener | The listener to call after completion or error during the logout process.
userState | Object | An arbitrary object that is used to determine the caller of the method.

Returns

Nothing.

Defined in

LiveAuthClient.java

Remarks

This method clears the previously created LiveConnectSession. If successful, LiveAuthListener.onAuthComplete(LiveStatus, LiveConnectSession, Object) is called on completion. Otherwise, LiveAuthListener.onAuthError(LiveAuthException, Object) is called.

See also

LiveAuthClient class


LiveAuthException class

Indicates that an exception occurred during the Auth process.

Signature

public class LiveAuthException

Properties

Name | Description
getError | Returns the authentication error.
getErrorUri | Returns the error URI.

Defined in

LiveAuthException.java

Package

com.microsoft.live

See also

com.microsoft.live package


LiveAuthException.getError method

Returns the authentication error.

Signature

public String getError()

Parameters

This method has no parameters.

Returns

The error.

Defined in

LiveAuthException.java

See also

LiveAuthException class


LiveAuthException.getErrorUri method

Returns the error URI.

Signature

public String getErrorUri()

Parameters

This method has no parameters.

Returns

The error URI.

Defined in

LiveAuthException.java

See also

LiveAuthException class


LiveAuthListener interface

Handles callback methods for LiveAuthClient init, login, and logout methods. Returns the status of the operation when onAuthComplete is called. If there was an error during the operation, onAuthError is called with the exception that was thrown.

Signature

public interface LiveAuthListener

Methods

Name | Description
onAuthComplete(LiveStatus, LiveConnectSession, Object) | Invoked when the operation completes successfully.
onAuthError(LiveAuthException, Object) | Invoked when the method call fails.

Defined in

LiveAuthListener.java

Package

com.microsoft.live

See also

com.microsoft.live package


LiveAuthListener.onAuthComplete(LiveStatus, LiveConnectSession, Object) method

Invoked when the operation completes successfully.

Signature

public void onAuthComplete(LiveStatus status, LiveConnectSession session, Object userState)

Parameters

Name | Datatype | Description
status | LiveStatus | The LiveStatus for an operation. If successful, the status is CONNECTED. If unsuccessful, NOT_CONNECTED or UNKNOWN are returned.
session | LiveConnectSession | The LiveConnectSession for this LiveAuthClient.
userState | Object | An arbitrary object that is used to determine the caller of the method.

Defined in

LiveAuthListener.java

See also

LiveAuthListener interface


LiveAuthListener.onAuthError(LiveAuthException, Object) method

Invoked when the method call fails.

Signature

public void onAuthError(LiveAuthException exception, Object userState)

Parameters

Name | Datatype | Description
exception | LiveAuthException | The LiveAuthException error.
userState | Object | An arbitrary object that is used to determine the caller of the method.

Defined in

LiveAuthListener.java

See also

LiveAuthListener interface


LiveConnectClient class

Makes client requests over the Live Connect Representational State Transfer (REST) API.

Signature

public class LiveConnectClient

Constructors

Name | Description
LiveConnectClient(LiveConnectSession) | Creates a new LiveConnectClient and initializes its member variable for a LiveConnectSession.

Methods

Name | Description
copy(String, String) | Performs a synchronous copy of a file with the given path, destination, and listener.
copyAsync(String, String, LiveOperationListener) | Performs an asynchronous copy of a file with the given path, destination, and listener.
copyAsync(String, String, LiveOperationListener, Object) | Performs an asynchronous copy of a file with the given path, destination, listener, and user state.
delete(String) | Performs a synchronous delete of a file with the given path.
deleteAsync(String, LiveOperationListener) | Performs an asynchronous delete of a file with the given path and LiveOperationListener.
deleteAsync(String, LiveOperationListener, Object) | Performs an asynchronous delete of a file with the given path.
download(String) | Performs a download of a file with the given path.
downloadAsync(String, File, LiveDownloadOperationListener) | Performs an asynchronous download of a file with the given path and a LiveDownloadOperationListener.
downloadAsync(String, File, LiveDownloadOperationListener, Object) | Performs an asynchronous download of a file with the given path, a LiveDownloadOperationListener, and a user state.
downloadAsync(String, LiveDownloadOperationListener) | Performs an asynchronous download of a file with the given path and a LiveOperationListener.
downloadAsync(String, LiveDownloadOperationListener, Object) | Performs an asynchronous download of a file with the given path, a LiveOperationListener, and a user state.
get(String) | Performs an asynchronous get on the resource using a given path.
getAsync(String, LiveOperationListener) | Performs an asynchronous get on the resource using a given path and listener.
getAsync(String, LiveOperationListener, Object) | Performs an asynchronous get on the resource using a given path, listener, and user state.
getSession | Gets the LiveConnectSession.
move(String, String) | Performs a synchronous move of a resource on the for a given path and destination.
moveAsync(String, String, LiveOperationListener) | Performs an asynchronous move of a resource for a given path, destination, and listener.
moveAsync(String, String, LiveOperationListener, Object) | Performs an asynchronous move of a resource for a given path, destination, listener, and user state.
post(String, JSONObject) | Performs a synchronous post for a given path and message request body.
post(String, String) | Performs a synchronous post for a given path and message request body.
postAsync(String, String, LiveOperationListener) | Performs an asynchronous post for a given path, message request body, and listener.
postAsync(String, String, LiveOperationListener, Object) | Performs an asynchronous post for a given path, message request body, listener, and user state.
postAsync(String, JSONObject, LiveOperationListener) | Performs an asynchronous post for a given path, message request body, and listener.
postAsync(String, JSONObject, LiveOperationListener, Object) | Performs an asynchronous post for a given path, message request body, listener, and user state.
put(String, JSONObject) | Performs a synchronous PUT that updates a resource with a given path and message path. If the resource does not exist, it creates a new one.
put(String, String) | Performs a synchronous PUT that updates a resource with a given path and message path. If the resource does not exist, it creates a new one.
putAsync(String, String, LiveOperationListener) | Performs an asynchronous PUT that updates a resource with a given path, message path, and listener. If the resource does not exist, it creates a new one.
putAsync(String, String, LiveOperationListener, Object) | Performs an asynchronous PUT that updates a resource with a given path, message path, listener, and user state. If the resource does not exist, it creates a new one.
putAsync(String, JSONObject, LiveOperationListener) | Performs an asynchronous PUT that updates a resource with a given path, message path, and listener. If the resource does not exist, it creates a new one.
putAsync(String, JSONObject, LiveOperationListener, Object) | Performs an asynchronous PUT that updates a resource with a given path, message path, listener, and user state. If the resource does not exist, it creates a new one.
upload(String, String, File) | Uploads a resource with a given path, filename, and file contents.
upload(String, String, File, OverwriteOption) | Uploads a resource with a given path, filename, file contents, and gives the option to overwrite an existing resource.
upload(String, String, InputStream) | Uploads a resource with a given path, filename, and file contents.
upload(String, String, InputStream, OverwriteOption) | Uploads a resource with a given path, filename, file contents, and gives the option to overwrite an existing resource.
uploadAsync(String, String, File, OverwriteOption, LiveUploadOperationListener, Object) | Performs an asynchronous upload of a resource with a given path, filename, file contents, listener, and user state.
uploadAsync(String, String, File, LiveUploadOperationListener) | Performs an asynchronous upload of a resource with a given path, filename, file contents, and listener.
uploadAsync(String, String, File, LiveUploadOperationListener, Object) | Performs an asynchronous upload of a resource with a given path, filename, file contents, listener, and user state.
uploadAsync(String, String, InputStream, OverwriteOption, LiveUploadOperationListener, Object) | Performs an asynchronous upload of a resource with a given path, filename, file contents, listener, user state, and gives the option to overwrite an existing resource.
uploadAsync(String, String, InputStream, LiveUploadOperationListener) | Performs an asynchronous upload of a resource with a given path, filename, file contents, and listener.
uploadAsync(String, String, InputStream, LiveUploadOperationListener, Object) | Performs an asynchronous upload of a resource with a given path, filename, file contents, listener, and user state.

Defined in

LiveConnectClient.java

Package

com.microsoft.live

Remarks

In order to perform requests, a LiveConnectSession is required. A LiveConnectSession can be created from a LiveAuthClient. LiveConnectClient provides methods to perform both synchronous and asynchronous calls on the Live Connect Representational State Transfer (REST) API. Each synchronous method has a corresponding asynchronous method that uses the "Async" suffix. For example, the synchronous method "get" has a corresponding asynchronous method "getAsync". Asynchronous methods require a call back listener that is called back on the main/UI thread on completion, error, or progress. Listens to an ApiRequestAsync for onComplete and onError events and calls the proper method on the given LiveDownloadOperationListener for a given event.

See also

com.microsoft.live package


LiveConnectClient(LiveConnectSession) constructor

Creates a new LiveConnectClient and initializes its member variables from a LiveConnectSession.

Signature

public LiveConnectClient(LiveConnectSession session)

Parameters

Name | Datatype | Description
session | LiveConnectSession | The LiveConnectSession that contains all the information for the Live Connect session.

Returns

Type: LiveOperation

The representation of the data returned from the Live Connect Representational State Transfer (REST) API.

Defined in

LiveConnectClient.java

Exceptions

Type: IllegalArgumentException

The path is empty or the path is an absolute URI.

Type: NullPointerException

The path parameters are null.

See also

LiveConnectClient class


LiveConnectClient.copy(String, String) method

Performs a synchronous copy of a file with the given path and destination.

Signature

public LiveOperation copy(String path, String destination) throws LiveOperationException

Parameters

Name | Datatype | Description
path | String | The path to the file/resource to copy.
destination | String | The destination ID for the file being copied.

Returns

Type: LiveOperation

The representation of the data returned from the Live Connect Representational State Transfer (REST) API.

Defined in

LiveConnectClient.java

Exceptions

Type: LiveOperationException

The LiveOperation associated with the request.

Type: IllegalArgumentException

The path is empty or the path is an absolute URI.

Type: NullPointerException

The path parameters are null.

Remarks

This is a helper function that makes calls to the Live Connect Representational State Transfer (REST) API. It supports all paths in the REST API.

See also

LiveConnectClient class


LiveConnectClient.copyAsync(String, String, LiveOperationListener) method

An object that implements LiveOperationListener interface.

Signature

public LiveOperation copyAsync(String path, String destination, LiveOperationListener listener)

Parameters

Name | Datatype | Description
path | String | The path to the file/resource to copy.
destination | String | The destination ID for the file being copied.
listener | LiveOperationListener | An object that implements the LiveOperationListener interface.

Returns

Type: LiveOperation

The representation of the data returned from the Live Connect Representational State Transfer (REST) API.

Defined in

LiveConnectClient.java

Exceptions

Type: IllegalArgumentException

The path is empty or the path is an absolute URI.

Type: NullPointerException

The path parameters are null.

Remarks

This is a helper function that makes calls to the Live Connect Representational State Transfer (REST) API. It supports all paths in the REST API.

LiveOperationListener.onComplete(LiveOperation) is called on success. Otherwise, LiveOperationListener.onError(LiveOperationException, LiveOperation) is called. Both of these methods are called on the main/UI thread.

See also

LiveConnectClient class


LiveConnectClient.copyAsync(String, String, LiveOperationListener, Object) method

Performs an asynchronous copy of a file with the given path, destination, listener, and user state.

Signature

public LiveOperation copyAsync(String path, String destination, LiveOperationListener listener, Object userState)

Parameters

Name | Datatype | Description
path | String | The path to the file/resource to copy.
destination | String | The destination ID for the file being copied.
listener | LiveOperationListener | The LiveOperationListener that implements the LiveDownloadOperationListener interface
userState | Object | The user state for this call.

Returns

Type: LiveOperation

The representation of the data returned from the Live Connect Representational State Transfer (REST) API.

Defined in

LiveConnectClient.java

Exceptions

Type: IllegalArgumentException

The path is empty or the path is an absolute URI.

Type: NullPointerException

The path parameters are null.

Remarks

This is a helper function that makes calls to the Live Connect Representational State Transfer (REST) API. It supports all paths in the REST API.

LiveOperationListener.onComplete(LiveOperation) is called on success. Otherwise, LiveOperationListener.onError(LiveOperationException, LiveOperation) is called. Both of these methods are called on the main/UI thread.

See also

LiveConnectClient class


LiveConnectClient.delete(String) method

Performs a synchronous delete of a file with the given path.

Signature

public LiveOperation delete(String path) throws LiveOperationException

Parameters

Name | Datatype | Description
path | String | The path to the file/resource to be deleted.

Returns

Type: LiveOperation

The representation of the data returned from the Live Connect Representational State Transfer (REST) API.

Defined in

LiveConnectClient.java

Exceptions

Type: LiveOperationException

The LiveOperation associated with the request.

Type: IllegalArgumentException

The path is empty or the path is an absolute URI.

Type: NullPointerException

The path parameters are null.

Remarks

This is a helper function that makes calls using HTTP DELETE to the Live Connect Representational State Transfer (REST) API. It supports all paths in the REST API.

See also

LiveConnectClient class


LiveConnectClient.deleteAsync(String, LiveOperationListener) method

Performs an asynchronous delete of a file with the given path and LiveOperationListener.

Signature

public LiveOperation deleteAsync(String path, LiveOperationListener listener)

Parameters

Name | Datatype | Description
path | String | The path to the file/resource to be deleted.
listener | LiveOperationListener | The LiveOperationListener that implements the LiveDownloadOperationListener interface

Returns

Type: LiveOperation

The representation of the data returned from the Live Connect Representational State Transfer (REST) API.

Defined in

LiveConnectClient.java

Exceptions

Type: IllegalArgumentException

The path is empty or the path is an absolute URI.

Type: NullPointerException

The path parameters are null.

Remarks

This is a helper function that makes calls using HTTP DELETE to the Live Connect Representational State Transfer (REST) API. It supports all paths in the REST API.

LiveOperationListener.onComplete(LiveOperation) is called on success. Otherwise, LiveOperationListener.onError(LiveOperationException, LiveOperation) is called. Both of these methods are called on the main/UI thread.

See also

LiveConnectClient class


LiveConnectClient.deleteAsync(String, LiveOperationListener, Object) method

Performs an asynchronous delete of a file with the given path.

Signature

public LiveOperation deleteAsync(String path, LiveOperationListener listener, Object userState)

Parameters

Name | Datatype | Description
path | String | The path to the file/resource to be deleted.
listener | LiveOperationListener | The LiveOperationListener that implements the LiveDownloadOperationListener interface
userState | Object | The user state for this call.

Returns

Type: LiveOperation

The representation of the data returned from the Live Connect Representational State Transfer (REST) API.

Defined in

LiveConnectClient.java

Exceptions

Type: IllegalArgumentException

The path is empty or the path is an absolute URI.

Type: NullPointerException

The path parameters are null.

Remarks

This is a helper function that makes calls using HTTP DELETE to the Live Connect Representational State Transfer (REST) API. It supports all paths in the REST API.

LiveOperationListener.onComplete(LiveOperation) is called on success. Otherwise, LiveOperationListener.onError(LiveOperationException, LiveOperation) is called. Both of these methods are called on the main/UI thread.

See also

LiveConnectClient class


LiveConnectClient.download(String) method

Performs a download of a file with the given path.

Signature

public LiveOperation download(String path) throws LiveOperationException

Parameters

Name | Datatype | Description
path | String | The path to the file/resource to download.

Returns

Type: LiveOperation

The representation of the data returned from the Live Connect Representational State Transfer (REST) API.

Defined in

LiveConnectClient.java

Exceptions

Type: IllegalArgumentException

The path is empty or the path is an absolute URI.

Type: NullPointerException

The path parameters are null.

Remarks

This is a helper function that makes calls to the Live Connect Representational State Transfer (REST) API. It supports all paths in the REST API.

See also

LiveConnectClient class


LiveConnectClient downloadAsync(String, File, LiveDownloadOperationListener)

Performs an asynchronous download of a file with the given path and a LiveDownloadOperationListener.

Signature

public LiveDownloadOperation downloadAsync(String path, File file, LiveDownloadOperationListener listener)

Parameters

Name | Datatype | Description
path | String | The path to the file/resource to download.
file | File | File is an object that represents a file on the file system that will contain the downloaded file.
listener | LiveOperationListener | An object that implements the LiveDownloadOperationListener interface.

Returns

Type: LiveOperation

The representation of the data returned from the Live Connect Representational State Transfer (REST) API.

Defined in

LiveConnectClient.java

Exceptions

Type: IllegalArgumentException

The path is empty or the path is an absolute URI.

Type: NullPointerException

The path parameters are null.

Remarks

This is a helper function that makes calls to the Live Connect Representational State Transfer (REST) API. It supports all paths in the REST API.

See also

LiveConnectClient class


LiveConnectClient downloadAsync(String, File, LiveDownloadOperationListener, Object)

Performs an asynchronous download of a file with the given path, a LiveDownloadOperationListener, and a user state.

Signature

public LiveDownloadOperation downloadAsync(String path, File file, LiveDownloadOperationListener listener, Object userState)

Parameters

Name | Datatype | Description
path | String | The path to the file/resource to download.
file | File | File is an object that represents a file on the file system that will contain the downloaded file.
listener | LiveOperationListener | An object that implements the LiveDownloadOperationListener interface.
userState | Object | The user state for this call.

Returns

Type: LiveOperation

The representation of the data returned from the Live Connect Representational State Transfer (REST) API.

Defined in

LiveConnectClient.java

Exceptions

Type: IllegalArgumentException

The path is empty or the path is an absolute URI.

Type: NullPointerException

The path parameters are null.

Remarks

This is a helper function that makes calls to the Live Connect Representational State Transfer (REST) API. It supports all paths in the REST API.

See also

LiveConnectClient class


LiveConnectClient.downloadAsync(String, LiveDownloadOperationListener) method

Performs an asynchronous download of a file with the given path and a LiveDownloadOperationListener.

Signature

public LiveDownloadOperation downloadAsync(String path, LiveDownloadOperationListener listener)

Parameters

Name | Datatype | Description
path | String | The path to the file/resource to download.
listener | LiveOperationListener | An object that implements the LiveDownloadOperationListener interface.

Returns

Type: LiveOperation

The representation of the data returned from the Live Connect Representational State Transfer (REST) API.

Defined in

LiveConnectClient.java

Exceptions

Type: IllegalArgumentException

The path is empty or the path is an absolute URI.

Type: NullPointerException

The path parameters are null.

Remarks

This is a helper function that makes calls to the Live Connect Representational State Transfer (REST) API. It supports all paths in the REST API.

See also

LiveConnectClient class


LiveConnectClient.downloadAsync(String, LiveDownloadOperationListener, Object) method

Performs an asynchronous download of a file with the given path, a LiveDownloadOperationListener, and a user state.

Signature

public LiveDownloadOperation downloadAsync(String path, LiveDownloadOperationListener listener, Object userState)

Parameters

Name | Datatype | Description
path | String | The path to the file/resource to download.
listener | LiveOperationListener | An object that implements the LiveDownloadOperationListener interface.
userState | Object | The user state for this call.

Returns

Type: LiveOperation

The representation of the data returned from the Live Connect Representational State Transfer (REST) API.

Defined in

LiveConnectClient.java

Exceptions

Type: IllegalArgumentException

The path is empty or the path is an absolute URI.

Type: NullPointerException

The path parameters are null.

Remarks

This is a helper function that makes calls to the Live Connect Representational State Transfer (REST) API. It supports all paths in the REST API.

See also

LiveConnectClient class


LiveConnectClient.get(String) method

Performs an asynchronous get on the resource using a given path.

Signature

public LiveOperation get(String path) throws LiveOperationException

Parameters

Name | Datatype | Description
path | String | The path to the file/resource to retrieve.

Returns

Type: LiveOperation

The LiveOperation associated with the request.

Defined in

LiveConnectClient.java

Exceptions

Type: LiveOperationException

There is an error during the execution of the request.

Type: IllegalArgumentException

The path is empty or the path is an absolute URI.

Type: NullPointerException

The path parameters are null.

Remarks

This method uses an HTTP GET call to the Live Connect Representational State Transfer (REST) API.

See also

LiveConnectClient class


LiveConnectClient.getAsync(String, LiveOperationListener) method

Performs an asynchronous get on the resource using a given path and listener.

Signature

public LiveOperation getAsync(String path, LiveOperationListener listener)

Parameters

Name | Datatype | Description
path | String | The path to the file/resource to retrieve.
listener | LiveOperationListener | The listener that is called when the get request either completes or throws an error.

Returns

Type: LiveOperation

The LiveOperation associated with the request.

Defined in

LiveConnectClient.java

Exceptions

Type: IllegalArgumentException

The path is empty or the path is an absolute URI.

Type: NullPointerException

The path parameters are null.

Remarks

This method uses an HTTP GET call to the Live Connect Representational State Transfer (REST) API.

LiveOperationListener.onComplete(LiveOperation) is called on success. Otherwise, LiveOperationListener.onError(LiveOperationException, LiveOperation) is called. Both of these methods are called on the main/UI thread.

See also

LiveConnectClient class


LiveConnectClient.getAsync(String, LiveOperationListener, Object) method

Performs an asynchronous get on the resource using a given path, listener, and user state.

Signature

public LiveOperation getAsync(String path, LiveOperationListener listener, Object userState)

Parameters

Name | Datatype | Description
path | String | The path to the file/resource to retrieve.
listener | LiveOperationListener | The listener that is called when the get request either completes or throws an error.
userState | Object | An arbitrary object that is used to determine the caller of the method.

Returns

Type: LiveOperation

The LiveOperation associated with the request.

Defined in

LiveConnectClient.java

Exceptions

Type: IllegalArgumentException

The path is empty or the path is an absolute URI.

Type: NullPointerException

The path parameters are null.

Remarks

This method uses an HTTP GET call to the Live Connect Representational State Transfer (REST) API.

LiveOperationListener.onComplete(LiveOperation) is called on success. Otherwise, LiveOperationListener.onError(LiveOperationException, LiveOperation) is called. Both of these methods are called on the main/UI thread.

See also

LiveConnectClient class


LiveConnectClient.getSession method

Gets the LiveConnectSession.

Signature

public LiveConnectSession getSession()

Parameters

This method has no parameters.

Returns

Type: LiveConnectSession

The representation of the data returned from the Live Connect session.

Defined in

LiveConnectClient.java

Exceptions

Type: IllegalArgumentException

The path is empty or the path is an absolute URI.

Type: NullPointerException

The path parameters are null.

See also

LiveConnectClient class


LiveConnectClient.move(String, String) method

Performs a synchronous move of a resource for a given path and destination.

Signature

public LiveOperation move(String path, String destination) throws LiveOperationException

Parameters

Name | Datatype | Description
path | String | The path to the file/resource to move.
destination | String | The folder_id of the destination for the resource being moved.

Returns

Type: LiveOperation

The LiveOperation associated with the request.

Defined in

LiveConnectClient.java

Exceptions

Type: LiveOperationException

There is an error during the execution of the request.

Type: IllegalArgumentException

The path is empty or the path is an absolute URI.

Type: NullPointerException

The path parameters are null.

Remarks

This method uses an HTTP MOVE call to the Live Connect Representational State Transfer (REST) API.

See also

LiveConnectClient class


LiveConnectClient.moveAsync(String, String, LiveOperationListener) method

Performs an asynchronous move of a resource for a given path, destination, and listener.

Signature

public LiveOperation moveAsync(String path, String destination, LiveOperationListener listener)

Parameters

Name | Datatype | Description
path | String | The path to the file/resource to move.
destination | String | The folder_id of the destination for the resource being moved.
listener | LiveOperationListener | The listener that is called when the move request either completes or throws an error.

Returns

Type: LiveOperation

The LiveOperation associated with the request.

Defined in

LiveConnectClient.java

Exceptions

Type: IllegalArgumentException

The path is empty or the path is an absolute URI.

Type: NullPointerException

The path parameters are null.

Remarks

This method uses an HTTP MOVE call to the Live Connect Representational State Transfer (REST) API.

LiveOperationListener.onComplete(LiveOperation) is called on success. Otherwise, LiveOperationListener.onError(LiveOperationException, LiveOperation) is called. Both of these methods are called on the main/UI thread.

See also

LiveConnectClient class


LiveConnectClient.moveAsync(String, String, LiveOperationListener, Object) method

Performs an asynchronous move of a resource for a given path, destination, listener, and user state.

Signature

public LiveOperation moveAsync(String path,
                               String destination,
                               LiveOperationListener listener,
                               Object userState)

Parameters

Name | Datatype | Description
path | String | The path to the file/resource to move.
destination | String | The folder_id of the destination for the resource being moved.
listener | LiveOperationListener | The listener that is called when the move request either completes or throws an error.
userState | Object | An arbitrary object that is used to determine the caller of the method.

Returns

Type: LiveOperation

The LiveOperation associated with the request.

Defined in

LiveConnectClient.java

Exceptions

Type: IllegalArgumentException

The path is empty or the path is an absolute URI.

Type: NullPointerException

The path parameters are null.

Remarks

This method uses an HTTP MOVE call to the Live Connect Representational State Transfer (REST) API.

LiveOperationListener.onComplete(LiveOperation) is called on success. Otherwise, LiveOperationListener.onError(LiveOperationException, LiveOperation) is called. Both of these methods are called on the main/UI thread.

See also

LiveConnectClient class


LiveConnectClient.post(String, JSONObject) method

Performs a synchronous post for a given path and message request body. The post adds a new resource to a collection.

Signature

public LiveOperation post(String path, JSONObject body) throws LiveOperationException

Parameters

Name | Datatype | Description
path | String | The path to the file/resource to post.
body | JSONObject | The message body of the post request.

Returns

Type: LiveOperation

The LiveOperation that contains the JSON result.

Defined in

LiveConnectClient.java

Exceptions

Type: LiveOperationException

There is an error during the execution of the request.

Type: IllegalArgumentException

The path is empty or the path is an absolute URI.

Type: NullPointerException

The path parameters are null.

Remarks

This method uses an HTTP POST call to the Live Connect Representational State Transfer (REST) API.

See also

LiveConnectClient class


LiveConnectClient.post(String, String) method

Performs a synchronous post for a given path and message request body. The post adds a new resource to a collection.

Signature

public LiveOperation post(String path, String body) throws LiveOperationException

Parameters

Name | Datatype | Description
path | String | The path to the file/resource to post.
body | String | The body of the post request.

Returns

Type: LiveOperation

The LiveOperation associated with the request.

Defined in

LiveConnectClient.java

Exceptions

Type: LiveOperationException

There is an error during the execution of the request.

Type: IllegalArgumentException

The path is empty or the path is an absolute URI.

Type: NullPointerException

The path parameters are null.

Remarks

This method uses an HTTP POST call to the Live Connect Representational State Transfer (REST) API.

See also

LiveConnectClient class


LiveConnectClient.postAsync(String, String, LiveOperationListener) method

Performs an asynchronous post for a given path, message request body, and listener. The post adds a new resource to a collection.

Signature

public LiveOperation postAsync(String path, String body, LiveOperationListener listener)

Parameters

Name | Datatype | Description
path | String | The path to the file/resource to post.
body | String | The message body of the post request.
listener | LiveOperationListener | The listener that is called when the post request either completes or throws an error.

Returns

Type: LiveOperation

The LiveOperation associated with the request.

Defined in

LiveConnectClient.java

Exceptions

Type: IllegalArgumentException

The path is empty or the path is an absolute URI.

Type: NullPointerException

The path parameters are null.

Remarks

This method uses an HTTP POST call to the Live Connect Representational State Transfer (REST) API.

LiveOperationListener.onComplete(LiveOperation) is called on success. Otherwise, LiveOperationListener.onError(LiveOperationException, LiveOperation) is called. Both of these methods are called on the main/UI thread.

See also

LiveConnectClient class


LiveConnectClient.postAsync(String, String, LiveOperationListener, Object) method

Performs an asynchronous post for a given path, message request body, listener, and user state. The post adds a new resource to a collection.

Signature

public LiveOperation postAsync(String path,
                               String body,
                               LiveOperationListener listener,
                               Object userState)

Parameters

Name | Datatype | Description
path | String | The path to the file/resource to post.
body | String | The message body of the post request.
listener | LiveOperationListener | The listener that is called when the post request either completes or throws an error.
userState | Object | An arbitrary object that is used to determine the caller of the method.

Returns

Type: LiveOperation

The LiveOperation associated with the request.

Defined in

LiveConnectClient.java

Exceptions

Type: IllegalArgumentException

The path is empty or the path is an absolute URI.

Type: NullPointerException

The path parameters are null.

Remarks

This method uses an HTTP POST call to the Live Connect Representational State Transfer (REST) API.

LiveOperationListener.onComplete(LiveOperation) is called on success. Otherwise, LiveOperationListener.onError(LiveOperationException, LiveOperation) is called. Both of these methods are called on the main/UI thread.

See also

LiveConnectClient class


LiveConnectClient.postAsync(String, JSONObject, LiveOperationListener) method

Performs an asynchronous post for a given path, message request body, and listener. The post adds a new resource to a collection.

Signature

public LiveOperation postAsync(String path, JSONObject body, LiveOperationListener listener)

Parameters

Name | Datatype | Description
path | String | The path to the file/resource to post.
body | JSONObject | The message body of the post request.
listener | LiveOperationListener | The listener that is called when the post request either completes or throws an error.

Returns

Type: LiveOperation

The LiveOperation that contains the JSON result.

Defined in

LiveConnectClient.java

Exceptions

Type: IllegalArgumentException

The path is empty or the path is an absolute URI.

Type: NullPointerException

The path parameters are null.

Remarks

This method uses an HTTP POST call to the Live Connect Representational State Transfer (REST) API.

LiveOperationListener.onComplete(LiveOperation) is called on success. Otherwise, LiveOperationListener.onError(LiveOperationException, LiveOperation) is called. Both of these methods are called on the main/UI thread.

See also

LiveConnectClient class


LiveConnectClient.postAsync(String, JSONObject, LiveOperationListener, Object) method

Performs an asynchronous post for a given path, message request body, listener, and user state. The post adds a new resource to a collection.

Signature

public LiveOperation postAsync(String path,
                               JSONObject body,
                               LiveOperationListener listener,
                               Object userState)

Parameters

Name | Datatype | Description
path | String | The path to the file/resource to post.
body | JSONObject | The message body of the post request.
listener | LiveOperationListener | The listener that is called when the post request either completes or throws an error.
userState | Object | An arbitrary object that is used to determine the caller of the method.

Returns

Type: LiveOperation

The LiveOperation that contains the JSON result.

Defined in

LiveConnectClient.java

Exceptions

Type: IllegalArgumentException

The path is empty or the path is an absolute URI.

Type: NullPointerException

The path parameters are null.

Remarks

This method uses an HTTP POST call to the Live Connect Representational State Transfer (REST) API.

LiveOperationListener.onComplete(LiveOperation) is called on success. Otherwise, LiveOperationListener.onError(LiveOperationException, LiveOperation) is called. Both of these methods are called on the main/UI thread.

See also

LiveConnectClient class


LiveConnectClient.put(String, JSONObject) method

Performs a synchronous PUT that updates a resource with a given path and message path. If the resource does not exist, it creates a new one.

Signature

public LiveOperation put(String path, JSONObject body) throws LiveOperationException

Parameters

Name | Datatype | Description
path | String | The path to the file/resource to put.
body | JSONObject | The message body of the put request.

object_id

Returns

Type: LiveOperation

The LiveOperation that contains the JSON result.

Defined in

LiveConnectClient.java

Exceptions

Type: LiveOperationException

There is an error during the execution of the request.

Type: IllegalArgumentException

The path is empty or the path is an absolute URI.

Type: NullPointerException

The path parameters are null.

Remarks

This method uses an HTTP PUT call to the Live Connect Representational State Transfer (REST) API.

See also

LiveConnectClient class


LiveConnectClient.put(String, String) method

Performs a synchronous PUT that updates a resource with a given path and message path. If the resource does not exist, it creates a new one.

Signature

public LiveOperation put(String path, String body) throws LiveOperationException

Parameters

Name | Datatype | Description
path | String | The path to the file/resource to put.
body | String | The message body of the put request.

object_id

Returns

Type: LiveOperation

The representation of the data returned from the Live Connect Representational State Transfer (REST) API.

Defined in

LiveConnectClient.java

Exceptions

Type: LiveOperationException

There is an error during the execution of the request.

Type: IllegalArgumentException

The path is empty or the path is an absolute URI.

Type: NullPointerException

The path parameters are null.

Remarks

This method uses an HTTP PUT call to the Live Connect Representational State Transfer (REST) API.

See also

LiveConnectClient class


LiveConnectClient.putAsync(String, String, LiveOperationListener) method

Performs an asynchronous PUT that updates a resource with a given path, message path, and listener. If the resource does not exist, it creates a new one.

Signature

public LiveOperation putAsync(String path, String body, LiveOperationListener listener)

Parameters

Name | Datatype | Description
path | String | The path to the file/resource to put.
body | String | The message body of the put request.
listener | LiveOperationListener | The listener that is called when the put request either completes or throws an error.

Returns

Type: LiveOperation

The representation of the data returned from the Live Connect Representational State Transfer (REST) API.

Defined in

LiveConnectClient.java

Exceptions

Type: IllegalArgumentException

The path is empty or the path is an absolute URI.

Type: NullPointerException

The path parameters are null.

Remarks

This method uses an HTTP PUT call to the Live Connect Representational State Transfer (REST) API.

LiveOperationListener.onComplete(LiveOperation) is called on success. Otherwise, LiveOperationListener.onError(LiveOperationException, LiveOperation) is called. Both of these methods are called on the main/UI thread.

See also

LiveConnectClient class


LiveConnectClient.putAsync(String, String, LiveOperationListener, Object) method

Performs an asynchronous PUT that updates a resource with a given path, message path, listener, and user state. If the resource does not exist, it creates a new one.

Signature

public LiveOperation putAsync(String path,
                              String body,
                              LiveOperationListener listener,
                              Object userState)

Parameters

Name | Datatype | Description
path | String | The path to the file/resource to put.
body | String | The message body of the put request.
listener | LiveOperationListener | The listener that is called when the put request either completes or throws an error.
userState | Object | An arbitrary object that is used to determine the caller of the method.

Returns

Type: LiveOperation

The representation of the data returned from the Live Connect Representational State Transfer (REST) API.

Defined in

LiveConnectClient.java

Exceptions

Type: IllegalArgumentException

The path is empty or the path is an absolute URI.

Type: NullPointerException

The path parameters are null.

Remarks

This method uses an HTTP PUT call to the Live Connect Representational State Transfer (REST) API.

LiveOperationListener.onComplete(LiveOperation) is called on success. Otherwise, LiveOperationListener.onError(LiveOperationException, LiveOperation) is called. Both of these methods are called on the main/UI thread.

See also

LiveConnectClient class


LiveConnectClient.putAsync(String, JSONObject, LiveOperationListener) method

Performs an asynchronous PUT that updates a resource with a given path, message path, and listener. If the resource does not exist, it creates a new one.

Signature

public LiveOperation putAsync(String path, JSONObject body, LiveOperationListener listener)

Parameters

Name | Datatype | Description
path | String | The path to the file/resource to put.
body | JSONObject | The message body of the put request.
listener | LiveOperationListener | The listener that is called when the put request either completes or throws an error.

Returns

Type: LiveOperation

The LiveOperation that contains the JSON result.

Defined in

LiveConnectClient.java

Exceptions

Type: IllegalArgumentException

The path is empty or the path is an absolute URI.

Type: NullPointerException

The path parameters are null.

Remarks

This method uses an HTTP PUT call to the Live Connect Representational State Transfer (REST) API.

LiveOperationListener.onComplete(LiveOperation) is called on success. Otherwise, LiveOperationListener.onError(LiveOperationException, LiveOperation) is called. Both of these methods are called on the main/UI thread.

See also

LiveConnectClient class


LiveConnectClient.putAsync(String, JSONObject, LiveOperationListener, Object) method

Performs an asynchronous PUT that updates a resource with a given path, message path, listener, and user state. If the resource does not exist, it creates a new one.

Signature

public LiveOperation putAsync(String path,
                              JSONObject body,
                              LiveOperationListener listener,
                              Object userState)

Parameters

Name | Datatype | Description
path | String | The path to the file/resource to put.
body | JSONObject | The message body of the put request.
listener | LiveOperationListener | The listener that is called when the put request either completes or throws an error.
userState | Object | An arbitrary object that is used to determine the caller of the method.

Returns

Type: LiveOperation

The LiveOperation that contains the JSON result.

Defined in

LiveConnectClient.java

Exceptions

Type: IllegalArgumentException

The path is empty or the path is an absolute URI.

Type: NullPointerException

The path parameters are null.

Remarks

This method uses an HTTP PUT call to the Live Connect Representational State Transfer (REST) API.

LiveOperationListener.onComplete(LiveOperation) is called on success. Otherwise, LiveOperationListener.onError(LiveOperationException, LiveOperation) is called. Both of these methods are called on the main/UI thread.

See also

LiveConnectClient class


LiveConnectClient upload(String, String, File) method

Uploads a resource with a given path, filename, and file contents.

Signature

public LiveOperation upload(String path,
                            String filename,
                            File file) throws LiveOperationException

Parameters

Name | Datatype | Description
path | String | The path to the file/resource to upload.
filename | String | The file name of the new resource.
file | File | File is an object that represents a file on the file system that gets uploaded.

Returns

Type: LiveOperation

The LiveOperation that contains the JSON response.

Defined in

LiveConnectClient.java

Exceptions

Type: LiveOperationException

There is an error during the execution of the request.

Remarks

This method uses an HTTP PUT call to the Live Connect Representational State Transfer (REST) API and returns the response as an InputStream.

See also

LiveConnectClient class


LiveConnectClient upload(String, String, File, OverwriteOption) method

Uploads a resource with a given path, filename, file contents, and gives the option to overwrite an existing resource.

Signature

public LiveOperation upload(String path,
                            String filename,
                            File file,
                            OverwriteOption overwrite) throws LiveOperationException

Parameters

Name | Datatype | Description
path | String | The path to the file/resource to upload.
filename | String | The file name of the new resource.
file | File | File is an object that represents a file on the file system that gets uploaded.
overwrite | OverwriteOption | The file overwrite behavior if a file with the same name already exists in the upload location.

Returns

Type: LiveOperation

The LiveOperation that contains the JSON response.

Defined in

LiveConnectClient.java

Exceptions

Type: LiveOperationException

There is an error during the execution of the request.

Remarks

This method uses an HTTP PUT call to the Live Connect Representational State Transfer (REST) API and returns the response as an InputStream.

See also

LiveConnectClient class


LiveConnectClient.upload(String, String, InputStream) method

Uploads a resource with a given path, filename, and file contents.

Signature

public LiveOperation upload(String path,
                            String filename,
                            InputStream file) throws LiveOperationException

Parameters

Name | Datatype | Description
path | String | The path to the file/resource to upload.
filename | String | The file name of the new resource.
file | InputStream | The file contents of the upload.

Returns

Type: LiveOperation

The LiveOperation that contains the JSON response.

Defined in

LiveConnectClient.java

Exceptions

Type: LiveOperationException

There is an error during the execution of the request.

Remarks

This method uses an HTTP PUT call to the Live Connect Representational State Transfer (REST) API and returns the response as an InputStream.

See also

LiveConnectClient class


LiveConnectClient.upload(String, String, InputStream, OverwriteOption) method

Uploads a resource with a given path, filename, file contents, and gives the option to overwrite an existing resource.

Signature

public LiveOperation upload(String path,
                            String filename,
                            InputStream file,
                            OverwriteOption overwrite) throws LiveOperationException

Parameters

Name | Datatype | Description
path | String | The path to the file/resource to upload.
filename | String | The file name of the new resource.
file | InputStream | The file contents of the upload.
overwrite | OverwriteOption | The file overwrite behavior if a file with the same name already exists in the upload location.

Returns

Type: LiveOperation

The LiveOperation that contains the JSON response.

Defined in

LiveConnectClient.java

Exceptions

Type: LiveOperationException

There is an error during the execution of the request.

Remarks

This method uses an HTTP PUT call to the Live Connect Representational State Transfer (REST) API and returns the response as an InputStream.

See also

LiveConnectClient class


LiveConnectClient uploadAsync(String, String, File, OverwriteOption, LiveUploadOperationListener, Object)

Performs an asynchronous upload of a resource with a given path, filename, file contents, listener, user state, and the option to overwrite an existing file.

Signature

public LiveOperation uploadAsync(String path,
                                 String filename,
                                 File file,
                                 OverwriteOption overwrite,
                                 LiveUploadOperationListener listener,
                                 Object userState)

Parameters

Name | Datatype | Description
path | String | The path to the file/resource to upload.
filename | String | The file name of the new resource.
file | File | The file contents of the upload.
overwrite | OverwriteOption | The file overwrite behavior if a file with the same name already exists in the upload location.
listener | LiveUploadOperationListener | The listener to call when the upload request completes, progresses, or has an error.
userState | Object | An arbitrary object that is used to determine the caller of the method.

Returns

Type: LiveOperation

The LiveOperation associated with the request.

Defined in

LiveConnectClient.java

Remarks

This method uses an HTTP PUT call to the Live Connect Representational State Transfer (REST) API.

LiveUploadOperationListener.onUploadCompleted(LiveOperation) is called on success. LiveUploadOperationListener.onUploadProgress(int, int, LiveOperation) is called on upload progress. Both of these methods are called on the main/UI thread. Otherwise, LiveUploadOperationListener.onUploadFailed(LiveOperationException, LiveOperation) is called. This method is not called on the main/UI thread.

See also

LiveConnectClient class


LiveConnectClient uploadAsync(String, String, File, LiveUploadOperationListener)

Performs an asynchronous upload of a resource with a given path, filename, file contents, and listener.

Signature

public LiveOperation uploadAsync(String path,
                                 String filename,
                                 File file,
                                 LiveUploadOperationListener listener)

Parameters

Name | Datatype | Description
path | String | The path to the file/resource to upload.
filename | String | The file name of the new resource.
file | File | The file contents of the upload.
listener | LiveUploadOperationListener | The listener to call when the upload request completes, progresses, or has an error.

Returns

Type: LiveOperation

The LiveOperation associated with the request.

Defined in

LiveConnectClient.java

Remarks

This method uses an HTTP PUT call to the Live Connect Representational State Transfer (REST) API.

LiveUploadOperationListener.onUploadCompleted(LiveOperation) is called on success. LiveUploadOperationListener.onUploadProgress(int, int, LiveOperation) is called on upload progress. Both of these methods are called on the main/UI thread. Otherwise, LiveUploadOperationListener.onUploadFailed(LiveOperationException, LiveOperation) is called. This method is not called on the main/UI thread.

See also

LiveConnectClient class


LiveConnectClient uploadAsync(String, String, File, LiveUploadOperationListener, Object)

Performs an asynchronous upload of a resource with a given path, filename, file contents, listener, and user state.

Signature

public LiveOperation uploadAsync(String path,
                                 String filename,
                                 File file,
                                 LiveUploadOperationListener listener,
                                 Object userState)

Parameters

Name | Datatype | Description
path | String | The path to the file/resource to upload.
filename | String | The file name of the new resource.
file | File | The file contents of the upload.
listener | LiveUploadOperationListener | The listener to call when the upload request completes, progresses, or has an error.
userState | Object | An arbitrary object that is used to determine the caller of the method.

Returns

Type: LiveOperation

The LiveOperation associated with the request.

Defined in

LiveConnectClient.java

Remarks

This method uses an HTTP PUT call to the Live Connect Representational State Transfer (REST) API.

LiveUploadOperationListener.onUploadCompleted(LiveOperation) is called on success. LiveUploadOperationListener.onUploadProgress(int, int, LiveOperation) is called on upload progress. Both of these methods are called on the main/UI thread. Otherwise, LiveUploadOperationListener.onUploadFailed(LiveOperationException, LiveOperation) is called. This method is not called on the main/UI thread.

See also

LiveConnectClient class


LiveConnectClient.uploadAsync(String, String, InputStream, OverwriteOption, LiveUploadOperationListener, Object) method

Performs an asynchronous upload of a resource with a given path, filename, file contents, listener, user state, and gives the option to overwrite an existing resource.

Signature

public LiveOperation uploadAsync(String path,
                                 String filename,
                                 InputStream file,
                                 OverwriteOption overwrite,
                                 LiveUploadOperationListener listener,
                                 Object userState)

Parameters

Name | Datatype | Description
path | String | The path to the file/resource to upload. The object_id of the resource to upload.
filename | String | The file name of the new resource.
file | InputStream | The file contents of the upload.
overwrite | OverwriteOption | The file overwrite behavior if a file with the same name already exists in the upload location.
listener | LiveUploadOperationListener | The listener to call when the upload request completes, progresses, or has an error.
userState | Object | An arbitrary object that is used to determine the caller of the method.

Returns

Type: LiveOperation

The LiveOperation associated with the request.

Defined in

LiveConnectClient.java

Remarks

This method uses an HTTP PUT call to the Live Connect Representational State Transfer (REST) API and returns the response as an InputStream.

LiveUploadOperationListener.onUploadCompleted(LiveOperation) is called on success. LiveUploadOperationListener.onUploadProgress(int, int, LiveOperation) is called on upload progress. Both of these methods are called on the main/UI thread. Otherwise, LiveUploadOperationListener.onUploadFailed(LiveOperationException, LiveOperation) is called. This method is not called on the main/UI thread.

See also

LiveConnectClient class


LiveConnectClient.uploadAsync(String, String, InputStream, LiveUploadOperationListener) method

Performs an asynchronous upload of a resource with a given path, filename, file contents, and listener.

Signature

public LiveOperation uploadAsync(String path,
                                 String filename,
                                 InputStream input,
                                 LiveUploadOperationListener listener)

Parameters

Name | Datatype | Description
path | String | The path to the file/resource to upload.
filename | String | The file name of the new resource.
input | InputStream | The file contents of the upload.
overwriteExisting | Boolean | If true, overwrites the existing resource.

Returns

Type: LiveOperation

The LiveOperation associated with the request.

Defined in

LiveConnectClient.java

Remarks

This method uses an HTTP PUT call to the Live Connect Representational State Transfer (REST) API and returns the response as an InputStream.

LiveUploadOperationListener.onUploadCompleted(LiveOperation) is called on success. LiveUploadOperationListener.onUploadProgress(int, int, LiveOperation) is called on upload progress. Both of these methods are called on the main/UI thread. Otherwise, LiveUploadOperationListener.onUploadFailed(LiveOperationException, LiveOperation) is called. This method is not called on the main/UI thread.

See also

LiveConnectClient class


LiveConnectClient.uploadAsync(String, String, InputStream, LiveUploadOperationListener, Object) method

Performs an asynchronous upload of a resource with a given path, filename, file contents, listener, and user state.

Signature

public LiveOperation uploadAsync(String path,
                                 String filename,
                                 InputStream input,
                                 LiveUploadOperationListener listener,
                                 Object userState)

Parameters

Name | Datatype | Description
path | String | The path to the file/resource to upload.
filename | String | The file name of the new resource.
input | InputStream | The file contents of the upload.
listener | LiveUploadOperationListener | The listener to call when the upload request completes, progresses, or has an error.
userState | Object | An arbitrary object that is used to determine the caller of the method.

Returns

Type: LiveOperation

The LiveOperation associated with the request.

Defined in

LiveConnectClient.java

Remarks

This method uses an HTTP PUT call to the Live Connect Representational State Transfer (REST) API and returns the response as an InputStream.

LiveUploadOperationListener.onUploadCompleted(LiveOperation) is called on success. LiveUploadOperationListener.onUploadProgress(int, int, LiveOperation) is called on upload progress. Both of these methods are called on the main/UI thread. Otherwise, LiveUploadOperationListener.onUploadFailed(LiveOperationException, LiveOperation) is called. This method is not called on the main/UI thread.

See also

LiveConnectClient class


LiveConnectSession class

Represents a Live Connect session.

Signature

public class LiveConnectSession

Methods

Name | Description
addPropertyChangeListener(PropertyChangeListener) method | Adds a PropertyChangeListener to the session that receives notification when any property is changed.
addPropertyChangeListener(String, PropertyChangeListener) method | Adds a PropertyChangeListener to the session that receives notification when a specific property is changed.
getAccessToken method | Gets the access token for the signed-in, connected user.
getAuthenticationToken method | Gets a user-specific token that provides information to an app so that it can validate the user.
getExpiresIn method | Gets the exact time when a session expires.
getRefreshToken method | Gets a user-specific refresh token that the app can use to refresh the access token.
getScopes method | Gets the scopes that the user has consented to.
toString method | Gets a string representation of the LiveConnectSession.
getTokenType method | Gets the type of token.
isExpired method | Boolean that indicates if the session is expired.
getPropertyChangeListeners method | Gets an array of all PropertyChangeListeners for this session.
getPropertyChangeListeners(String) method | Gets an array of all PropertyChangeListeners for a specific property for this session.
removePropertyChangeListener(PropertyChangeListener) method | Removes all PropertyChangeListeners on a session.
removePropertyChangeListener(String, PropertyChangeListener) method | Removes a PropertyChangeListener for a specific property on a session.

Defined in

LiveConnectSession.java

Package

com.microsoft.live

See also

com.microsoft.live package


LiveConnectSession.addPropertyChangeListener(PropertyChangeListener) method

Adds a PropertyChangeListener to the session that receives notification when any property is changed.

Signature

public void addPropertyChangeListener(PropertyChangeListener listener)

Parameters

Name | Datatype | Description
listener | PropertyChangeListener | The PropertyChangeListener.

Returns

Nothing.

Defined in

LiveConnectSession.java

Remarks

This method listens to all property changes.

See also

LiveConnectSession class


LiveConnectSession.addPropertyChangeListener(String, PropertyChangeListener) method

Adds a PropertyChangeListener to the session that receives notification when a specific property is changed.

Signature

public void addPropertyChangeListener(String propertyName, PropertyChangeListener listener)

Parameters

Name | Datatype | Description
propertyName | String | The name of the property to track.
listener | PropertyChangeListener | The PropertyChangeListener.

Returns

Nothing.

Defined in

LiveConnectSession.java

See also

LiveConnectSession class


LiveConnectSession.getAccessToken method

Gets the access token for the signed-in, connected user.

Signature

public String getAccessToken()

Parameters

This method has no parameters.

Returns

The access token.

Defined in

LiveConnectSession.java

See also

LiveConnectSession class


LiveConnectSession.getAuthenticationToken method

Gets a user-specific token that provides information to an app so that it can validate the user.

Signature

public String getAuthenticationToken()

Parameters

This method has no parameters.

Returns

An authentication token.

Defined in

LiveConnectSession.java

See also

LiveConnectSession class


LiveConnectSession.getExpiresIn method

Gets the exact time when a session expires.

Signature

public Date getExpiresIn()

Parameters

This method has no parameters.

Returns

The expiration time.

Defined in

LiveConnectSession.java

Remarks

The expiration unit is in seconds since 1970/01/01.

See also

LiveConnectSession class


LiveConnectSession.getRefreshToken method

Gets a user-specific refresh token that the app can use to refresh the access token.

Signature

public String getRefreshToken()

Parameters

This method has no parameters.

Returns

The refresh token.

Defined in

LiveConnectSession.java

See also

LiveConnectSession class


LiveConnectSession.getScopes method

Gets the scopes that the user has consented to.

Signature

public Iterable<String> getScopes()

Parameters

This method has no parameters.

Returns

The scopes.

Defined in

LiveConnectSession.java

Remarks

If the user consents to some permissions, including the first time, this method retrieves the list of consented scopes. If this is an incremental permission request and scopes is null, the user rejected the permission request. If a user rejects a permission request, this is explicitly returned as a LiveAuthException error. This object is never null.

See also

LiveConnectSession class


LiveConnectSession.toString method

Retrieves a string representation of the LiveConnectSession.

Signature

public String toString()

Parameters

This method has no parameters.

Returns

The LiveConnectSession.

Defined in

LiveConnectSession.java

See also

LiveConnectSession class


LiveConnectSession.getTokenType method

Gets the type of token.

Signature

public String getTokenType()

Parameters

This method has no parameters.

Returns

The token type.

Defined in

LiveConnectSession.java

See also

LiveConnectSession class


LiveConnectSession.isExpired method

Boolean that indicates if the session is expired.

Signature

public boolean isExpired()

Parameters

This method has no parameters.

Returns

Returns true if the session is expired.

Defined in

LiveConnectSession.java

See also

LiveConnectSession class


LiveConnectSession.getPropertyChangeListeners method

Gets an array of all PropertyChangeListeners for this session.

Signature

public PropertyChangeListener[] getPropertyChangeListeners()

Parameters

This method has no parameters.

Returns

An array of PropertyChangeListeners.

Defined in

LiveConnectSession.java

See also

LiveConnectSession class


LiveConnectSession.getPropertyChangeListeners(String) method

Gets an array of all PropertyChangeListeners for a specific property for this session.

Signature

public PropertyChangeListener[] getPropertyChangeListeners(String propertyName)

Parameters

Name | Datatype | Description
propertyName | String | The name of the property to get.

Returns

An array of PropertyChangeListeners.

Defined in

LiveConnectSession.java

See also

LiveConnectSession class


LiveConnectSession.removePropertyChangeListener(PropertyChangeListener) method

Removes all PropertyChangeListeners on a session.

Signature

public void removePropertyChangeListener(PropertyChangeListener listener)

Parameters

Name | Datatype | Description
listener | PropertyChangeListener | The PropertyChangeListener.

Returns

Nothing.

Defined in

LiveConnectSession.java

See also

LiveConnectSession class


LiveConnectSession.removePropertyChangeListener(String, PropertyChangeListener) method

Removes a PropertyChangeListener for a specific property on a session.

Signature

public void removePropertyChangeListener(String propertyName,
                                         PropertyChangeListener listener)

Parameters

Name | Datatype | Description
propertyName | String | The name of the property being tracked.
listener | PropertyChangeListener | The PropertyChangeListener.

Returns

Nothing.

Defined in

LiveConnectSession.java

See also

LiveConnectSession class


LiveDownloadOperation class

Represents data returned from a download call to the Live Connect Representational State Transfer (REST) API.

Signature

public class LiveDownloadOperation

Methods

Name | Description
getMethod method | Gets the type of HTTP method used to make the call.
getPath method | Gets the path for the stream object.
getStream method | Gets the stream object that contains the downloaded file.
getUserState method | Gets the user state.

Defined in

LiveDownloadOperation.java

Package

com.microsoft.live

See also

com.microsoft.live package


LiveDownloadOperation.getMethod method

Gets the type of HTTP method used to make the call.

Signature

public String getMethod()

Parameters

This method has no parameters.

Returns

The method type.

Defined in

LiveDownloadOperation.java

See also

LiveDownloadOperation class


LiveDownloadOperation.getPath method

Gets the path for the stream object.

Signature

public String getPath()

Parameters

This method has no parameters.

Returns

The stream object path.

Defined in

LiveDownloadOperation.java

See also

LiveDownloadOperation class


LiveDownloadOperation.getStream method

Gets the stream object that contains the downloaded file.

Signature

public InputStream getStream()

Parameters

This method has no parameters.

Returns

The stream object.

Defined in

LiveDownloadOperation.java

See also

LiveDownloadOperation class


LiveDownloadOperation.getUserState method

Gets the user state.

Signature

public Object getUserState()

Parameters

This method has no parameters.

Returns

The user state.

Defined in

LiveDownloadOperation.java

See also

LiveDownloadOperation class


LiveDownloadOperationListener interface

Represents any functionality related to downloads that works with the Live Connect Representational State Transfer (REST) API.

Signature

public class LiveDownloadOperationListener

Methods

Name | Description
onDownloadCompleted(LiveDownloadOperation) method | Called when the associated download operation call completes.
onDownloadFailed(LiveOperationException, LiveOperation) method | Called when the associated Representational State Transfer (REST) API operation call fails.
onDownloadProgress(int, int, LiveDownloadOperation) method | Updates the progression of the download.

Defined in

LiveDownloadOperationListener.java

Package

com.microsoft.live

Remarks

The class that implements this interface is passed in with the associated operation that is invoked.

See also

com.microsoft.live package


LiveDownloadOperationListener.onDownloadCompleted(LiveDownloadOperation) method

Called when the associated download operation call completes.

Signature

public void onDownloadCompleted(LiveDownloadOperation operation)

Parameters

Name | Datatype | Description
operation | LiveDownloadOperation | The LiveDownloadOperation object.

Returns

Nothing.

Defined in

LiveDownloadOperationListener.java

See also

LiveDownloadOperationListener interface


LiveDownloadOperationListener.onDownloadFailed(LiveOperationException, LiveDownloadOperation) method

Called when the associated Representational State Transfer (REST) operation call fails.

Signature

public void onDownloadFailed(LiveOperationException exception,
                             LiveDownloadOperation operation)

Parameters

Name | Datatype | Description
exception | LiveOperationException | The error returned by the REST operation call.
operation | LiveDownloadOperation | The LiveDownloadOperation object.

Returns

Nothing.

Defined in

LiveDownloadOperationListener.java

See also

LiveDownloadOperationListener interface


LiveDownloadOperationListener.onDownloadProgress(int, int, LiveDownloadOperation) method

Updates the progression of the download.

Signature

public void onDownloadProgress(int totalBytes,
                                   int bytesRemaining,
                                   LiveDownloadOperation operation);

Parameters

Name | Datatype | Description
totalBytes | int | The total bytes downloaded.
bytesRemaining | int | The bytes remaining to download.
operation | LiveDownloadOperation | The LiveDownloadOperation object.

Returns

Nothing.

Defined in

LiveDownloadOperationListener.java

See also

LiveDownloadOperationListener interface


LiveOperation class

Represents data returned from the Live Connect Representational State Transfer (REST) API services.

Signature

public class LiveOperation

Methods

Name | Description
cancel method | Cancels the pending request.
getMethod method | Gets the type of HTTP method used to make the call.
getPath method | Gets the path to which the call was made.
getRawResult method | Gets the raw result of the operation in the requested format.
getResult method | Gets the JSON object that is the result of the requesting operation.
getUserState method | Gets the user state that was passed in.

Defined in

LiveOperation.java

Package

com.microsoft.live

See also

com.microsoft.live package


LiveOperation Cancel method

Cancels the pending request.

Signature

public void cancel()

Parameters

This method has no parameters.

Returns

Nothing.

Defined in

LiveOperation.java

Remarks

Under some circumstances, the cancel operation may not actually cancel the operation. For example, if the user is trying to cancel an upload operation, it is possible that the upload finishes before the cancel operation takes place.

See also

LiveOperation class


LiveOperation.getMethod method

Gets the type of HTTP method used to make the call.

Signature

public String getMethod()

Parameters

This method has no parameters.

Returns

The method type.

Defined in

LiveOperation.java

See also

LiveOperation class


LiveOperation.getPath method

Gets the path of the request.

Signature

public String getPath()

Parameters

This method has no parameters.

Returns

The path.

Defined in

LiveOperation.java

See also

LiveOperation class


LiveOperation.getRawResult method

Gets the raw result of the operation in the requested format.

Signature

public String getRawResult()

Parameters

This method has no parameters.

Returns

The raw result or null if there is no result.

Defined in

LiveOperation.java

See also

LiveOperation class


LiveOperation.getResult method

Gets the JavaScript Object Notation (JSON) object that contains the parsed result of the requesting operation.

Signature

public JSONObject getResult()

Parameters

This method has no parameters.

Returns

The JSON object result.

Defined in

LiveOperation.java

See also

LiveOperation class


LiveOperation.getUserState method

Gets the user state that was passed in.

Signature

public Object getUserState()

Parameters

This method has no parameters.

Returns

The user state.

Defined in

LiveOperation.java

See also

LiveOperation class


LiveOperationException class

Represents errors that occur when making requests to the Representational State Transfer (REST) API.

Signature

public class LiveOperationException extends Exception

Defined in

LiveOperationException.java

Package

com.microsoft.live

See also

com.microsoft.live package


LiveOperationListener interface

Called when an operation finishes or has an error.

Signature

public interface LiveOperationListener

Methods

Name | Description
onComplete(LiveOperation) method | Called when the associated Representational State Transfer (REST) API operation call completes.
onError(LiveOperationException, LiveOperation) method | Called when the associated Representational State Transfer (REST) API operation call fails.

Defined in

LiveOperationListener.java

Package

com.microsoft.live

See also

com.microsoft.live package


LiveOperationListener.onComplete(LiveOperation) method

Called when the associated Representational State Transfer (REST) operation call completes.

Signature

public void onComplete(LiveOperation operation)

Parameters

Name | Datatype | Description
operation | LiveOperation | The LiveOperation object.

Returns

Nothing.

Defined in

LiveOperationListener.java

See also

LiveOperationListener interface


LiveOperationListener.onError(LiveOperationException, LiveOperation) method

Called when the associated Representational State Transfer (REST) operation call fails.

Signature

public void onError(LiveOperationException exception, LiveOperation operation)

Parameters

Name | Datatype | Description
exception | LiveOperationException | The error returned by the REST operation call.
operation | LiveOperation | The LiveOperation object.

Returns

Nothing.

Defined in

LiveOperationListener.java

See also

LiveOperationListener interface


LiveStatus enumeration

Specifies the status of an operation.

Signature

public enum LiveStatus

Members

Member | Value | Description
UNKNOWN | LiveStatus.UNKNOWN | The status is not known.
CONNECTED | LiveStatus.CONNECTED | The session is connected.
NOT_CONNECTED | LiveStatus.NOT_CONNECTED | The session is not connected.

Defined in

LiveStatus.java

See also

com.microsoft.live package
LiveAuthListener.onAuthComplete method


LiveUploadOperationListener interface

Represents any functionality related to uploads that works with the Live Connect Representational State Transfer (REST) API.

Signature

public interface LiveUploadOperationListener

Methods

Name | Description
onUploadCompleted(LiveOperation) method | Called when the associated upload operation call completes.
onUploadFailed(LiveOperationException, LiveOperation) method | Called when the associated Representational State Transfer (REST) API operation call fails.
onUploadProgress(int, int, LiveOperation) method | Called arbitrarily during the progress of the upload request.

Defined in

LiveUploadOperationListener.java

Package

com.microsoft.live

Remarks

The class that implements this interface is passed in with the associated operation that is invoked.

See also

com.microsoft.live package


LiveUploadOperationListener.onUploadCompleted(LiveOperation) method

Called when the associated upload operation call completes.

Signature

public void onUploadCompleted(LiveOperation operation)

Parameters

Name | Datatype | Description
operation | LiveOperation | The LiveOperation object.

Returns

Nothing.

Defined in

LiveUploadOperationListener.java

See also

LiveUploadOperationListener interface


LiveUploadOperationListener.onUploadFailed(LiveOperationException, LiveOperation) method

Called when the associated Representational State Transfer (REST) operation call fails.

Signature

public void onUploadFailed(LiveOperationException exception, LiveOperation operation)

Parameters

Name | Datatype | Description
exception | LiveOperationException | The error returned by the REST operation call.
operation | LiveOperation | The LiveOperation object.

Returns

Nothing.

Defined in

LiveUploadOperationListener.java

See also

LiveUploadOperationListener interface


LiveUploadOperationListener.onUploadProgress(int, int, LiveOperation) method

Called arbitrarily during the progress of the upload request.

Signature

public void onUploadProgress(int totalBytes, int bytesRemaining, LiveOperation operation)

Parameters

Name | Datatype | Description
totalBytes | int | The total bytes downloaded.
bytesRemaining | int | The bytes remaining to download.
operation | LiveOperation | The LiveOperation object.

Returns

Nothing.

Defined in

LiveUploadOperationListener.java

See also

LiveUploadOperationListener interface


OverwriteOption enumeration

Specifies the overwrite behavior for an incoming file that's uploaded to Microsoft SkyDrive when a file with the same name already exists in the same upload location.

Signature

public enum OverwriteOption

Members

Member | Value | Description
Overwrite | OverwriteOption.Overwrite | Overwrite the existing file with the incoming file.
DoNotOverwrite | OverwriteOption.DoNotOverwrite | Do not overwrite the existing file.
Rename | OverwriteOption.Rename | Do not overwrite the existing file. Instead, SkyDrive will assign the incoming file a new file name as it's being downloaded. Note The file renaming pattern that SkyDrive uses may produce unpredictable file names.

Defined in

OverwriteOption.java

See also

com.microsoft.live package


Topic Not Found

The requested topic was not found. The following are possible causes and solutions.

  • Cause: The topic has a bad link.

    Solution: Send feedback about the topic. To provide feedback for a topic on the MSDN site, go to the page and click "Click to Rate and Give Feedback". To provide feedback for an offline topic, go to the page and click "Contact Us".

  • Cause: You are using a local installation of the MSDN Library, but you did not install the component that contains the topic.

    Solution: Install the complete SDK documentation using the latest MSDN CD.

  • Cause: You are using a local installation of the SDK, but you did not install the component that contains the topic.

    Solution: Install the complete SDK documentation from the latest SDK.

Note that you can also download the latest SDK documentation from the Microsoft Download Center or view the SDK online on MSDN.