Building a Windows Phone 7 Twitter Application using Silverlight

On Monday I had the opportunity to present the MIX 2010 Day 1 Keynote in Las Vegas (you can watch a video of it here).  In the keynote I announced the release of the Silverlight 4 Release Candidate (we’ll ship the final release of it next month) and the VS 2010 RC tools for Silverlight 4.  I also had the chance to talk for the first time about how Silverlight and XNA can now be used to build Windows Phone 7 applications.

During my talk I did two quick Windows Phone 7 coding demos using Silverlight – a quick “Hello World” application and a “Twitter” data-snacking application.  Both applications were easy to build and only took a few minutes to create on stage.  Below are the steps you can follow yourself to build them on your own machines as well.

[Note: In addition to blogging, I am also now using Twitter for quick updates and to share links. Follow me at: twitter.com/scottgu]

Building a “Hello World” Windows Phone 7 Application

First make sure you’ve installed the Windows Phone Developer Tools CTP – this includes the Visual Studio 2010 Express for Windows Phone development tool (which will be free forever and is the only thing you need to develop and build Windows Phone 7 applications) as well as an add-on to the VS 2010 RC that enables phone development within the full VS 2010 as well.

After you’ve downloaded and installed the Windows Phone Developer Tools CTP, launch the Visual Studio 2010 Express for Windows Phone that it installs or launch the VS 2010 RC (if you have it already installed), and then choose “File”->”New Project.”  Here, you’ll find the usual list of project template types along with a new category: “Silverlight for Windows Phone”. The first CTP offers two application project templates. The first is the “Windows Phone Application” template - this is what we’ll use for this example. The second is the “Windows Phone List Application” template - which provides the basic layout for a master‑details phone application:

image

After creating a new project, you’ll get a view of the design surface and markup. Notice that the design surface shows the phone UI, letting you easily see how your application will look while you develop. For those familiar with Visual Studio, you’ll also find the familiar ToolBox, Solution Explorer and Properties pane.

image

For our HelloWorld application, we’ll start out by adding a TextBox and a Button from the Toolbox. Notice that you get the same design experience as you do for Silverlight on the web or desktop. You can easily resize, position and align your controls on the design surface. Changing properties is easy with the Properties pane. We’ll change the name of the TextBox that we added to username and change the page title text to “Hello world.”

image

We’ll then write some code by double‑clicking on the button and create an event handler in the code-behind file (MainPage.xaml.cs).

image

We’ll start out by changing the title text of the application. The project template included this title as a TextBlock with the name textBlockListTitle (note that the current name incorrectly includes the word “list”; that will be fixed for the final release.)  As we write code against it we get intellisense showing the members available.  Below we’ll set the Text property of the title TextBlock to “Hello “ + the Text property of the TextBox username:

image

We now have all the code necessary for a Hello World application.  We have two choices when it comes to deploying and running the application. We can either deploy to an actual device itself or use the built‑in phone emulator:

image

Because the phone emulator is actually the phone operating system running in a virtual machine, we’ll get the same experience developing in the emulator as on the device. For this sample, we’ll just press F5 to start the application with debugging using the emulator.  Once the phone operating system loads, the emulator will run the new “Hello world” application exactly as it would on the device:

image

Notice that we can change several settings of the emulator experience with the emulator toolbar – which is a floating toolbar on the top right.  This includes the ability to re-size/zoom the emulator and two rotate buttons.  Zoom lets us zoom into even the smallest detail of the application:

image

The orientation buttons allow us easily see what the application looks like in landscape mode (orientation change support is just built into the default template):

image

Note that the emulator can be reused across F5 debug sessions - that means that we don’t have to start the emulator for every deployment. We’ve added a dialog that will help you from accidentally shutting down the emulator if you want to reuse it.  Launching an application on an already running emulator should only take ~3 seconds to deploy and run.

Within our Hello World application we’ll click the “username” textbox to give it focus.  This will cause the software input panel (SIP) to open up automatically.  We can either type a message or – since we are using the emulator – just type in text.  Note that the emulator works with Windows 7 multi-touch so, if you have a touchscreen, you can see how interaction will feel on a device just by pressing the screen.

image

We’ll enter “MIX 10” in the textbox and then click the button – this will cause the title to update to be “Hello MIX 10”:

image

We provide the same Visual Studio experience when developing for the phone as other .NET applications. This means that we can set a breakpoint within the button event handler, press the button again and have it break within the debugger:

