Windows Live Web Toolbar Mashup – MessyTwit

A lot of people nowadays have Twitter accounts, a Facebook account etc. and if you’re reading this then I’m also assuming you have a Windows Live account and some interest in Windows Live Services. Each of these have their own “Personal Message” where you can tell people what you are currently doing and there-in lies the problem. You have to visit each of these places to update them individually. Why not have a central place where you can update them all?

The good news is that you can. There are various ways of doing this, whether through a website or a Silverlight application. Basically anything that can use web services. With Microsoft’s recent introduction of the Windows Live Web Toolbar, I thought I’d do just that and show you how easy it is.  I will be building upon my previous articles regarding the new Windows Live controls so please go check them out if you haven’t already as I’ve discussed a lot of the code present in this mashup in previous articles.

So first up, lets take a look at our actual web page :-

messytwitblank_thumb_75bf9d00 Developer

Here you can see that I’ve sectioned off the page. At the top of the page we will display the users Windows Live login picture along with their personal message that is tied to that account. Just below that will be the list of their contacts. This is an easy way to display the personal messages of their Windows Live contacts. The next section will be their Twitter account showing their own personal messages that they have sent to Twitter and at the bottom you will see the Windows Live Web Toolbar that we will use to sign people into their Windows Live accounts and hook in with the other Windows Live Web Controls that we display on the page.

<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>
 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:msgr="http://messenger.live.com/2009/ui-tags">
<head runat="server">
    <title>MessyTwit</title>
    <link type="text/css" rel="Stylesheet" href="MessyTwit.css" />
    <script type="text/javascript" src="http://www.wlmessenger.net/api/3.0/loader.js"></script>
    <script type="text/javascript" src="JScript/JQuery.js"></script>
    <script type="text/javascript" src="JScript/Messenger.js"></script>
    <script type="text/javascript" src="JScript/Twit.js"></script>
    <script type="text/javascript">
        Microsoft.Live.Core.Loader.load(['Messenger.UI', 'Messenger.UI.Styles.Core'], null);
    </script>
</head>
<body>
    <msgr:app 
            privacy-url="Privacy.html" 
            channel-url="Channel.htm" 
            application-verifier-token="<%= appVerifier %>" 
            token-url="RefreshMessengerToken.aspx"
            onauthenticated="onAuthenticated"></msgr:app> 
    <form id="form1" runat="server">
    <div id="msgrDisplayPic">
    </div>
    <hr />
    <div>
            <msgr:contact-list word-wheel-enabled="false"></msgr:contact-list>
        </div>
        <hr />
<%--    <div id="ctrls">
            <msgr:personal-message cid='$user' id='persmsg' editable='true'></msgr:personal-message>
    </div> 
--%>    
        <div id="msgs">
            <div id="TwitCreds" class="msgHidden">
                <span>Twitter Username&nbsp;&nbsp;</span>
                <input type="text" id="acct" /><br />
                <span>Twitter Password&nbsp;&nbsp;</span>
                <input type="password" id="pwd" /><br />
                <span id="TwitLogin">Login to Twitter</span>
            </div>
    </div>
    <hr />
        <div id="persMsg" class="msgHidden">
            <input type="text" id="msg" value="Enter a personal message" size="80" />
            <span id="msgsend">Send</span>
        </div>
    <div>
            <msgr:bar sign-in-enabled="true"></msgr:bar>
    </div> 
</form>
</body>
</html>

 

 

Above is the default.aspx page. As you can see, it’s not very complicated at all. Most of this was covered in my previous articles so I’ll just give a quick rundown here.

At the top we include various Javascript files which we’ll cover later and we tell the page to load the messenger controls when the xhtml page has loaded.

Next we have the messenger application section in which we supply various required variables such as where our privacy and channel pages are and we also set an event for when the user has authenticated (logged in to) their Windows Live Account.

After that there is a placeholder for where we will put the users display picture and Windows Live personal message. Following the horizontal rule (I’ve only put that in the display physically break the page into sections) we have the Windows Live Contact List control. It’s as simple as that one line of markup to display a very nice list of the users contacts.

