Export (0) Print
Expand All

Working with the code examples

To make full use of the smaller code examples in the Core concepts, Identity API, Outlook.com API, and OneDrive API 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

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.html (for Windows Store apps using JavaScript only)


<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title>JS_SignIntoSkyDrive</title>

    <!-- WinJS references -->
    <link href="//Microsoft.WinJS.1.0/css/ui-dark.css" rel="stylesheet" />
    <script src="//Microsoft.WinJS.1.0/js/base.js"></script>
    <script src="//Microsoft.WinJS.1.0/js/ui.js"></script>

    <!-- JS_SignIntoSkyDrive references -->
    <link href="/css/default.css" rel="stylesheet" />
    <script src="/js/default.js"></script>

    <!-- Live SDK reference -->
    <script src="///LiveSDKHTML/js/wl.js"></script>
    <script src="js/account.js"></script>
</head>
<body>
    <div>    
        <h1>Live Connect JavaScript Code Sample</h1>
        <button id="sign-in">Sign In</button><br /><br />
        <div id="output">You are not currently signed in.</div>
    </div>
</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.

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

In the default.js file, replace the handler for the app.onactivated event with the following code:



(function () {
    "use strict";

    // Other app initialization code ...
    
    app.onactivated = function (args) {
        if (args.detail.kind === activation.ActivationKind.launch) {
            if (args.detail.previousExecutionState !== activation.ApplicationExecutionState.terminated) {
                
                // TODO: This application has been newly launched. Initialize
                // your application here.

                // Initialize the account settings.
                account.init();

            } else {

                // TODO: This application has been reactivated from suspension.
                // Restore application state here.
            }
            args.setPromise(WinJS.UI.processAll());
        }
    };

})();

account.js (for Windows Store apps using JavaScript only)


/// <reference path="///LiveSDKHTML/js/wl.js" />
var account = (function () {

    var signInButton;

    // Initialize the sign-in page.
    function init() {

        // Initialize the Live SDK APIs.
        WL.init();
        WL.Event.subscribe("auth.login", onLogin);

        // Add event handler to sign-in button.
        signInButton = document.getElementById("sign-in");
        signInButton.onclick = signIn;
    }

    // Sign the user into their Microsoft account.
    function signIn() {
        var session = WL.getSession();
        if (session) {
            log("You are already signed in!")
        }
        else {
            WL.login({ scope: "wl.basic" }).then(
                function () {
                    log("Log in successful");
 
                },
                function (response) {
                    log("Could not connect, status = " + response.status);
                });
        }
    }

    // Get the current session for the user's account.
    function onLogin() {
        var session = WL.getSession();
        if (session) {
            log("You are now signed in.");
        }
    }

    // Output the results to a div in the page.
    function log(message) {
        document.getElementById('output').innerText = message;
    }

    return {
        init: init
    };

})();

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


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 about how to add additional scopes.


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



    </body>
</html>


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


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


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

    <Grid >
        <Button x:Name="signInBtn"  
            Click="SignIn"  
            Content="Sign in" 
            Grid.Row="1" 
            Margin="0,20,0,-38"/>
        <TextBlock Height="32" 
            Foreground="White" 
            HorizontalAlignment="Left" 
            Margin="8,76,0,0" 
            Name="infoTextBlock" 
            VerticalAlignment="Top" 
            Width="419" />
    </Grid>
</Page>

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

In the code-behind file for the Main Page of the Windows Store app, add the following handler for the SignIn button's click event.


        // Signs the user into their Microsoft account.
        private async void SignIn(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;
            }
        }

Note  The preceding code sample prompts the user to consent to the wl.basic 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.

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.


<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 Phone apps using 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


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


#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


<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


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.


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, follow 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 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 - Microsoft OneDrive 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

 

 

Show:
© 2014 Microsoft