Export (0) Print
Expand All

Creating an Activity and Posting it to Your Activity Stream

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

This topic demonstrates how to allow authenticated users to post a message to their activity streams. The examples presented here enable users to post to their activity streams from any webpage that has been implemented with the Messenger Connect JavaScript library. The examples get a user's activity stream collection, create a new message, append the message to the collection, and save the collection.

In this topic you will create an activity by using one of the activity templates that derive from Microsoft.Live.Services.Activity. For more information about templates and their benefits, see Working with Activities (JavaScript Library).

The following examples demonstrate how to create the most common types of activities: comment, status, video, bookmark, article, and photo. In each example, the collection of activities is already saved in the variable myActivitiesCollection. A full working sample is shown later in this topic.

The correct scope must be used to enable the posting of activities. Declaratively in the Application control, use the WL_Activities.Update scope; programmatically, use the wl_Activities_Update field of the Scope class.

In each of the following examples, an HTML TEXTBOX element having the attribute "ID=txtActivity" provides customized text for each activity. Each example also assumes that a data context and an in-memory activities collection exist. (A full sample is shown later, in the Samples section.)

The first example adds a comment activity by using the CommentActivityObject and AddCommentActivity classes.

function addCommentActivity() {
    if (myActivitiesCollection) {
        var title = 'Comment activity ' + $get('txtActivity').value;
        var inReplyTo = 'http://www.contoso.com/inReplyTo/';
        var alternateLink = 'http://www.contoso.com/alternateLink';
        var commentActivityObject = new Microsoft.Live.Services.CommentActivityObject(inReplyTo, alternateLink, title);

        var newCommentActivity = new Microsoft.Live.Services.AddCommentActivity([commentActivityObject], 'http://www.contoso.com/appLink');

        if (newCommentActivity.validateParams([commentActivityObject], 'http://www.contoso.com/appLink')) {
            myActivitiesCollection.add(newCommentActivity);
            myActivitiesCollection.save(operationCompleted);
        }
    }
}

The next example adds a status activity by using the StatusActivityObject and Add classes.

function addStatusActivity() {
    if (myActivitiesCollection) {
        var statusActivityObject = new Microsoft.Live.Services.StatusActivityObject('Status activity text.');
        statusActivityObject.set_content($get('txtActivity').value + "  " + new Date());

        var addStatusActivity = new Microsoft.Live.Services.AddStatusActivity([statusActivityObject], 'http://www.contoso.com/appLink');

        if (addStatusActivity.validateParams([statusActivityObject], 'http://www.contoso.com/appLink')) {
            myActivitiesCollection.add(addStatusActivity);
            myActivitiesCollection.save(operationCompleted);
        }
    }
}

The next example adds a video activity by using the VideoActivityObject and AddVideoActivity classes.

function addVideoActivity() {
    if (myActivitiesCollection) {
        var timestamp = (new Date()).toTimeString();
        var previewLink = 'http://www.contoso.com/previewLink' + timestamp;
        var alternateLink = 'http://www.contoso.com/alternateLink';
        var title = "video title " + $get('txtActivity').value;
        var videoActivityObject = new Microsoft.Live.Services.VideoActivityObject(previewLink, alternateLink, title);
        videoActivityObject.set_description("video description");

        var addVideoActivity = new Microsoft.Live.Services.AddVideoActivity([videoActivityObject], 'http://www.contoso.com/appLink');

        if (addVideoActivity.validateParams([videoActivityObject], 'http://www.contoso.com/appLink')) {
            myActivitiesCollection.add(addVideoActivity);
            myActivitiesCollection.save(operationCompleted);
        }
    }
}

The next example adds a bookmark activity by using the Bookmark and Add classes.

function addBookmarkActivity() {
    if (myActivitiesCollection) {
        var targetLink = 'http://www.contoso.com/targetLink';
        var title = 'a bookmark ' + $get('txtActivity').value;
        var description = 'a favorite site';
        var bookmarkActivityObject = new Microsoft.Live.Services.BookmarkActivityObject(targetLink, title, description);
        var addBookmarkActivity = new Microsoft.Live.Services.AddBookmarkActivity([bookmarkActivityObject], 'http://www.contoso.com/appLink');
        if (addBookmarkActivity.validateParams([bookmarkActivityObject], 'http://www.contoso.com/appLink')) {
            myActivitiesCollection.add(addBookmarkActivity);
            myActivitiesCollection.save(operationCompleted);
        }
    }
}

