Twitter In Windows Store Application, How It All Works

Introduction

I have been on Twitter for a long time, tweeting all, about what I eat, about where I go, about my girlfriend, and so on. Can you still believe that such an intelligent personality (me) has only 37 followers (@Neelesh__)? Shocked!! But yes, this is the reality.

Never mind. Though having just a few followers, I am still very much dedicated to making various Twitter applications for Windows 8. In this article, we will see how to set up a Windows Store application to get the tweets of a specified person and much more.

For that, you need to have Twitter's authentication token. We will see how to get one in the next article. But for this article, we will be concentrating on simply having a project set up, in which we simply will just plug in the tokens.

TwitterTweets

The first step as always is to create a new Windows Store application project. Without thinking much, let's add a Twitter authentication WinJS helper, that you can download from http://www.4shared.com/document/Lpu3GhGb/winjs-oauth-for-twitter.html. Also, let's add a config.js file which in turn possesses the configuration key and access token.

Here is what my config.js file contains.

WinJS.Namespace.define("Twitter.OAuth.Config", {
    consumerKey: '<Your consumer Key>',
    consumerSecret: '<Your consumer secret>',
    userOAuthToken: '<Your OAuth Token>',
    userOAuthTokenSecret: '<Your OAuth Token Sceret>'
});

That is it. It completes our code for the config.js file. Next is the creation of the user interface. You can create the user interface by editing HTML. Here is what I have in my design on the default.html page.

<body>
    <p class="findbuddy fragment">
        <header aria-label="Header content" role="banner">
            <button class="win-backbutton" aria-label="Back" disabled type="button"></button>
            <h1 class="titlearea win-type-ellipsis">
                <span class="pagetitle">Welcome to Tweet Search</span>
            </h1>
        </header>
        <section aria-label="Main content" role="main">
            <p id="hashTagContainer">
                <span>Name your Tag:</span>
                <input type="text" id="hashTagName">
                <button type="reset" id="btnSearch">Search</button>
            </p>
            <p id="mediumListIconTextTemplate" data-win-control="WinJS.Binding.Template">
                <p id="tweetsTemplate">
                    <p style="background-color:#00639c;">
                        <img data-win-bind="src: image" id="profilePic"/>
                    </p>
                    <p id="tweetContent">
                        <!-- Displays the "title" field. -->
                        <h4 data-win-bind="innerText: name" style="background-color:#00639c;"></h4>
                        <h5 data-win-bind="innerText: handle" style="background-color:#00639c;"></h5>
                        <!-- Displays the "text" field. -->
                        <h6 data-win-bind="innerText: tweet" style="background-color:#00639c;"></h6>
                        <span data-win-bind="innerText: timeOfTweet" style="background-color:#00639c;"></span>
                    </p>
                </p>
            </p>
            <p id="basicListView" data-win-control="WinJS.UI.ListView" data-win-options="{ itemTemplate: select('#mediumListIconTextTemplate') }">
            </p>
        </section>
    </p>
</body>

The UI isn't good until we write some CSS for it. Here is what my CSS contains.

.TagResult p {
    margin-left: 120px;
}

body {
    height: 100%;
    background-color: #00639c;
}

#sectionMain {
    height: auto;
    background-color: #00639c;
}

#hashTagContainer {
    margin: 20px 0px 0px 54px;
}

#hashTagContainer input {
    margin-left: 10px;
}

#basicListView {
    margin-top: 60px;
    margin-left: 53px;
    min-height: 100%;
    height: 520px;
    background-color: #00639c;
}

#tweetsTemplate {
    width: 300px;
    height: 150px;
    background-color: #00639c;
}

#mediumListIconTextTemplate {
    background-color: #00639c;
}

#tweetContent:hover {
    background-color: lightGRAY;
}

#tweetsTemplate h6 {
    color: white;
    overflow: auto;
    max-height: 100px;
    min-height: 70px;
}

#tweetsTemplate h5 {
    color: darkgray;
}

#tweetsTemplate span {
    color: Yellow;
    overflow: auto;
    font-size: 10px;
}

#tweetsTemplate #tweetContent {
    margin-left: 20%;
    background-color: #00639c;
}

#profilePic {
    position: absolute;
}