image

Building a “Twitter” Windows Phone 7 Application using Silverlight

Rather than just stop with “Hello World” let’s keep going and evolve it to be a basic Twitter client application.

We’ll return to the design surface and add a ListBox, using the snaplines within the designer to fit it to the device screen and make the best use of phone screen real estate.  We’ll also rename the Button “Lookup”:

image

We’ll then return to the Button event handler in Main.xaml.cs, and remove the original “Hello World” line of code and take advantage of the WebClient networking class to asynchronously download a Twitter feed. This takes three lines of code in total: (1) declaring and creating the WebClient, (2) attaching an event handler and then (3) calling the asynchronous DownloadStringAsync method.

In the DownloadStringAsync call, we’ll pass a Twitter Uri plus a query string which pulls the text from the “username” TextBox. This feed will pull down the respective user’s most frequent posts in an XML format. When the call completes, the DownloadStringCompleted event is fired and our generated event handler twitter_DownloadStringCompleted will be called:

image

The result returned from the Twitter call will come back in an XML based format.  To parse this we’ll use LINQ to XML. LINQ to XML lets us create simple queries for accessing data in an xml feed. To use this library, we’ll first need to add a reference to the assembly (right click on the References folder in the solution explorer and choose “Add Reference):

image

We’ll then add a “using System.Xml.Linq” namespace reference at the top of the code-behind file at the top of Main.xaml.cs file:

image

We’ll then add a simple helper class called TwitterItem to our project. TwitterItem has three string members – UserName, Message and ImageSource:

image

We’ll then implement the twitter_DownloadStringCompleted event handler and use LINQ to XML to parse the returned XML string from Twitter.  What the query is doing is pulling out the three key pieces of information for each Twitter post from the username we passed as the query string. These are the ImageSource for their profile image, the Message of their tweet and their UserName. For each Tweet in the XML, we are creating a new TwitterItem in the IEnumerable<XElement> returned by the Linq query. 

We then assign the generated TwitterItem sequence to the ListBox’s ItemsSource property:

image

We’ll then do one more step to complete the application. In the Main.xaml file, we’ll add an ItemTemplate to the ListBox. For the demo, I used a simple template that uses databinding to show the user’s profile image, their tweet and their username.

<ListBox Height="521" HorizonalAlignment="Left" Margin="0,131,0,0" Name="listBox1" VerticalAlignment="Top" Width="476">
    <ListBox.ItemTemplate>
        <DataTemplate>
           <StackPanel Orientation="Horizontal" Height="132">
              <Image Source="{Binding ImageSource}" Height="73" Width="73" VerticalAlignment="Top" Margin="0,10,8,0"/>
              <StackPanel Width="370">
                 <TextBlock Text="{Binding UserName}" Foreground="#FFC8AB14" FontSize="28" />
                 <TextBlock Text="{Binding Message}" TextWrapping="Wrap" FontSize="24" />
              </StackPanel>
           </StackPanel>
        </DataTemplate>
     </ListBox.ItemTemplate>
</ListBox>

Now, pressing F5 again, we are able to reuse the emulator and re-run the application. Once the application has launched, we can type in a Twitter username and press the  Button to see the results. Try my Twitter user name (scottgu) and you’ll get back a result of TwitterItems in the Listbox:

image

Try using the mouse (or if you have a touchscreen device your finger) to scroll the items in the Listbox – you should find that they move very fast within the emulator.  This is because the emulator is hardware accelerated – and so gives you the same fast performance that you get on the actual phone hardware.

Summary

Silverlight and the VS 2010 Tools for Windows Phone (and the corresponding Expression Blend Tools for Windows Phone) make building Windows Phone applications both really easy and fun. 

At MIX this week a number of great partners (including Netflix, FourSquare, Seesmic, Shazaam, Major League Soccer, Graphic.ly, Associated Press, Jackson Fish and more) showed off some killer application prototypes they’ve built over the last few weeks.  You can watch my full day 1 keynote to see them in action. I think they start to show some of the promise and potential of using Silverlight with Windows Phone 7.  I’ll be doing more blog posts in the weeks and months ahead that cover that more.

Hope this helps,

Scott