The next example adds an article activity by using the ArticleActivityObject and AddArticleActivity classes.

function addArticleActivity() {
    if (myActivitiesCollection) {
        var title = 'Article activity ' + $get('txtActivity').value;
        var articleActivityObject = new Microsoft.Live.Services.ArticleActivityObject('http://www.contoso.com/permaLink', title);

        var addArticleActivity = new Microsoft.Live.Services.AddArticleActivity([articleActivityObject], 'http://www.contoso.com/appLink');

        if (addArticleActivity.validateParams([articleActivityObject], 'http://www.contoso.com/appLink')) {
            myActivitiesCollection.add(addArticleActivity);
            myActivitiesCollection.save(operationCompleted);
        }
    }
}

The next example adds a photo activity by using the PhotoActivityObject, PhotoAlbumActivityObject, and AddPhotoActivity classes.

function addPhotoActivity() {
    if (myActivitiesCollection) {

        var photoActivityObject1 = new Microsoft.Live.Services.PhotoActivityObject('http://www.contoso.com/enclosure1/', 'http://www.contoso.com/preview/photo1.jpg', 'Photo1 Title');
        photoActivityObject1.set_description('Photo Description 1' + new Date());

        var photoActivityObject2 = new Microsoft.Live.Services.PhotoActivityObject('http://www.contoso.com/enclosure2/', 'http://www.contoso.com/preview/photo2.jpg', 'Photo2 Title');
        photoActivityObject2.set_description('Photo Description 2 ' + new Date());

        var photoActivityTarget = new Microsoft.Live.Services.PhotoAlbumActivityObject($get('txtActivity').value, 'http://www.contoso.com/photoalbum/');

        var addPhotoActivity = new Microsoft.Live.Services.AddPhotoActivity([photoActivityObject1, photoActivityObject2], photoActivityTarget, 'http://www.contoso.com/appLink');

        if (addPhotoActivity.validateParams([photoActivityObject1, photoActivityObject2], photoActivityTarget, 'http://www.contoso.com/appLink')) {
            myActivitiesCollection.add(addPhotoActivity);
            myActivitiesCollection.save(operationCompleted);
        }
    }
}

For more information about the Activities resource, see Working with Activities (JavaScript Library). For an API usage overview, see Using the Data Context.

The following sample enables an authenticated user of a webpage to post an activity to an activity stream. The activities included in this example are blog, article, video, comment, status, and photo. To use other activities, follow a coding pattern similar to that demonstrated in the sample.

To construct the sample:

  1. Set up the test project as shown in Getting Started Sample for ASP.NET.).
  2. Create a new ASP.NET page in the project.
  3. Replace the HTML element with the sample code that follows this procedure.
  4. Ensure that the web.config file has the required keys in the WL:APP element.
