image image

Mobile application development is the future. The evolution in the user experience of mobile device started with iPhone that changed the way people use their phones (I believe). Catching up the wave, Microsoft unveiled their new Mobile OS called Windows Phone 7 with a very different, unique and easy UI (based on Metro UI) bringing new opportunities for developers.

I also got indulged in the Windows Phone 7 Developer tools CTP and it is really fun to program. In my experience, this is easier than any other mobile platform development I have ever come along with. Windows Phone List Application is one of the type of project templates you can use for creating your appliaction in the current version of Visual Studio 2010 express for Windows Phone for creating applications that use list and navigation controls. In this tutorial I am going to tell you how you can load twitter timeline in Windows Phone List application. This also clears the idea of calling a web service Asynchronously which is treated as a separated thread in Windows Phone 7 applications. Also clears basic concept of populating the list.

Tutorial:

Start Visual Studio 2010 Express for Windows Phone 7, go to File > New Project

In templates select Windows Phone List Application and name it as TwitterTimeline_ListApp (or any other name you like). Click OK

image

Just for the sake of looking good, change text property of textBlockPageTitle to “MY TWITTER APP” and textBlockListTitle to “Timeline”

image

(To add images in the List Application) In the solution explorer, open ItemViewModel.cs in the ViewModels folder. And in ItemViewModel class, add the following property

private string _image;        public string Image        {            get            {                return _image;            }            set            {                _image = value;                NotifyPropertyChanged("Image");            }        }

In MainPage.xaml go to the XAML code of ListBoxOne (In the design view select ListBoxOne and then switch to code view). And update the <mpc:ListViewItem/> to the following code. (Actually the new thing added is Imagesource=”{Binding Image}”)

<mpc:ListViewItem Layout="TextAndDetailsWithIcon" Text="{Binding LineOne}" ImageSource="{Binding Image}" Details="{Binding LineTwo}" Style="{StaticResource PhoneListBoxItemLayout}"/>

In the solution explorer, right click References and click Add Reference

image

In the .NET tab, select System.Xml.Linq and click OK

image

Now open MainPage.xaml.cs and include the following namespaces

using System.IO;using System.Xml.Linq;using System.Collections.ObjectModel;using System.Windows.Threading;

In MainPage.xaml.cs, add class level variables defined in the code below

namespace TwitterTimeline_ListApp{    public partial class MainPage : PhoneApplicationPage    {        object _selectedItem;

        public event EventHandler TwitterRequestCompleted; //Twitter Request Completed event        public string twitterXMLGlobal = "no value";        public bool tokenCompleted = false;        public ObservableCollection<ItemViewModel> items = new ObservableCollection<ItemViewModel>();        DispatcherTimer timer = new DispatcherTimer();

No add the following methods in MainPage class inside MainPage.xaml.cs

void MainPage_TwitterRequestCompleted(object sender, EventArgs e)        {            XDocument twitterXML = XDocument.Parse(twitterXMLGlobal);

            try            {                var resultTweets = from tweets in twitterXML.Descendants("status")

                                   select new                                   {

                                       tweetId = tweets.Element("id").Value,                                       text = tweets.Element("text").Value,                                       name = tweets.Element("user").Element("name").Value,                                       profile_image_url = tweets.Element("user").Element("profile_image_url").Value,                                       userId = tweets.Element("user").Element("id").Value

                                   };

                foreach (var tweet in resultTweets)                {                    items.Add(new ItemViewModel()                    {                        LineOne = tweet.name,                        LineTwo = tweet.text,                        Image = tweet.profile_image_url,                        LineThree = tweet.text

                    });                }

            }            catch (UnauthorizedAccessException)            {

            }        }

        public void GetTwitter()        {            HttpWebRequest req =                              (HttpWebRequest)HttpWebRequest.Create(@"http://twitter.com/statuses/friends_timeline.xml?count=20");

            NetworkCredential creds = new NetworkCredential("<Twitter Username>", "<Twitter Password>");

            req.Credentials = creds;            req.Method = "GET";

            IAsyncResult token = req.BeginGetResponse(new AsyncCallback(GetStatusesCallBack), req);

        }

        public void GetStatusesCallBack(IAsyncResult result)        {

            WebResponse response = ((HttpWebRequest)result.AsyncState).EndGetResponse(result);            StreamReader reader = new StreamReader(response.GetResponseStream());

            string responseString = reader.ReadToEnd();            reader.Close();

            twitterXMLGlobal = responseString;

            tokenCompleted = result.IsCompleted;

            TwitterRequestCompleted(this, EventArgs.Empty);

        }        public void timerTick()        {

                if (tokenCompleted)                {

                    ListBoxOne.ItemsSource = items;

                    timer.Stop();

                }

        }        void timer_TickEvent(object sender, EventArgs e)        {            timerTick();

        }

In the GetTwitter() mentioned in the code above, update NetworkCredentials with user’s twitter id and password and run the code. Done :D

Download the complete solution files (source code) [TwitterTimeline_ListApp.zip]