The next section on the page is where we will gather the users’ Twitter credentials so that we can interact with their Twitter account.  Towards the bottom we have a simple input box that the user will type their personal message in to and finally we display the Windows Live Web Toolbar at the bottom of the page.

For completeness here is the code behind for the default.aspx page :-

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using WindowsLive;
using System.Diagnostics;
 
public partial class _Default : System.Web.UI.Page 
{
    WindowsLiveLogin wll = new WindowsLiveLogin(true);
    public string appVerifier
    {
        get
        {
            return wll.GetAppVerifier();
        }
    }
}

 

I’ve covered this before so won’t go into it here.

The corresponding style sheet associated with this page is very basic. Here is MessyTwit.css :-

input#msg
{
    border-width: 0px;
}
 
.msgHidden
{
    display: none;
}
 
.msgShow
{
    display: block;
}

 

 

We hide the border around the personal message input box and we define two classes to hide or show various elements of our page.

There are two main Javascript files that cover all of the functionality on the page. The Messenger.js file I’ve basically covered before :-

var userToken = null;
var msgrUser = null;
function onAuthenticated(e)
{
    msgrUser = e.get_user();
    msgrUser.add_signInCompleted(SignInCompleted);
}
function onUserConsentCompleted(e)
{
    userToken = e.get_consentToken();
}
function SignInCompleted(sender, e)
{
    if (e.get_resultCode() === Microsoft.Live.Messenger.SignInResultCode.success)
    {
        if (typeof (InvokeOnUserSignIn) === 'function')
        {
            InvokeOnUserSignIn();
        }
    }
    else
    {
        OnUserSignedOut();
    }
    var userAddress = msgrUser.get_address().get_address();
    var usercid = msgrUser.get_identity().get_cid();
    var signinframe = document.getElementById("msgrDisplayPic");
    var tag = Microsoft.Live.Messenger.UI.Tags.TagsFactory.createTag('display-picture', 
    { 'cid': usercid, 'presence-enabled': 'true', 'size': 'Large', 'logo-enabled': 'true' });
    $("#msgrDisplayPic").append(tag);
    var tag2 = Microsoft.Live.Messenger.UI.Tags.TagsFactory.createTag('personal-message', { 'cid': '$user', 'editable': 'false', 'id':'Persmsg2'});
    $("#msgrDisplayPic").append(tag2);
    $("div#TwitCreds").removeClass("msgHidden");
    $("div#TwitCreds").addClass("msgShow");
}
function OnUserSignedOut()
{
    //add code for sign-out.
}

 

 

As a quick overview we have the onAuthenticated event handler that we tied up in the messenger application block on the default.aspx page. As mentioned this gets fired when the user logs in to their Windows Live account. Once they login we capture that event and extract the user object then setup another event to capture when sign-in has been completed. The API fires off multiple events at differing stages of login. Another one of those events is when the user gives consent to send information back to our web site. In this event handler we simply capture the consent token that is sent.

Once the user has completed sign-in we make sure that sign-in was successful (i.e. the correct username and password were supplied). Next we create the users display picture and also their personal message. These are two different Windows Live controls.

The documentation for the Personal Message control says that it must have the CID of the user in order to display their personal message. This makes sense. However if you pass in the CID as we do for the display picture, the Personal Message control does not work. You HAVE to pass the $user string that is a reserved variable created by the Windows Live API.

Next we simply use some jQuery to insert these controls onto our page. We also now use some jQuery to show the Twitter credentials portion of our web page which is hidden until after the user signs in to their Windows Live account.

messytwitafterlogin_thumb_1eca3bfd Developer

After the user has signed into their Windows Live account, this is what you will see. On this screenshot, my personal message is not displayed as I don’t have a personal message currently tied to this account however the control is present as you’ll see later.

The second of the two main Javascript files, twit.js, contains the jQuery functions for manipulating the page. This is all new so I’ll break it down a bit :-

