Export (0) Print
Expand All

Live SDK developer guide

Introducing Live Connect

More than 500 million people use services like Microsoft account, Microsoft OneDrive, and Outlook.com. 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 Microsoft account, OneDrive, and Outlook.com.

The Live Connect APIs use industry standard protocols such as OAuth 2.0 and JavaScript Object Notation (JSON). 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:

  • OneDrive for working with documents and media. Your apps can use the Live Connect APIs to create, read, update, and delete a OneDrive user's folders, files, albums, photos, and videos, and to read, create, and delete any associated tags and comments.
  • Outlook.com for working with contacts and calendars. With the Live Connect APIs, your apps can create and read an Outlook.com user's contacts, and can create, read, update, and delete the user's calendars and their associated events.
  • 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

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), and JSON.

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

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 Outlook.com contacts list, it would request the wl.basic scope through Live Connect. Live Connect prompts the user to sign in to Outlook.com (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, Outlook.com). 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 an Outlook.com 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.


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.";
}


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.


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.


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.


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


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.


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]


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]


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]


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.


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


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


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


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.


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.


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

Outlook.com: contacts and calendars

Users store a lot of contacts and calendar events in Outlook.com. 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 Outlook.com:

  • 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 Microsoft Outlook.com (contacts and calendars).

Creating a new contact

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


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]


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]


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.


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


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.


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]


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]


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.


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


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

OneDrive: files and photos

Users store a lot of documents and media on OneDrive. 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 OneDrive:

  • Create, read, update, and delete folders and albums. (An album is a special type of OneDrive 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 OneDrive 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 OneDrive (files and photos).

Reading a folder's properties

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


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]


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]


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.


- (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 OneDrive 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.


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.


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]


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]


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.


- (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 = @"OneDrive 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.


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

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.

Top

 

 

Show:
© 2014 Microsoft