#progressRing {
    position: absolute;
    color: white;
    margin: -300px 0px 0px 50%;
    display: none;
}

After doing the UI, we need to add code, code that interacts with Twitter's API to get the results we desire. Here's what my code of default.js has.

// For an introduction to the Blank template, see the following documentation:     
// http://go.microsoft.com/fwlink/?LinkId=232509     
(function() {     
    "use strict";     
     
    WinJS.Binding.optimizeBindingReferences = true;     
     
    // Various twitter's api we can use     
    var queryParams, url = 'https://api.twitter.com/1.1/users/show.json';     
    var getHomeTimelineUrl = "https://api.twitter.com/1.1/statuses/home_timeline.json";     
    var userTimeline = "https://api.twitter.com/1/statuses/user_timeline.json";     
    var getMentionsUrl = "https://api.twitter.com/1.1/statuses/mentions_timeline.json";     
    var getRetweetsOfMeUrl = "http://api.twitter.com/1.1/statuses/retweets_of_me.json";     
    var ret = "http://api.twitter.com/1/statuses/retweet/329472492626395130.json";     
    var app = WinJS.Application;     
    var activation = Windows.ApplicationModel.Activation;     
    app.onactivated = function(args) {     
        if (args.detail.kind === activation.ActivationKind.launch) {     
            if (args.detail.previousExecutionState !==     
                activation.ApplicationExecutionState.terminated) {     
                // Event handler for button     
                btnSearch.addEventListener('click', SearchClicked, false);     
            } else {     
                // TODO: This application has been reactivated from suspension.     
                // Restore application state here.     
            }     
            args.setPromise(WinJS.UI.processAll());     
        }     
    };     
    app.oncheckpoint = function(args) {};     
    app.start();     
     
    function personAndTweet() {     
        var name;     
        var image;     
        var tweet;     
        var timeOfTweet;     
        var handle;     
    }     
     
    function getSampleTwitterProfile(twitterOAuthInstance, personName) {     
        var pt = new Array();     
        queryParams = {     
            'screen_name': personName,     
            'count': '1000'     
        };     
        twitterOAuthInstance.sendAuthorizedRequestForUser(userTimeline, 'GET', queryParams)     
            .then(function(responseTweets) {     
                var resTweet = JSON.parse(responseTweets.results);     
                // pt[0].tweet = new Array();     
                for (var j = 0; j <= resTweet.length - 1; j++) {     
                    pt[j] = new personAndTweet();     
                    pt[j].handle = "@" + resTweet[j].user.screen_name;     
                    pt[j].name = resTweet[j].user.name;     
                    pt[j].image = resTweet[j].user.profile_image_url;     
                    pt[j].tweet = resTweet[j].text;     
                    pt[j].timeOfTweet = resTweet[j].created_at.split("+")[0];     
                }     
                var dataList = new WinJS.Binding.List(pt);     
                basicListView.winControl.itemDataSource = dataList.dataSource;     
            })     
            .done();     
    }     
     
    function setTweetAuthentication(personName) {     
        var twitterOAuthInstance;     
     
        // With all the neccesary credentials in place we can make signed requests to Twitter     
        // on the user's behalf     
        twitterOAuthInstance = new TwitterOAuth(Twitter.OAuth.Config.consumerKey,     
            Twitter.OAuth.Config.consumerSecret,     
            Twitter.OAuth.Config.userOAuthToken,     
            Twitter.OAuth.Config.userOAuthTokenSecret);     
        getSampleTwitterProfile(twitterOAuthInstance, personName);     
     
    }     
     
    function SearchClicked() {     
        setTweetAuthentication(hashTagName.value);     
    }     
     
})();    

The code above possesses data binding and template creation that we will look at in more detail when we study the MVVM pattern in JavaScript. Describing the code is the toughest job in the world right now. We will get over it in the subsequent posts on Windows Store applications.

This is what we need to do to create a simple Twitter application. Just some more steps to get the OAuth code and then our application will be fully functional. Do read the next article. Until then.

You can download the project from http://www.4shared.com/rar/_Guw8WNy/TwitterTweets.html.

Summary

In this article, we learned about Twitter In Windows Store Application, How It All Works.


Similar Articles