48 Comments

  • i love how similar this is to timheuers silverlight basics. its great that i can easily port my knowldege to the phone! now all my silverlight dream apps can be realized on the phone! yey! can't wait for the phone to come out!

  • That's VERY nice!

  • This sample is very useful.
    Always great thank you for your help.

  • It'd be nice to get a clear view of what the differences are between Silverlight 3 and Silverlight for WinMo. What happens if you take a very complex pre-existing Silverlight program and try to get it going on the emulator?

  • Thank you for this great article! Can't wait for the Windows Phone 7's release! I'm currently using HTC HD2 with Windows Mobile 6.5!

  • It certainly looks like a hell of a lot easier to write apps for the new Windowss phone than the iPhone. All Microsoft have to do is have an equally easy app store submission / download mechanism and I can see them being a real contender.

    Exciting.

    -- Lee

  • Awesome stuff... great to see the development for phones becomes as easy, productive and fun as the development for PC's :)
    Just a question I have about Windows Phone Developer Tools download. I already have VS 2010 RC installed, why does the setup download VS 2010 Express for me? It's a 200+ MB download that isn't required I guess; shouldn't be downloading only the development tools for VS 2010 RC?
    Thanks

  • can we use SyndicationService in dotnet mobile or facebook api also

  • Man, that's so easy!!!
    And powerfull!!!!!!!!!!!!!
    I want a phone with WP7 right now :D

  • Hi Scott, great job at MIX. Thanks!

  • Thanks guys this sample was very useful for us.

  • Brilliant and simple to follow. Like @Carsten I also had to change URI.

    Cheers

  • You say the emulator is hardware accelerated so you get the same performance that you get on the actual phone hardware. What about limiting the emulator's speed so those who run the emulator on a fast computer don't see speeds that are so much faster then practical on an actual device?

  • Thanks for the basic and clear introduction!
    Can't wait to get my hands dirty!

  • I love the fact that a similar application in MonoTouch for the iPhone looks almost identical.

    http://github.com/chrisntr/MonoTouch-Twitter-Example/blob/master/TwitterExample/TweetListViewController.xib.cs

    Keep it up.

  • Great! Was a great mini tutorial!


  • [ArgumentException: Culture name 'en-in' is not supported.
    Parameter name: name]
    System.Globalization.CultureTableRecord..ctor(String cultureName, Boolean useUserOverride) +7483593
    System.Globalization.CultureTableRecord.GetCultureTableRecord(String name, Boolean useUserOverride) +213
    System.Globalization.CultureInfo..ctor(String name, Boolean useUserOverride) +45
    System.Web.HttpServerUtility.CreateReadOnlyCultureInfo(String name) +200
    System.Web.UI.Page.set_UICulture(String value) +188
    OJAP.jobapply.InitializeCulture() +349
    ASP.jobapply_aspx.__BuildControlTree(jobapply_aspx __ctrl) +56
    ASP.jobapply_aspx.FrameworkInitialize() +46
    System.Web.UI.Page.ProcessRequest(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +56
    System.Web.UI.Page.ProcessRequest() +80
    System.Web.UI.Page.ProcessRequestWithNoAssert(HttpContext context) +21
    System.Web.UI.Page.ProcessRequest(HttpContext context) +49
    ASP.jobapply_aspx.ProcessRequest(HttpContext context) +4
    System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +181
    System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +75

  • Hi Scott,

    I tried to implement your example, but the DownloadStringCompleted event is never raised. Any idea why?

    Michael

  • I want to echo what others have said about how easy these tools are. It only took me 3 minutes to make my first "Hello World" after opening up the Phone Tools in Visual Studio the first time.

    I was able to fully read and understand your post in less than 1 minute.

    Not only are these tools productive, they are fun to use :)

    So my only concern now is being able to deploy phone apps without having to go through the marketplace. It would be cool if I could pay $100 a phone to allow it to receive apps that use .xap's that are signed by me. This way I could pay $1000 to allow say 10 salespeople to use phone apps that a company wanted to deploy privately.

  • Hi Scott,
    What are your plans for enterprise customers? How can developers deploy apps to Windows Phone 7 without having to go through the market place? It would be shame if this is not sorted out as soon as possible... such a great device with great potential - but right now I don't see how it can work for business users. Any thoughts?

  • is it still not possible to use anonymous types for databinding in Silverlight 4? it's a bit easier than always creating helper classes like TwitterItem.

  • Hi Scott,

    The really really neat thing about Microsoft .NET Development Platform is:
    The Consistent development experience across different runtimes

    Really Coooooool, Really Awesome

    Great JOB Scott, Keep going Forward

  • So when the official release is made for Windows Phone 7 is it going to support Silverlight 4? I have apps for Windows Mobile which looks like we cannot offer a version for Windows Phone 7 in the current state as we hook to the email and process rules over the email received and then alert the user the way they chose. This new move to make the Zune a phone, from what it looks like in the CTP I have downloaded and started playing with, seems like it is lacking local apps to run but expects things to all live in the cloud. Even if we should rely on data in the cloud, there are needs to store data locally and from what I can tell that is not even supported for SQL CE (or whatever the name is these days), or SQLite (I would love to see native adaptors for this as it is cross platform capable). Thanks for all your examples and helping the dev community.

  • Wow, I want to ditch my Android phone and get a Win7 phone now! Seriously!

  • I want to ditch my iPhone and get a Windows 7 phone!
    I'm so excited about the fact that it's so easy to get up and running with W7 phone apps.
    You have to jump through so many hoops to get going with iPhone development. The last fiery hoop is to work on a Mac which is something that I couldn't do.

    What is the release date for the first W7 phones?

  • If only SL mobile apps could operate on both iPhone and Windows Phone 7.

  • Hi, very useful tutorial, I'm looking forward to have WP7 in my hand :D

    I have question :
    How I can add an items with the same item template you made but the data retrieved from a List !!?

    Thanks

  • Hi Scott,

    Thanks for sharing the latest tutorial on WP7. Will very helpful to me.

    Thanks

  • I'm excited to jump from MonoTouch .Net on the iPhone to Silverlight (4?) on Windows Phone 7. The development tools are key and Microsoft has it 100% down.

  • I am waiting to get started, but it does not work on windows xp! Why not ? VS2010 RC is working on it.

  • Since Silverlight is supposed to be a multi platform environment.. are we going to be seeing Silverlight on other phone OS's

  • It was very helpful . Thank you so much :)

  • Scott,

    The artcile is great! One question on the listbox. When we reach scrolling to end or begening of the list does it behave like an IPhone user list (smooth scoll and spring action like when you reach end of the list). Will this be added as a default behaiour to listbox?

  • Great stuff Scott. I have started writing my first Windows Phone 7 application and it is a very easy process. I have a question. Is there a way to either launch the emulator on another computer when you debug or are there steps to manually install the application in the emulator? I use my desktop for development but I wanted to test the phone application on the multitouch Acer netbook we got at the PDC.

  • Hi Scott,
    This is a nice tutorial. I love the fact that you can use the same knowledge and there's not another layer of complexity to learn this. I can see myself creating Windows Phone 7 applications very easy. Thanks again for the tutorial!

  • Can you use Windows XP Pro platform to develop Windows 7 Phone applications?
    Will all the tools run under Windows XP Pro?

    Thanks

  • Can someone post the whole app in for download please. Every time I try to write the code I get an error. Thanks in advance.

  • Great stuff. I am working on my first Windows mobile application and it leverages all of my existing .NET skills. One question, is it possible to debug or deploy the application using the emulator on another computer? I want to test the touchscreen functionality on the Acer Aspire we got from the PDC while I develop on my desktop.

  • Can some please put the complete app up for download. It would make it easier for me to understand how this app works. Please post a link here. thanks

  • Help me lot to start the my first application in Silverlight.

    Many Thanks!!

  • This is actually quite exciting stuff. I can't wait to see how this pans out. I am currently using Android, but something that is easy for developers to use is very important to me!

  • This is actually quite exciting stuff. I can't wait to see how this pans out. I am currently using Android, but something that is easy for developers to use is very important to me!

  • This is actually quite exciting stuff. I can't wait to see how this pans out. I am currently using Android, but something that is easy for developers to use is very important to me!

  • As in my installation experience, this will cause the software input panel to open up automatically. We can either type a message or since we are using the emulator just type in text. Note that the emulator works with Windows 7 multi touch so, if you have a touchscreen, you can see how interaction will feel on a device just by pressing the screen.

  • I like the tutorial. I’m sorry I found it after I created my own site with Twitter.

  • can i use php do this work?

  • As in my installation experience, this will cause the software input panel to open up automatically.

  • Awesome tutorial !

    By the way, is there a way to create Windows Phone 7 applications on Win XP SP3? I tried to install the development tools, but Win Vista or Win 7 is required, so I wonder do I need to upgrade my OS?

    Thanks in advance for the response!

Comments have been disabled for this content.