Working with the code examples

Expand
10 out of 22 rated this helpful - Rate this topic

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.

JavaScript code samples

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

default.htm (for Metro style apps using JavaScript only)


<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>JavaScript Code Sample</title>
    <!-- WinJS references -->
    <link href="//Microsoft.WinJS.0.6/css/ui-dark.css" rel="stylesheet">
    <script src="//Microsoft.WinJS.0.6/js/base.js"></script>
    <script src="//Microsoft.WinJS.0.6/js/ui.js"></script>
    <!-- JavaScript Code Sample references -->
    <script src="/js/default.js"></script>
    <link href="/css/default.css" rel="stylesheet">
    <!-- 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>  



</body>
</html>

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.

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


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

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 websites and scripts using JavaScript only; replace YOUR_CLIENT_ID with your app's client ID and YOUR_REDIRECT_URL with your app's redirect URL)


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

callback.htm (for client-side websites 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 code easier to manage, you could put code in a separate file, named gather_info.js in this code sample, that runs when users interact with the app, like clicking buttons.

Top

C# code samples

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 Metro style apps using C# only)


<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; replace the client ID here 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="000000004406774D" 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 Metro style apps using C# only)


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


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


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

namespace WindowsPhoneCodeSample
{
    public partial class MainPage : PhoneApplicationPage
    {
        private LiveAuthClient auth;
        private LiveConnectClient client;
        private LiveConnectSession session;

        public MainPage()
        {
            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;
            }
        }
    }
}


Top

Objective-C code samples

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 (where APP_CLIENT_ID is 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


Java code samples

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 (where MY CLIENT ID is your app's client ID—for example, 00000000603E7410)


package com.live.dev;

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

REST code samples

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

 

 

Build date: 4/26/2012

Did you find this helpful?
(1500 characters remaining)