Export (0) Print
Expand All

Windows Live Messenger Connect Developer Guide, Version 4.1

Gg251990.note(en-us,MSDN.10).gifNote:
Current information about Live Connect is now available in the Windows Live Developer Center. The information in the following sections is provided for legacy purposes only.

Windows Live® Messenger Connect is a set of JavaScript APIs and REST services that enable you to connect what users do on your site with their Windows Live friends and contacts. By using the Messenger Connect APIs, you can add features such as authentication, instant messaging, and content sharing to your application, creating intuitive experiences that tightly integrate your application with Windows Live.

Messenger Connect focuses on three core scenarios:

  • Identity. Hundreds of millions of Windows Live ID accounts are used every month. With Messenger Connect, your application can help users use their Windows Live IDs to sign in to your site or register a new account on your site quickly. Because many users already sign in to Windows Live through other services like Windows Live Hotmail®, they can connect with your site in just a few clicks. You can also automatically fill in registration forms with information such as the user's email address, simplifying the steps that users must follow to register with your site.
  • Social distribution. A newsfeed is associated with each Windows Live user and can be shown to the user's Windows Live Messenger contacts across the Windows Live network. Messenger Connect includes a sharing badge, which enables users to easily share what they're doing on your site with their friends and contacts.
  • Real-time shared experiences. People want to be able to share experiences like inviting friends to your site in real time, chatting with their friends without leaving your site, and seeing who among their friends and contacts are also on your site when they are. Messenger Connect includes a full-featured chat control—a chat room through which users can chat with other people on your site. You can also use the Messenger Connect JavaScript library to enable users to have individual conversations with their friends and contacts without leaving your site. They can even chat with other Windows Live users who are also visiting your site, even if they are not on each other's contact lists.

To learn how to put Messenger Connect to work on your site and engage your users in these compelling scenarios, read on.

Adding Messenger Connect functionality to your website is a straightforward process that typically takes only a short time to complete. The steps to add Messenger Connect are as follows:

  1. Verify that you have a few prerequisites in place.
  2. Register your application with Windows Live.
  3. Identify the scopes that your application will use. (The word scope has a particular meaning for Messenger Connect; more about that soon.)
  4. Add a couple of webpages that manage communications between your application and Windows Live.
  5. Update your webpages with the appropriate HTML namespace attribute and the Messenger Connect <script> and <app> tags.

Prerequisites

One of the advantages to Messenger Connect is that it does not require a long list of prerequisites before you start coding. Still, there are a couple of things to keep in mind before you start your development cycle:

  • Storing user identifiers and consent information. Windows Live assigns each user an identifier, called a CID. If your application will retain user information over a period of time, you must store both the CID and the refresh token, which is used to maintain data access. A good practice is to modify your database or caching structure to store this CID and use it as an index. This approach can help your application access your users' information quickly after they have given their consent for your site to use it.
  • Choosing your implementation. You can implement Messenger Connect technologies using the following methods: user interface (UI) controls, a JavaScript library, and a Representational State Transfer (REST) API service. The Messenger Connect UI controls are ideal for applications that do not require a lot of customization. The JavaScript library picks up where the UI controls leave off, giving you more control over how your application integrates with Windows Live. If you have an existing application that uses server-side code, you can use the Messenger Connect REST API to build solutions.
  • Preparing your privacy statement and terms of service. When you register your application with Windows Live, you provide URLs that point to the privacy statement and terms of service pages on your site. When users choose to use their Windows Live account to sign in to your site, they can click links to these pages to learn about how your site uses their information.

Registering Your Application