<%@ Import Namespace="System.Web.Configuration" %>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:wl="http://apis.live.net/js/2010">
<head >
    <title>Posting Activity</title>
    <script type="text/javascript" src="http://js.live.net/4.1/loader.js"></script>    
    <script type="text/javascript">
        var dataContext;
        var myActivitiesCollection;

        function appLoaded(applicationLoadCompletedEventArgs) {
            if (Microsoft.Live.App.get_auth().get_state() === Microsoft.Live.AuthState.authenticated) {
                getActivities();
            }
        }

        function signOut() {
            $get('ActivitiesList').innerHTML = "";
        }

        function signIn(signInCompletedEventArgs) {
            if (signInCompletedEventArgs.get_resultCode() != Microsoft.Live.AsyncResultCode.success) {
                alert("sign-in failed: " + signInCompletedEventArgs.get_resultCode());
                return;
            }
            // Get LiveDataContext and load contacts.
            dataContext = signInCompletedEventArgs.get_dataContext();
            getActivities();
        }

        function getActivities() {
            options = { "$top": String.format("{0}", $get('selShow').value) };
            Microsoft.Live.App.get_dataContext().load(Microsoft.Live.DataType.myActivities, options, myActivitiesLoaded);
        }

        function addCommentActivity() {
            if (myActivitiesCollection) {
                var title = 'Comment activity ' + $get('txtActivity').value;
                var inReplyTo = 'http://www.contoso.com/inReplyTo/';
                var alternateLink = 'http://www.contoso.com/alternateLink';
                var commentActivityObject = new Microsoft.Live.Services.CommentActivityObject(inReplyTo, alternateLink, title);

                var newCommentActivity = new Microsoft.Live.Services.AddCommentActivity([commentActivityObject], 'http://www.contoso.com/appLink');

                if (newCommentActivity.validateParams([commentActivityObject], 'http://www.contoso.com/appLink')) {
                    myActivitiesCollection.add(newCommentActivity);
                    myActivitiesCollection.save(operationCompleted);
                }
            }
        }

        function addArticleActivity() {
            if (myActivitiesCollection) {
                var title = 'Article activity ' + $get('txtActivity').value;
                var articleActivityObject = new Microsoft.Live.Services.ArticleActivityObject('http://www.contoso.com/permaLink', title);

                var addArticleActivity = new Microsoft.Live.Services.AddArticleActivity([articleActivityObject], 'http://www.contoso.com/appLink');

                if (addArticleActivity.validateParams([articleActivityObject], 'http://www.contoso.com/appLink')) {
                    myActivitiesCollection.add(addArticleActivity);
                    myActivitiesCollection.save(operationCompleted);
                }
            }
        }

        function addPhotoActivity() {
            if (myActivitiesCollection) {

                var photoActivityObject1 = new Microsoft.Live.Services.PhotoActivityObject('http://www.contoso.com/enclosure1/', 'http://www.contoso.com/preview/photo1.jpg', 'Photo1 Title');
                photoActivityObject1.set_description('Photo Description 1' + new Date());

                var photoActivityObject2 = new Microsoft.Live.Services.PhotoActivityObject('http://www.contoso.com/enclosure2/', 'http://www.contoso.com/preview/photo2.jpg', 'Photo2 Title');
                photoActivityObject2.set_description('Photo Description 2 ' + new Date());

                var photoActivityTarget = new Microsoft.Live.Services.PhotoAlbumActivityObject($get('txtActivity').value, 'http://www.contoso.com/photoalbum/');

                var addPhotoActivity = new Microsoft.Live.Services.AddPhotoActivity([photoActivityObject1, photoActivityObject2], photoActivityTarget, 'http://www.contoso.com/appLink');

                if (addPhotoActivity.validateParams([photoActivityObject1, photoActivityObject2], photoActivityTarget, 'http://www.contoso.com/appLink')) {
                    myActivitiesCollection.add(addPhotoActivity);
                    myActivitiesCollection.save(operationCompleted);
                }
            }
        }

        function addStatusActivity() {
            if (myActivitiesCollection) {
                var statusActivityObject = new Microsoft.Live.Services.StatusActivityObject('Status activity text.');
                statusActivityObject.set_content($get('txtActivity').value + "  " + new Date());

                var addStatusActivity = new Microsoft.Live.Services.AddStatusActivity([statusActivityObject], 'http://www.contoso.com/appLink');

                if (addStatusActivity.validateParams([statusActivityObject], 'http://www.contoso.com/appLink')) {
                    myActivitiesCollection.add(addStatusActivity);
                    myActivitiesCollection.save(operationCompleted);
                }
            }
        }

        function addVideoActivity() {
            if (myActivitiesCollection) {
                var timestamp = (new Date()).toTimeString();
                var previewLink = 'http://www.contoso.com/previewLink' + timestamp;
                var alternateLink = 'http://www.contoso.com/alternateLink';
                var title = "video title " + $get('txtActivity').value;
                var videoActivityObject = new Microsoft.Live.Services.VideoActivityObject(previewLink, alternateLink, title);
                videoActivityObject.set_description("video description");

                var addVideoActivity = new Microsoft.Live.Services.AddVideoActivity([videoActivityObject], 'http://www.contoso.com/appLink');

                if (addVideoActivity.validateParams([videoActivityObject], 'http://www.contoso.com/appLink')) {
                    myActivitiesCollection.add(addVideoActivity);
                    myActivitiesCollection.save(operationCompleted);
                }
            }
        }

        function addBookmarkActivity() {
            if (myActivitiesCollection) {
                var targetLink = 'http://www.contoso.com/targetLink';
                var title = 'a bookmark ' + $get('txtActivity').value;
                var description = 'a favorite site';
                var bookmarkActivityObject = new Microsoft.Live.Services.BookmarkActivityObject(targetLink, title, description);
                var addBookmarkActivity = new Microsoft.Live.Services.AddBookmarkActivity([bookmarkActivityObject], 'http://www.contoso.com/appLink');
                if (addBookmarkActivity.validateParams([bookmarkActivityObject], 'http://www.contoso.com/appLink')) {
                    myActivitiesCollection.add(addBookmarkActivity);
                    myActivitiesCollection.save(operationCompleted);
                }
            }
        }


        function myActivitiesLoaded(dataLoadCompletedEventArgs) {
            if (dataLoadCompletedEventArgs.get_resultCode() !== Microsoft.Live.AsyncResultCode.success) {
                alert("Activities failed to load! Are you signed in?");
                return;
            }
            myActivitiesCollection = dataLoadCompletedEventArgs.get_data();
            createListOfActivities(myActivitiesCollection);

        }
        // List just "view" of activities
        function createListOfActivities(ActivitiesCollection) {
            var list = $get('ActivitiesList');
            list.innerHTML = '';
            for (var i = 0; i < ActivitiesCollection.get_length(); i++) {
                if (ActivitiesCollection.getItem(i) !== undefined) {
                    var activity = ActivitiesCollection.getItem(i);
                    list.innerHTML += "<li>";
                    list.innerHTML += activity.get_title();
                    list.innerHTML += "</li>";
                }
            }
        }

        // Callback method called by methods that operate on collections.
        function operationCompleted(dataSaveCompletedEventArgs) {
            for (var i = 0; i < dataSaveCompletedEventArgs.get_results().length; i++) {
                var dataSaveResult = dataSaveCompletedEventArgs.get_results()[i];
                if (dataSaveResult.get_resultCode() !== Microsoft.Live.AsyncResultCode.success) {
                    alert("Error saving data: " + dataSaveResult.get_error().message);
                    continue;
                }
                // Reload collection.
                getActivities();
                alert("You shared your activity successfully.");
            }
        }
    </script>
    <style type="text/css">
    ul { list-style-type: none;}
    </style>