$(document).ready
(
    function()
    {
        $('span#msgsend').click
    (
        function()
        {
            var acct = $("input#acct").val();
            var pwd = $("input#pwd").val();
            var msg = $("input#msg").val();

 

Everything in this Javascript file is done using event handlers. We attach the event handlers to the default.aspx document on ready. This is slightly different than onLoad. With onLoad you need to wait until the page has fully loaded, including the images that are displayed on the page. With jQuery’s ready handler the page has basically loaded, we have access to the page DOM, script etc. but we don’t have to wait until all the images are loaded.

So in the ready section we attach an event handler to the “send” text next to the personal message input. I just used text here but it could just have easily been a button.
When the text gets clicked we first get the username and password for the users Twitter account and we also get the personal message they want to send.
 
$.post("/MessyTwit/TwitterService.asmx/SendTweet",
{ 'account': acct, 'pass': pwd, 'msg': msg },

 

Next we have an AJAX call to a web service that we have created to send the personal to the users Twitter account.

 

function(_xml)
{
    $('div#msgs').text('');
    $xml = $(_xml);
    $xml.find("status").each
(
    function()
    {
        $('div#msgs').append("<div><img src='" + $(this).find("profile_image_url").text() + "'/>" +
        "<span>&nbsp;&nbsp;" + $(this).find('text').text() + "</span></div>");
    }
);
}
        , 'xml');

 

 

To finish off this AJAX call we define an anonymous function that gets called once the call returns to our script. Here we first blank out any Twitter messages that may already be displayed on the screen. Then we take the XML that is returned by the AJAX call and parse it. We loop through the XML parsing each individual message. For each message we take the display picture of the user and also the text of the message and display it in the placeholder we marked out in our default.aspx page.  The final part to this is just saying that the AJAX call will use XML rather than JSON or some other format.

        if (msgrUser)
        {
            msgrUser.get_presence().set_personalMessage(msg);
        }
 

So we have posted the users personal message to their Twitter account, next we need to do the same for their Windows Live account. In the code above, this is exactly what we do. We first check to see that the user object isn’t null and if it’s not then we simply call the set_personalMessage method to update their Windows Live personal message.

        $('input#msg').val('');
 
    }
);

 

Finally for this event handler we do some cleanup. Here I’m blanking out the personal message input box ready for their next message.

 

$('input#msg').focus
(
    function()
    {
        $(this).val('');
    }
);
 
$('input#msg').blur
(
    function()
    {
        if (this.value == '')
        {
            this.value = 'Enter your personal Message';
        }
    }
);
 

Here is the personal message input box before the user has clicked on it :-

messytwitinput1_thumb_3a0294fe Developer

and after they have clicked on it :-

messytwitinput2_thumb_435e5a32 Developer

The next two event handlers we define are tied to the personal message input box. All that this does is blank the input box when the user focuses on it (clicks or tabs into it). If the user clicks or tabs away from it and the input box is blank then we insert the message “Enter your personal Message” into it so the user knows where to type.

        $('span#TwitLogin').click
        (
            function()
            {
                $('div#persMsg').removeClass('msgHidden');
                $('div#persMsg').addClass('msgShow');
                $('div#TwitCreds').removeClass('msgShow');
                $('div#TwitCreds').addClass('msgHidden');
                var acct = $("input#acct").val();
                $.post("/MessyTwit/TwitterService.asmx/GetTweet",
            { 'account': acct },
    function(_xml)
    {
        $xml = $(_xml);
        $xml.find("status").each
    (
        function()
        {
            $('div#msgs').append("<div><img src='" + $(this).find("profile_image_url").text() + "'/>" +
            "<span>&nbsp;&nbsp;" + $(this).find('text').text() + "</span></div>");
        }
    );
    }
            , 'xml');
            }
        );
 
    }
);

 

 

The final event handler is tied to the text I’ve displayed on the page for logging in to their Twitter account. Again, I’ve just used some text but it could just as well be a button control.

When the user clicks on the login text we hide the twitter login credentials area and display the personal message input box. Next we get the users username and again make an AJAX call. This time only to retrieve the users’ own Twitter messages. Finally we use the same anonymous function as we had above to parse through the returned XML and extract the display picture and message from each message returned and display them onscreen. As soon as the user enters their Twitter credentials you should see the following :-

messytwittwitsignin_thumb_17ad9036 Developer