To have Windows Live recognize your application, you must register it by using the Windows Live application management site (https://manage.dev.live.com). At this site, your first step is to sign in by using a Windows Live ID account. Your application is associated with this account, so we recommend that you create a Windows Live ID to use specifically for application development. You can also create and use multiple Windows Live ID accounts for use with applications that correspond to your organization's development environments, such as development, test, and production.

After you sign in to the application management site, supply the following information about your application:

  • Application name. Identifies your application to users when they sign in.
  • Application type. Messenger Connect supports several application types; however, the most common application type is Web Application.
  • Domain. Specifies the URL that Windows Live uses to return users to your application after they have signed in. It’s important to remember that you cannot change the domain of your application after you specify it here.

After you supply this information (and agree to read the Windows Live Developer Services Terms of Use), click I accept.

At this point, Windows Live has enough information for you to begin developing and testing your application. Before you move the application into production, however, you might need to configure additional settings—for example, adding a logo for your application. To learn about other available application settings, see Appendix B: Registering and Managing Your Messenger Connect Applications.

Identifying Scopes

To help users maintain control of their information, Messenger Connect requires that applications make specific requests for user data. These requests are grouped into categories called scopes. When a user provides consent for your application to use data, that consent applies only to the scopes that you have specified. For example, to access a user’s Windows Live Messenger contacts and enable that user to send instant messages to those contacts, you would use the Messenger.Signin scope, and any user consent would be limited to that scope. The user must also consent to any change to the scopes that your application uses. For example, if you decide to add the ability to view a user’s profile within your application, you have to ask your user to provide consent again.

For a complete list of scopes, see Messenger Connect Scopes in the Messenger Connect documentation.

Adding the Required Web Pages

You must add two web pages to your web application to integrate it with Messenger Connect: the Channel.html page and a callback handler page.

The Channel.html page exists to help Messenger Connect work with old web browsers. In general, the following Channel.html page is sufficient for most applications.

<html>
<head>
<title>Channel</title>
<script type="text/javascript">
    function parseIsLiveUserResponse(e) {
        var b = "isLiveUser";
        if (!e) return false;
        for (var d = e.substring(1).split("&"), a = [], c = 0; c < d.length; c++) {
            parm = d[c].split("="); a[unescape(parm[0])] = unescape(parm[1])
        }
        if (a[b] !== undefined && a[b].length != 0 && window.parent && window.parent.parent && window.parent.parent.Microsoft !== undefined) {
            var f = a[b] == "true";
            window.parent.parent.Microsoft.Live.App.get_auth().set_isLiveUser(f);
            return true
        }
        return false
    }
    var channelVersion = "4.1";
    function onLoad() {
        try {
            var b = window.location.hash.substr(1), d = window.location.search;
            if (window.location.replace == null) window.location.replace = window.location.assign;
            if (parseIsLiveUserResponse(d)) return;
            if (b.substr(0, 13) == "meshresponse=") {
                b = decodeURIComponent(b); a = window.parent.parent;
                a.Microsoft && a.Microsoft.Live.Services.JSONPCloudRequestHandler.postResult(b)
            }
            else {
                var c = b.split("/")[0], a = null;
                if (c && c != ".parent") a = window.parent.frames[c];
                else a = window.parent.parent; a.Microsoft && a.Microsoft.Live.Channels.Mux._recv_chunk(b)
            }
        }
        catch (e) {
        }
    }
</script>
</head>
<body onload="onLoad();"></body>
</html>

The callback handler page receives and processes the information that is returned by Windows Live after a user signs in with a Windows Live ID. You can either create your own handler or use one of the handler pages that are included with the Live SDK.

The following is an example of a callback handler, written in Microsoft® ASP.NET.

<%@ page language="C#" classname="Callback" autoeventwireup="true" %>
<%@ import namespace="System.Net" %>
<%@ import namespace="System.IO" %>
<script runat="server">   
// For security purposes, create session-specific callback URLs when not serving the callback over HTTPS.
public static string GetUrlForSession()
{
    return ConfigurationManager.AppSettings["wl_wrap_client_callback"] + "?Session=" + HttpContext.Current.Session.SessionID;
}
    
protected void Page_Load(object sender, EventArgs e)
{
    // If we receive a verification code, we can get an access token.
    if (Request.QueryString["wrap_verification_code"] != null)
    {
        // Construct a request for an access token.
        WebRequest tokenRequest = WebRequest.Create("https://consent.live.com/AccessToken.aspx");
        tokenRequest.ContentType = "application/x-www-form-urlencoded";
        tokenRequest.Method = "POST";
        using (StreamWriter writer = new StreamWriter(tokenRequest.GetRequestStream()))
        {
            writer.Write(
                string.Format("wrap_client_id={0}&wrap_client_secret={1}&wrap_callback={2}&wrap_verification_code={3}",
                    HttpUtility.UrlEncode(ConfigurationManager.AppSettings["wl_wrap_client_id"]),
                    HttpUtility.UrlEncode(ConfigurationManager.AppSettings["wl_wrap_client_secret"]),
                    HttpUtility.UrlEncode(GetUrlForSession()),
                    HttpUtility.UrlEncode(Request.QueryString["wrap_verification_code"])
            ));
        }
            
        // Get the response to our token request.
        WebResponse tokenResponse = tokenRequest.GetResponse();

        // Read the first line of the response body.
        string tokenResponseText = new StreamReader(tokenResponse.GetResponseStream()).ReadLine();

        // Parse the response body (format: 'x-www-form-urlencoded').
        NameValueCollection tokenResponseData = HttpUtility.ParseQueryString(tokenResponseText);

        // Store response data in session state.
        Session["wl_wrap_access_token"] = tokenResponseData["wrap_access_token"];

        // Store data in cookies where the Messenger Connect JavaScript library picks them up.
        Response.Cookies["c_clientId"].Value = ConfigurationManager.AppSettings["wl_wrap_client_id"];
        Response.Cookies["c_clientState"].Value = Request.QueryString["wrap_client_state"];
        Response.Cookies["c_scope"].Value = Request.QueryString["exp"];
        Response.Cookies["c_accessToken"].Value = tokenResponseData["wrap_access_token"];
        Response.Cookies["c_expiry"].Value = tokenResponseData["wrap_access_token_expires_in"];
        Response.Cookies["c_uid"].Value = tokenResponseData["uid"];
        Response.Cookies["lca"].Value = "done";
    }
}
</script>
<!DOCTYPE html>
<html>
<body onload="onLoad()">
    <script type="text/javascript">
        var windowClose = window.close;
        window.close = function () {
            window.open("", "_self");
            windowClose();
        }
        function onLoad() {
            window.close();
        }
    </script>
</body>
</html>

You must make two additional pages available on your site when you integrate with Messenger Connect:

  • Terms of Service page. Contains all the information that a user needs to know about how your application uses Windows Live data. The consent page that users see when they click a sign-in link on your site contains a link to this Terms of Service page.
  • Privacy page. Contains your application's privacy statement. As with the Terms of Service page, the consent page presents a link to this page.

Updating Your Application to Use Messenger Connect

To integrate Messenger Connect features into your web application, you add the following to each page:

  • The Messenger Connect namespace
  • The JavaScript loader script
  • An application control

Adding the Messenger Connect namespace to your application makes it possible also to quickly add one of the JavaScript UI controls, such as the Sign-in control. To add the namespace to your application, insert the following attribute into the <html> tag.

xmlns:wl="http://apis.live.net/js/2010

If you do not have access to the <html> tag or do not want to add this namespace to your pages, you have the option of adding JavaScript controls dynamically. For more information about doing that, see Declarative vs. Imperative Programming.

The following <script> tag links the JavaScript loader class to your application.

<script type="text/javascript" src="http://js.live.net/4.1/loader.js"></script> 

The Application control, which can be implemented by means of the <app> tag, contains information about your specific application. This information is used when your site attempts to exchange information with Windows Live. An example of an <app> tag is as follows.

<wl:app 
    client-id="***YOUR CLIENT ID***"
    scope="***YOUR SCOPES***"
    callback-url="***YOUR CALLBACK URL***"
    channel-url="***YOUR CHANNEL URL***"
    onload="appLoaded">
</wl:app>

The following is an example of a fully configured <app> tag.

<wl:app
    channel-url="http://www.contoso.com/channel.htm"
    callback-url="http://www.contoso.com/callback.aspx?<%=SessionId%>"
    client-id="0000000040044B03"
    scope="WL_Profiles.View, Messenger.SignIn"
    onload="appLoaded">
</wl:app>

As soon as your <app> tag is in place, you can start adding Messenger Connect features to your application. For information about the possibilities, see Using the JavaScript Library and Controls.

Before you add Windows Live Messenger Connect, Version 4.1 to your application, you need to understand how Messenger Connect supports user consent and privacy. With Windows Live Messenger Connect, Version 4.1, users control access to their data. Your website cannot access any of a user's information from Windows Live without prior consent from that user. You must request permission for and use only the minimum amount of data necessary to complete a particular scenario. Here are some examples:

  • If a user is signing up at your site and your scenario supports importing information about the user's contacts for viewing purposes only—that is, if this information can be viewed on your site but cannot be changed there—request permission to access only the user's contacts, and only for viewing.
  • If your site enables users to view and update information about the user's activities, ask for permission to update activity information but not other Windows Live user data such as photos.

Messenger Connect provides access to an authenticated user's data by using scopes. For more information, see "Identifying Scopes" earlier in this guide.

The permission granted by the user is valid for one year, unless the user clears the Connect Automatically check box in the consent user interface. (The check box is selected by default.) However, the user can go to the Windows Live consent page (https://consent.live.com) to revoke permissions at any time.

After the access token expires or the user revokes permission, further attempts to access the user's data are denied (a "401 Unauthorized" error is returned). To regain access, your site must obtain permission from the user again. If your site needs to access the Windows Live resources when the user is not present, or without the user seeing the Messenger Connect consent screen again, you can store the refresh token with the user's profile. A refresh token is valid only if the user has granted consent to your application and has not revoked it. If the user revokes consent, the refresh token that you have stored is no longer valid.

The following steps provide an example of the consent user experience.

  1. Your website renders a sign-in button, either by using HTML or by using the Messenger Connect <wl:signin> tag.
  2. The user sees the Messenger Connect button on your site and clicks it to sign in.
  3. A pop-up window opens. This window includes your logo and links to your terms-of-service and privacy statement pages. In these pages, you must clearly explain what you plan to do with the permission granted by the user.
  4. Optionally, the user can click the What will I share? link to see each individual permission that your site requests.

For more information about user consent and privacy, see the Messenger Connect documentation.

As we use it here, identity means the information about users or their contacts that is stored with Windows Live. Identity is a central component to any website that wants to expand its level of user engagement. For example, you can build your site so that users can sign in by using their Windows Live ID. You can use their profile information to personalize your site and reduce the need for them to provide information repeatedly—for example, their first name. Messenger Connect can also help users discover friends and other contacts who also use your application.

You can use identity to encourage users to sign in or register on your site by using their existing credentials. For example, you might allow users to sign in to your site by using a Windows Live ID, Google, or Facebook account. When a user registers on your site by using an address in the hotmail.com domain, your site can use that information to conclude that the identity account is a Windows Live ID. Based on that conclusion, your site can use Messenger Connect to guide the user to connect his or her Windows Live account with your application. Adding logic like this can potentially reduce the time it takes for users to register with your site, which can then increase the success rate of your registration process.

When you start developing with Messenger Connect, think of a user’s identity as divided into three categories:

  • Authentication. This is the process by which users identify themselves, by using their Windows Live ID. This identification can occur when a user provides credentials to sign in to a site, as would be required to make a comment on a blog post. Because many users have probably already signed in with Windows Live ID credentials before visiting your site—for example, by signing in to Hotmail—using Messenger Connect for authentication can reduce the number of steps that a user must take to sign in to your site.
  • Profile access. Profile information is included in the data that users store with Windows Live. After users sign in by means of Windows Live ID, your site can access their profile information, such as their first name. Profile access not only helps you personalize your site to a specific user, it also reduces the amount of repeat information that a user would otherwise have to supply when registering with your site.
  • Relationships. If you know who your users are, you can use Messenger Connect to help them find their Windows Live friends and contacts who might also use your site. Through Messenger Connect, you can even let users know when their friends are also online and using your application.

Authentication

Messenger Connect makes it easy for users to sign in by using their Windows Live ID. You can enable users to sign in to your site either by using a UI control or programmatically, by using the JavaScript library.

Before you implement authentication by using Messenger Connect, you should first ensure that your server-side code has the capability to store user information. Windows Live provides several key pieces of information that you can use to access the user’s data after the user has authorized such access:

  • CID—A hexadecimal value that uniquely identifies a Windows Live ID user. Many of the requests that your site makes to access a user’s data require the CID to identify the user. This is the identifier that you should store in your site’s database and use as an index for the user.
  • Access token—Your site's proof that a user has authorized your access to his or her information. In most cases an access token has a limited lifespan—typically from 4 to 16 hours. For more information about this token, see Acquiring an Access Token.
  • Refresh token—A second type of token, also returned to your site after the user provides consent, that you use to obtain a new access token when the current one has expired. As noted earlier, if the user revokes consent, the refresh token is no longer valid. For more information, see Refreshing an Access Token.

To correctly implement Messenger Connect to support authentication, the server-side code for your site must support long-term storage of a user’s CID and refresh token—for example, in a database. It also must support short-term storage of a user’s access token—for example, in a cookie. To learn more about these practices, see OAuth WRAP.

When your server-side code is ready to process the user’s consent information, you can add sign-in functionality to your site. An easy way to do this is by using the JavaScript Sign In control. To add this control to your site, insert the following tag into your HTML.

<wl:signin></wl:signin>

This control puts the Connect button on your website. You can see this button in action at the Windows Live Interactive SDK.

You can customize the appearance of the button by using one or more of the attributes that are described in the following table.

Attribute Type Required Default value Description

buttonsize

String

No

large

Specifies the size of the button image to display. Valid values are small or large.

signedintext

String

No

sign out

Specifies the text that is displayed by the button when the user is signed in.

signedouttext

String

No

connect

Specifies the text that is displayed by the button when the user is signed out.

theme

String

No

orange

Specifies the color theme to use for the control. Valid values are orange or white.

wlonly

Boolean

No

false

Indicates whether the control should be visible only if the current user is a Windows Live user.

onsignin

Function

No

None

Specifies the callback function to invoke when sign-in is complete.

onsignout

Function

No

None

Specifies the callback function to invoke when the sign-out is complete.

onbeforesignin

Function

No

None

Specifies the callback function to invoke before the application displays the consent UI.

The following is an example of a webpage that uses a customized sign-in control.

<html xmlns="http://www.w3.org/1999/xhtml" xmlns:wl="http://apis.live.net/js/2010">
<head>
    <title>SignIn Example</title>
    <script type="text/javascript" src="http://js.live.net/4.0/loader.js"></script>
    <script type="text/javascript">
        function appLoaded(appLoadedEventArgs) {
        }
        function signInCallback(signInCompletedEventArgs) {
            if (signInCompletedEventArgs.get_resultCode() === Microsoft.Live.AsyncResultCode.success) {
                alert('Sign-in successful.');
            }
            else {
                alert('Sign-in failed.');
            }
        }
    </script>
</head>
<body>
    <wl:app channel-url="/channel.htm" 
        callback-url="/OAuthWrapCallback.ashx?wl_session_id=<%= Session.SessionID %>"
        client-id="<Your-Client-Id>" 
        scope="WL_Profiles.View" 
        onload="{{appLoaded}}">
    </wl:app>
    <wl:signin 
        id="signInControl" 
        signedintext="Signed in. Click to sign out." 
        signedouttext="Click to sign in."
        onsignin="{{signInCallback}}" />
</body>
</html>

Sometimes you might want to construct the sign-in control programmatically—for example, when the Document Object Model (DOM) elements on the page are not known until after the DOM is ready, or when the appearance of the Sign In control is determined dynamically. In these situations, you can use the signIn method of the Messenger Connect JavaScript library to create the Sign In control, as shown in the following example.

<html xmlns="http://www.w3.org/1999/xhtml" xmlns:wl="http://apis.live.net/js/2010">
<head>
    <title> SignIn Example</title>
    <script type="text/javascript" src="http://js.live.net/4.1/loader.js"></script>
    <script type="text/javascript">
        var signInControl, domElement, toggleButton, isDefined, state;
        function appLoaded(appLoadedEventArgs) {
        }
        function addSignInControl() {
            domElement =  $get('SignInControlDiv');
            toggleButton = $get('ToggleSignInButton');
            switch (toggleButton.value) {
                case 'Show SignIn':
                    toggleButton.value = 'Hide SignIn';
                    domElement.style.visibility = 'visible';
                    break;
                case 'Hide SignIn':
                    toggleButton.value = 'Show SignIn';
                    domElement.style.visibility = 'hidden';
                    break;
            }
            // Create a new Sign In control.
            if (!isDefined) {
                Microsoft.Live.Core.Loader.load(['microsoft.live.ui'], function () {
                    signInControl = new Microsoft.Live.UI.SignIn(domElement);
                    signInControl.set_signedInText('Click to sign out!');
                    signInControl.set_signedOutText('Click to sign in.');
                    signInControl.add_signin(signInCallback);
                    signInControl.add_signout(signOutCallback);
                    signInControl.initialize();
                    isDefined = true;
                });
            }
        }
        function signInCallback(eventArgs) {
            alert('Signed in.');
        }
        function signOutCallback() {
            alert('Signed out.');
        }

    </script>
</head>
<body>
    <wl:app 
    channel-url="/channel.htm" 
    callback-url="/OAuthWrapCallback.ashx?wl_session_id=<%= Session.SessionID %>"
    client-id="<Your-Client-ID>" 
    scope="WL_Profiles.View" 
    onload="{{appLoaded}}">
    </wl:app>
    <input type="button" id="ToggleSignInButton" value="Show SignIn" onclick="addSignInControl()" />
    <div id="SignInControlDiv" />
</body>
</html>

After you decide how you want to display the Sign In control, the next step is to determine where you want it to appear. We recommend that you follow these guidelines to help create a positive user experience:

  • Place the Sign In control in the same location as any other sign-in or registration buttons that you may have on your site.
  • If the user is not signed in already, you should give them the option to perform an action (such as posting a comment on a blog). Then, give them the option to register on your site by using their Windows Live ID.
  • Consider how using Messenger Connect might affect your current “forgotten password” or “forgotten account” user-interface flows.
  • Determine what changes you must make to your existing database or caching structure—for example, adding an index on the user’s CID to quickly retrieve account information.

For additional information about the Sign In control and the signIn method, see the Windows Live Messenger Connect, Version 4.1 developer documentation.

Profile Access and Relationships

After your application receives a user’s consent to access data, you can begin to personalize the application for that user. A common way to do this is by automatically filling out forms with the user's Windows Live data, which is available to your application based on its scope. This practice reduces the amount of redundant information that the user must provide and streamlines his or her experience with your application.

How you access a profile depends on the scopes that you have requested for your application. For example, if you want users to interact with their friends and contacts, your application probably uses the Messenger.Signin scope. This scope allows you to use the JavaScript Profile control, which displays the following information about a user:

  • Display picture
  • Display name
  • Personal message

To add this control to your site, insert the following tag into your HTML.

<wl:profile cid=”$user”></wl:profile>

The user’s information appears on your site. To see this feature in action, see the Windows Live Interactive SDK.

Notice that the value of the cid attribute is $user. This value is a special identifier that instructs the Profile control to display information about the currently authenticated in user. To display information about one of the user's contacts, you specify a CID value instead of the $user variable, as shown in the following example.

<wl:profile cid=”-0123456789”></wl:profile>

You can customize the appearance of the Profile control by using one or more of the following attributes.

Attribute Type Required Default value Description

cid

String

Yes

None

Specifies the CID of the contact whose profile is to be displayed. If you set cid to $user, the user's own profile is displayed.

editable

Boolean

No

true

Indicates whether the profile is editable. This attribute applies only if the cid attribute is set to $user; otherwise, it is ignored.

display-picture-size

String

No

large

Specifies the size of the display picture. Valid values are small, medium, or large.

linked

Boolean

No

true

Indicates whether the display name is to be a hyperlink to the user's profile page.

If your application does not use the WL_Profiles.View scope, you can display profile information by using the UserInfo control.

<wl:userinfo></wl:userinfo>

The UserInfo control has the following two attributes.

Attribute Type Required Default value Description

initialized

String

No

None

Specifies the event-handler function to be run after the control is initialized.

cid

String

Yes

None

Specifies the CID of the contact whose profile is to be displayed. If you set cid to $user, the user's own profile is displayed.

You can customize the UserInfo control adding a <span> tag as a child element to the <wl:userinfo> element. The <span> tag has two attributes: an id attribute with a value of "userInfoTemplate", and a class attribute with a value of "sys-template". The markup inside the <span> element can include Microsoft Ajax binding converter syntax to bind properties of Document Object Model (DOM) elements to properties in a ProfileCollection object. The following example demonstrates customization that:

  • Prevents the user’s profile image from appearing.
  • Displays a text frame that contains the user's first name.
  • Adds another text frame to show the user's location.
<wl:UserInfo>
<span id='userInfoTemplate' class='sys-template'>
    <div class='LiveConnectProfileTextFrame'>
        <div class='LiveConnectProfileName' 
            sys:innertext=""{binding aboutYouProfile.firstName,convert={{new Function('a'\, 'return a?a:String.Empty;')}} }"">
        </div>
        <div class='LiveConnectProfileStatus' 
            sys:innertext=""{binding statusProfile.statusText,convert={{new Function('a'\, 'return a?a:String.Empty;')}} }"">
        </div>
        <div class='LiveConnectUserInfoTextFrame'>
            Your location is: 
            <span id='UserInfoLocation' class='LiveConnectUserInfoName'
            sys:innertext='{binding aboutYouProfile.location}'>
        </div>
    </div>
</span>
</wl:UserInfo>

You can also access profile information by using either the Messenger Connect JavaScript library or its REST endpoints. For more information, see JavaScript Library Reference for Windows Live Messenger Connect, Version 4.1 and REST API Service and Resource Model (Messenger Connect).

Helping users to communicate is critical to the development of a personalized and compelling web application. From chatting in real time with other site visitors to sending instant messages to their contacts, users want to be able to interact with their friends as easily online as they do in person.

Windows Live Messenger Connect, Version 4.1 provides a number of features that enable you to add these real-time shared experiences to your web application. With Messenger Connect you can:

  • Add a Chat control. This control is easy to add and lets users on the same page communicate with each other. They can filter the messages they see to show all messages or only the messages of their friends.
  • Enable instant messaging with Windows Live Messenger. You can add instant messaging features to your site by using a UI control or by creating customized JavaScript code.

Chat Control

One way to create real-time experiences on your site is by using the Messenger Connect Chat control. This control can be placed anywhere on your site. When users visit your site, they can use the Chat control by clicking the sign-in button at the top of the control. After they sign in with their Windows Live ID and are authenticated, they can chat with anyone else who has also signed in to the control. As the owner of the application, you can moderate the discussion in the Chat control.

Using the Chat control requires some of the same setup tasks that were discussed in the "Getting Started" section earlier in this guide. Specifically, you must register your application, add the Windows Live Messenger Connect, Version 4.1 namespace to your HTML, and put a link to the JavaScript loader class on your page. To add the Chat control, add the following HTML to your site.

<wl:chat-frame
   event-name = "Example Event Name"
   client-id="<Your Client ID>"
</wl:chat-frame>

You can customize the Chat control by using the following attributes.

Attribute Type Required Default value Description

client-id

String

Yes

None

Specifies the client ID of the domain that is hosting the attribute.

event-description

String

No

None

Specifies the description of the webpage that receives the chat event.

The event description is used when a user invites a contact to the chat room.

event-name

String

No

The URL of the current page.

Gets or sets the event name. If no event name is specified, this attribute uses the URL of the current page. You can use the event-name attribute to create several chat windows on the same page, or to share a single chat room between two different pages.

The maximum length of the event-name string is 512 characters.

event-embed-height

Integer

No

0

Specifies the height of the embedded video. A value of 0 specifies the height of the existing chat window.

event-embed-source

String

No

video

Gets or sets the URL of the web resource that is used for embedding video on another webpage.

This value is used when a user chooses to share the chat event with contacts. If the user shares the chat event, a link to the video and a thumbnail image are included in the user's Windows Live feed.

The following example demonstrates how to embed the source address for a video from the YouTube video community.

event-embed-source="http://www.youtube.com/v/11OOz1I-gCk&hl=en_US&fs=1"

event-embed-type

Enumeration

No

None

Specifies the type of additional content—for example, video that is Adobe Flash Player compatible—that is embedded in the chat window.

The following example demonstrates how to specify that the embedded content is compatible with Adobe Flash Player.

event-embed-type="application/x-shockwave-flash

event-embed-width

Integer

No

0

Specifies the width of the embedded video. A value of 0 specifies the width of the existing chat window.

event-thumbnail-url

String

No

None

The URL of a thumbnail image for the preview. This value is used to display an invitation message when a contact is invited to chat.

event-title

String

No

The HTML title of the current page.

The title of the webpage that contains the chat event.

The event-title is used when a user shares Chat control metadata with friends, but does not specify any message.

Although the default value of this attribute is the title of the webpage that contains the chat control, you can override that value.

event-url

String

No

The URL of the current page.

The URL of the parent page that is hosting the Chat control.

The URL is used to share the location of the chat control with a user's friends, or to invite a contact to chat. If the event-embedding attributes (event-embed-height, event-embed source, and others) are used, this URL should specify the location of the page that contains the embedded video.

height

Integer

No

450

Gets or sets the height, in pixels, of the chat control. The minimum height of the Chat control is 250. If a number smaller than 250 is specified, 250 is used instead.

theme

String

No

light

Specifies the theme of the Chat control. Set the theme value to "dark" for the dark theme, or to "light" for the lighter theme. If no value is provided, the default is "light".

width

Integer

No

300

Gets or sets the width, in pixels, of the Chat control. The minimum width of the Chat control is 250. If a number smaller than 250 is specified, 250 is used instead.

Instant Messaging

Instant messaging (IM) remains one of the primary means by which users share information with each other online. You can implement IM in your web application by using the Messenger Web Bar control, or by writing custom JavaScript code by using the Messenger Connect JavaScript library.

Gg251990.note(en-us,MSDN.10).gifNote:
Examples in this section assume that you have followed the steps described in the "Getting Started" section earlier in this guide.

Messenger Web Bar Control

One of the most feature-rich controls available with Messenger Connect is also one of the easiest to implement on your site: the Messenger Web Bar control. This control appears at the bottom of your webpage and enables users to sign in, view their contacts, and have conversations with their friends.

You can add the Messenger Web Bar control by adding the following HTML to your page.

<wl:bar></wl:bar>

To see the Messenger Web Bar control in action, go to the Windows Live Interactive SDK. No matter where you put this HTML in your page code, the control always appears at the bottom of the user’s browser window.

You can customize this control by using the following attributes.

Attribute Type Required Default value Description

on-consent-completed

Function callback

No

None

Specifies the event handler that is triggered by the on-consent-completed event. When the user grants consent to the application, the application receives an access token that it can store and use to sign the user in to the Windows Live Messenger service. The token value is stored in the event arguments for the consentCompleted event.

sign-in-enabled

Boolean

No

true

Indicates whether a sign-in control should be part of the Messenger Web Bar.

hide-first-run-experience

Boolean

No

false

Specifies whether to display the first-run experience, which walks the user through using Windows Live Messenger on the web.

Managing Conversations by Using the JavaScript Library

The Messenger Connect JavaScript library includes all the functionality you need to create your own custom chat interface. In general, creating such an interface requires that you:

  1. Determine which of the user's contacts are online.
  2. Send messages to the contact that the user selects.
  3. Receive messages from the contact.

To get a list of a user’s online Messenger contacts, you use the getOnlineContacts method of the IMessengerContext interface. The following example shows a function that uses this method. The example's addOption function populates a drop-down list box, with an id of Online_Name_list, on the webpage with a list of online contacts.

function getOnlineContacts() {
    var messengerContext = Microsoft.Live.App.get_messengerContext();
    var onlineContacts = messengerContext.getOnlineContacts();
    for (i = 0; i < onlineContacts.get_count(); i++) {
        var contact = onlineContacts.get_item(i);
        addOption($get('Online_Name_list'),
        contact.get_displayName(),
        contact.get_cid());
    }
}

function addOption(selectbox, text, value) {
    var optn = document.createElement("OPTION");
    optn.text = text;
    optn.value = value;
    selectbox.options.add(optn);
}

To start a conversation, you create an instance of the Conversation class. In the following example, we get the CID of the contact that a user has selected from a list of online contacts. The CID is the primary identifier of any contact within Windows Live. When we have the Conversation object, we update an HTML element named contactLabel with a message that lets the user know with whom he or she is chatting.

function startConversation() {
    // Get the User object.
    var messengerContext = Microsoft.Live.App.get_messengerContext();
    var user = messengerContext.get_user();
    var contactId = document.getElementById("Online_Name_list").value;
    var contact = messengerContext.findContact(contactId);            
    // Create a new conversation with the selected contact.
    var conv = user.get_conversations().create(contact.get_currentAddress());
    // Subscribe to Microsoft.Live.Messenger.MessageReceivedEventHandler.
    conv.add_messageReceived(recvMsg);
    // Update the page with the name of the user with whom the chat is 
    //occurring.
    document.getElementById('contactLabel').innerText = 'Now chatting with: ' + contact.get_displayName();
}

The next step is to add functionality that enables the user to send messages. The following example creates a function called sendMsg, which works with two HTML elements: a <textarea> element with an id attribute of "txtMessage", and an <input> button tag with an id attribute of "Send" that calls the function when clicked. Also, this function calls an additional function named displayMsg, which displays the sent message on the webpage. (The displayMsg function, and the HTML elements just mentioned, are described later in this section.)

function startConversation() {
    // Get the User object.
    var messengerContext = Microsoft.Live.App.get_messengerContext();
    var user = messengerContext.get_user();
    var contactId = document.getElementById("Online_Name_list").value;
    var contact = messengerContext.findContact(contactId);
    // Create a new conversation with the selected contact.
    var conv = user.get_conversations().create(contact.get_currentAddress());
    // Subscribe to Microsoft.Live.Messenger.MessageReceivedEventHandler.
    conv.add_messageReceived(recvMsg);
    // Update the page with the name of the user with whom the chat is 
    //occurring.
    document.getElementById('contactLabel').innerText = 'Now chatting with: ' + contact.get_displayName();
}

To receive messages, you must create an event handler that listens for incoming text. The following example shows this handler, which uses the same displayMsg function described earlier to display the message on the webpage.

function recvMsg(sender, e) {
    switch (e.get_message().get_type()) {
        case Microsoft.Live.Messenger.MessageType.textMessage:
            var message = e.get_message();
            displayMsg(message);
            break;
        default:
            break;
    }
}

The following code contains the displayMsg function, which displays both sent and received text messages on the webpage. This function displays the message in a <textarea> element with an id attribute of "txtConv".

function displayMsg(message) {
    var elMsg = message.createTextElement();
    var txtConv = document.getElementById("txtConv");
    var sender = message.get_sender();
    var dispName = sender.get_presence().get_displayName() || sender.get_address();
    txtConv.appendChild(document.createTextNode(dispName + " says: "));
    txtConv.appendChild(elMsg);
    txtConv.appendChild(document.createElement("br"));
}

The HTML that is needed to work with these functions is as follows.

<table>
    <tr>
        <td id="contactLabel">
        </td>
    </tr>
    <tr>
        <td>
            <textarea rows="20" cols="40" id="txtConv"></textarea>
        </td>
    </tr>
    <tr>
        <td>
            <textarea rows="5" cols="40" id="txtMessage"></textarea>
        </td>
        <td>
            <input type="button" id="Send" value="Send Message" onclick="sendMsg()" />
        </td>
    </tr>
</table>

To create a fully-functional chat client requires a little more work than can be covered in this guide. For example, you should add functionality that detects when the status of a user’s contact changes. You should also add error-handling in case a message is undeliverable or a user selects a contact that has gone offline. You can learn more about how to accomplish these tasks in the Messenger Connect documentation.

A key element to adding a social experience to a web application is to help users share what they are doing online with their friends and contacts. You can add this functionality to your site by using the Messenger Connect sharing badge. This badge consists of a few lines of HTML code and enables your users to share with their friends what they have found on your site.

Users can share two types of content:

  • Articles, which include a page summary that contains the URL, thumbnail, page title, and description.
  • Videos, which include inline playback of the shared video inside the page summary.

You can add the sharing badge to your site by adding a customized URL to the Windows Live sharing badge template. Unlike other features of Messenger Connect, you do not have to register your application with Windows Live to use the sharing badge.

The following HTML code is an example of the badge template.

<a href="http://profile.live.com/badge?url={your URL}" title="Share with Messenger">
     <img style="border-style:none; vertical-align:middle; margin-right:4px"
     src="http://img.wlxrs.com/$Live.SN.MessengerBadge/icon16wh.png" 
     alt="Share with Messenger"/>
Messenger</a>

The preceding template creates a white sharing badge. You can create an orange sharing badge instead by replacing the src attribute with the following URL.

http://img.wlxrs.com/$Live.SN.MessengerBadge/icon16or.png

Notice the {your URL} placeholder in the anchor tag's href attribute. This URL is the location of the article or video that your users can share. The following is a sample URL for an article:

http://profile.live.com/badge/?url= http%3A %2Fwww.contoso.com%2Farticle.htm&title=Article%20title&description=Article%20description&screenshot=http:%2F%2Fwww.contoso.com%2Fimg%2Fimage1.jpg

The following table lists the attributes to add for the purpose of sharing an article.

Attribute Type Required Description

url

String; maximum of 512 characters

Yes

The URL of the article that is being shared.

screenshot

String; maximum of 512 characters

No

The URL of the image to be used as the thumbnail in the activity stream.

title

String; maximum of 512 characters

Yes

The title of the webpage.

description

String; maximum of 512 characters

No

The description of the webpage.

msg

String; maximum of 512 characters

No

The default message that is included when the user shares the content. Users can edit this message before sharing.

The following example shares a video.

http://profile.live.com/badge/?url= http%3A %2F%2Fwww.contoso.com%2Fvideo.htm&title=Video%20title&description=Video%20description&screenshot=http:%2F%2Fwww.contoso.com%2Fimg%2Fimage1.jpg&swfurl=http:%2F%2Fwww.contoso.com%2Fvideo.flv&height=340&width=500&ctype=flash

For videos, the following parameters are available.

Attribute Type Required Description

url

String; maximum of 512 characters

Yes

The URL that is being shared.

screenshot

String; maximum of 512 characters

No

The URL of the image to be used as the thumbnail in the activity stream.

title

String; maximum of 512 characters

Yes

The title of the webpage.

description

String; maximum of 512 characters

No

The description of the webpage.

msg

String; maximum of 512 characters

No

The default message to be included when the user shares the content. Users can edit this message before sharing.

swfurl

String; maximum of 512 characters

Yes

The URL of the video source.

height

Integer between 1 and 9999

No

The height of the video.

width

Integer between 1 and 9999

No

The width of the video.

ctype

Enumeration

No

The type of video to be embedded. Currently the only valid value for this attribute is "flash".

emy

String; maximum of 512 characters

No

Additional variables for the embedded object. For content that is compatible with Adobe Flash Player, these variables are used for the flashvars variable.

This developer guide provides you with the tools you need to start your development projects with Messenger Connect. To learn more about Messenger Connect features, check out the following resources:

Show:
© 2014 Microsoft