</head>
<body>
    <div>
        <wl:app channel-url="<%=WebConfigurationManager.AppSettings["wl_wrap_channel_url"]%>"
            callback-url="<%=WebConfigurationManager.AppSettings["wl_wrap_client_callback"]%>?<%=SessionId%>"
            client-id="<%=WebConfigurationManager.AppSettings["wl_wrap_client_id"]%>" scope="WL_Activities.Update"
            onload="appLoaded">
        </wl:app>
        <wl:signin onsignin="{{signIn}}" onsignout="{{signOut}}"></wl:signin>
        <br />
        <hr /> 
        <wl:userinfo/>
        <br />
        Share What You Are Doing: <input type="text" id="txtActivity" size="120" /> <br />
        <input type="button" value="Add Comment Activity" onclick="addCommentActivity()"/>
        <input type="button" value="Add Photo Activity" onclick="addPhotoActivity()" /> 
        <input type="button" value="Add Status Activity" onclick="addStatusActivity()" /> 
        <input type="button" value="Add Video Activity" onclick="addVideoActivity()" />
        <input type="button" value="Add Article Activity" onclick="addArticleActivity()" />
        <input type="button" value="Add Bookmark Activity" onclick="addBookmarkActivity()" />
        <br />
        <h3>Your Recent Activities</h3>
        Show 
        <select id="selShow">
            <option value="1">1</option>
            <option value="5" selected="selected">5</option>
            <option value="10">10</option>
            <option value="20">20</option>
        </select>
        <input type="button" value="Refresh" onclick="getActivities()" />
        <ul id="ActivitiesList">
        </ul>
    </div>
</body>
</html>

Show:
© 2014 Microsoft