Now you can take this code and expand on it so that when the user clicks on the login text you actually do a check against their Twitter credentials and display an error message if they are not correct. Twitter has lots of web service calls that you can use to make this code more robust. See the Twitter API for more details.

This really only leaves one piece left, our web service :-

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Xml;
using System.Xml.Linq;
using System.IO;
using System.Net;
 
/// <summary>
/// Summary description for TwitterService
/// </summary>
[WebService(Namespace = "blah")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
[System.Web.Script.Services.ScriptService]
public class TwitterService : System.Web.Services.WebService {
 
    public TwitterService () {
 
        //Uncomment the following line if using designed components 
        //InitializeComponent(); 
    }
 
    [WebMethod]
    public XmlDocument GetTweet(string account) 
        {
            string url = "http://www.twitter.com/statuses/user_timeline/" + account + ".xml?count=5";
            HttpWebRequest Request = (HttpWebRequest)WebRequest.Create(url);
            Request.Method = "GET";
            WebResponse Response = Request.GetResponse();
            StreamReader Reader = new StreamReader(Response.GetResponseStream());
            string Result = Reader.ReadToEnd();
            Reader.Close();
            XmlDocument doc = new XmlDocument();
            doc.LoadXml(Result);
            return doc;
    }
 
        [WebMethod]
        public XmlDocument SendTweet(string account, string pass, string msg)
        {
            string url = "http://www.twitter.com/statuses/update.json";
            NetworkCredential creds = new NetworkCredential(account, pass);
            string EncodedText = "status=" + HttpUtility.UrlEncode(msg);
            HttpWebRequest Request = (HttpWebRequest)WebRequest.Create(url);
            Request.Method = "POST";
            Request.Credentials = creds;
            Request.ContentType = "application/x-www-form-urlencoded";
            Request.ContentLength = EncodedText.Length;
            Request.UserAgent = "MessyTwit";
            Request.Timeout = 10000;
 
            System.Net.ServicePointManager.Expect100Continue = false;
 
            Stream reqStream = Request.GetRequestStream();
            StreamWriter Writer = new StreamWriter(reqStream);
            Writer.Write(EncodedText);
            Writer.Close();
 
            WebResponse Response = Request.GetResponse();
            StreamReader Reader = new StreamReader(Response.GetResponseStream());
            string Results = Reader.ReadToEnd();
 
            Reader.Close();
            Response.Close();
            reqStream.Close();
            XmlDocument doc = GetTweet(account);
            return doc;
        }
}
 

 

This is a standard .Net web service except that we need to un-comment the line that reads :-

[System.Web.Script.Services.ScriptService]

 

 

This is so that our Javascript can actually make calls to it. The first method that we have simply calls the Twitter web service and gets the top 5 messages the user has posted and returns that as XML back to our AJAX call.

The second method is the one that actually posts the message to Twitter. After we have posted our message to using the Twitter API we make the call to the first method to retrieve the new updated top 5 messages. The main line to take note of in this method is :-

System.Net.ServicePointManager.Expect100Continue = false;

 

 

Without this line any posts to Twitter will fail with a 417 return code. This only applies to posts, not to gets.

And there you have it. One web page that updates both a users’ Windows Live personal message and also their Twitter account as can be seen in the screenshot below. The Windows Live Personal-Message control now contains my latest message at the top of the page and also my latest Twitter entry has the same message :-

messytwitfinal_thumb_72afcfbc Developer

This should give you an idea of the kind of mashups that you can do using the new Windows Live Messenger UI controls. I’ve expanded this example to include Facebook although I didn’t put the code here but it’s fairly easy to do and the above code will give you all the basics you need. You can expand it to include any other site that does some kind of personal message you wish.

One final point should be noted. The Windows Live Web Toolbar includes it’s own area in which a user can type their personal message. When the personal message gets posted you can capture the event using the following :-

// attach event for future changes
user.get_presence().add_propertyChanged(function (sender, e) {
  if (e.get_propertyName() == “PersonalMessage”)  {
    var msg = user.get_presence().get_personalMessage();
  }
});

This also applies to the Personal Message UI control if you allow it to be edited. This way you can handle whether the user types their personal message into the Web Toolbar or using a control that you’ve specifically placed on the page.