×
Namespaces

Variants
Actions
(Difference between revisions)

Accessing Twitter using Windows Phone

From Nokia Developer Wiki
Jump to: navigation, search
somnathbanik (Talk | contribs)
(Somnathbanik -)
joaocardoso (Talk | contribs)
m (Joaocardoso - - Implementation)
(7 intermediate revisions by 2 users not shown)
Line 1: Line 1:
[[Category:Code Examples]][[Category:Windows Phone]]
+
[[Category:Code Examples]][[Category:Windows Phone]][[Category:Silverlight]][[Category:Web Services]][[Category:XML]]
{{Abstract|This article demonstrates how to handle web service  request using [http://msdn.microsoft.com/en-us/library/system.net.webclient.aspx WebClient] and  [http://msdn.microsoft.com/en-us/library/system.net.networkinformation.networkinterface.aspx NetworkInterface].}}
+
{{Abstract|This article demonstrates how to check a network interface using [http://msdn.microsoft.com/en-us/library/system.net.networkinformation.networkinterface.aspx NetworkInterface], request data from a web service (twitter) using [http://msdn.microsoft.com/en-us/library/system.net.webclient.aspx WebClient] and then parse the XML data returned for display.}}
+
  
{{ArticleMetaData
+
{{ArticleMetaData <!-- v1.2 -->
|sourcecode= [[Media: TwitterWebService.zip]]<!-- Link to example source code e.g. [[Media:The Code Example ZIP.zip]] -->
+
|sourcecode= [[Media:TwitterWebService.zip]]  
 
|installfile= <!-- Link to installation file (e.g. [[Media:The Installation File.sis]]) -->
 
|installfile= <!-- Link to installation file (e.g. [[Media:The Installation File.sis]]) -->
 
|devices= WP7 Emulator  <!-- Devices tested against - e.g. ''devices=N95, N8'') -->
 
|devices= WP7 Emulator  <!-- Devices tested against - e.g. ''devices=N95, N8'') -->
Line 10: Line 9:
 
|platform= WP7.1 <!-- Compatible platforms - e.g. Symbian^1 and later, Qt 4.6 and later -->
 
|platform= WP7.1 <!-- Compatible platforms - e.g. Symbian^1 and later, Qt 4.6 and later -->
 
|devicecompatability= <!-- Compatible devices e.g.: All* (must have internal GPS) -->
 
|devicecompatability= <!-- Compatible devices e.g.: All* (must have internal GPS) -->
|signing=<!-- Signing requirements - empty or one of: Self-Signed, DevCert, Manufacturer -->
+
|dependencies= <!-- Any other/external dependencies e.g.: Google Maps Api v1.0 -->
|capabilities=<!-- Capabilities required by the article/code example (e.g. Location, NetworkServices. -->
+
|signing= <!-- Signing requirements - empty or one of: Self-Signed, DevCert, Manufacturer -->
|keywords= Web Service/WebClient/NetworkInterface/Twitter<!-- APIs, classes and methods (e.g. QSystemScreenSaver, QList, CBase -->
+
|capabilities= <!-- Capabilities required by the article/code example (e.g. Location, NetworkServices. -->
|id= <!-- Article Id (Knowledge base articles only) -->
+
|keywords= Web Service/WebClient/NetworkInterface/Twitter<!-- APIs, classes and methods (e.g. QSystemScreenSaver, QList, CBase -->
|creationdate= 10th October,2011<!-- Format YYYYMMDD -->
+
|language= <!-- Language category code for non-English topics - e.g. Lang-Chinese -->
|author= [[User:somnathbanik]] <!-- Display as link [[User:username]] -->
+
|translated-by= <!-- [[User:XXXX]] -->
 +
|translated-from-title= <!-- Title only -->
 +
|translated-from-id= <!-- Id of translated revision -->
 +
|review-by= <!-- After re-review: [[User:username]] -->
 +
|review-timestamp= <!-- After re-review: YYYYMMDD -->
 +
|update-by= <!-- After significant update: [[User:username]]-->
 +
|update-timestamp= <!-- After significant update: YYYYMMDD -->
 +
|creationdate= 20111010
 +
|author= [[User:Somnathbanik]]
 
}}
 
}}
 
==Introduction==
 
==Introduction==
[http://msdn.microsoft.com/en-us/library/system.net.webclient.aspx WebClient] class provides common methods for sending and receiving data from a resource identified by a URI where as [http://msdn.microsoft.com/en-us/library/system.net.networkinformation.networkinterface.aspx NetworkInterface] class provides a information about the network. Here  we will use both the classes to see how we can get data from web service and use those data in our application.  
+
[http://msdn.microsoft.com/en-us/library/system.net.webclient.aspx WebClient] class provides common methods for sending and receiving data from a resource identified by a URI where as [http://msdn.microsoft.com/en-us/library/system.net.networkinformation.networkinterface.aspx NetworkInterface] class provides a information about the network. In this example we use both the classes, getting data from web service and using it in the application.  
+
+
+
 
   
 
   
 +
The code example is a basic Twitter Client that can display information about a particular user. In this case we add a {{Icode|SearchBox}} where user can put the ''UserName'' and as the user clicks on the ''SearchButton'', we make a web request  ''(<nowiki>http:</nowiki>//api.twitter.com/1/statuses/user_timeline.xml?screen_name=<username>)'' to fetch the XML data about the user. More information about Twitter’s API can be found  [http://dev.twitter.com/ here].
 +
 
[[File: TwitterWebService.png|thumb|301px|none| Twitter User Data]]  
 
[[File: TwitterWebService.png|thumb|301px|none| Twitter User Data]]  
+
 
==Basic Idea==
+
We  aim to create a basic Twitter Client that can display information about  a particular user. In this case we add a ''SearchBox'' where user can  put the ''UserName'' and as he clicks on the ''SearchButton'', we make a  web request  ''(http://api.twitter.com/1/statuses/user_timeline.xml?screen_name=<username>)''
+
to  fetch the XML data about the user. We use  [http://msdn.microsoft.com/en-us/library/system.net.webclient.aspx  WebClient] to make a web request and get the data but before that  [http://msdn.microsoft.com/en-us/library/system.net.networkinformation.networkinterface.aspx  NetworkInterface] is used to check whether the network is available  or  not. More information about Twitter’s API can be found  [https://dev.twitter.com/ here].
+
+
+
+
 
==Implementation==
 
==Implementation==
 
   
 
   
First lets create a project with '''Windows Phone Application''' Template.  Once the project is being created we add a ''TextBox'', ''Button'',  ''Image'', two ''TextBlock'' and a ''ListBox'' which has the text message in the '''MainPage.xaml''' file.
+
First create a project with '''Windows Phone Application''' Template.  Once the project is being created we add a ''TextBox'', ''Button'',  ''Image'', two ''TextBlock'' and a ''ListBox'' which has the text message in the '''MainPage.xaml''' file.
<code cpp>
+
 
 +
<code xml>
 
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
 
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
 
             <Grid.ColumnDefinitions>
 
             <Grid.ColumnDefinitions>
Line 66: Line 67:
 
         </Grid>
 
         </Grid>
 
          
 
          
     </Grid>
+
     </Grid>  
+
 
</code>
 
</code>
 +
 
We create a class name '''TwitterData.cs''' which holds the text message of the status.  
 
We create a class name '''TwitterData.cs''' which holds the text message of the status.  
<code cpp>
+
<code csharp>
 
public class TwitterData
 
public class TwitterData
 
     {
 
     {
 
         public string textMessage { get; set; }
 
         public string textMessage { get; set; }
 
     }
 
     }
 
 
</code>
 
</code>
 
   
 
   
When we click on the ''SearchButton''  {{Icode|NetworkInterface::GetIsNetworkAvailable()}} method is called to see whether any network connection is available or not. If we have a network connection then we create a new  [http://msdn.microsoft.com/en-us/library/system.net.webclient.aspx WebClient] object, and make an asynchronous call with  {{Icode|DownloadStringAsync()}}  out to the Twitter API  ''(http://api.twitter.com/1/statuses/user_timeline.xml?screen_name=<username>)''.  First, we create a new event handler  {{Icode|DownloadStringCompleted()}} for when our data retrieval is complete, and second we make the asynchronous call.  In this example,  we will get the user name that user has entered in the serarch box.  When the data returns, our event handler fires  {{Icode|twitter_DownloadStringCompleted()}}
+
When we click on the ''SearchButton''  {{Icode|NetworkInterface::GetIsNetworkAvailable()}} method is called to see whether any network connection is available or not. If we have a network connection then we create a new  [http://msdn.microsoft.com/en-us/library/system.net.webclient.aspx WebClient] object, and make an asynchronous call with  {{Icode|DownloadStringAsync()}}  out to the Twitter API  ''(http://api.twitter.com/1/statuses/user_timeline.xml?screen_name=<username>)''.  First, we create a new event handler  {{Icode|DownloadStringCompleted()}} for when our data retrieval is complete, and second we make the asynchronous call.  In this example,  we will get the user name that user has entered in the serarch box.  When the data returns, our event handler fires  {{Icode|twitter_DownloadStringCompleted()}}
<code cpp>
+
<code csharp>
 
private void SearchButton_Click(object sender, RoutedEventArgs e)
 
private void SearchButton_Click(object sender, RoutedEventArgs e)
 
         {
 
         {
Line 87: Line 87:
 
   
 
   
 
                 twitter.DownloadStringCompleted += new DownloadStringCompletedEventHandler(twitter_DownloadStringCompleted);
 
                 twitter.DownloadStringCompleted += new DownloadStringCompletedEventHandler(twitter_DownloadStringCompleted);
                 twitter.DownloadStringAsync(new Uri("http://api.twitter.com/1/statuses/user_timeline.xml?screen_name=" +  UserSearchBox.Text));
+
                 twitter.DownloadStringAsync(new Uri("http://api.twitter.com/1/statuses/user_timeline.xml?screen_name=" +  UserSearchBox.Text));
 
             }
 
             }
 
         }
 
         }
 
 
 
</code>
 
</code>
 
   
 
   
Once we get the data from the web service we need to display the content in list view.  I am not going to focus on this part here, rather we will see how to parse the XML using LINQ . To do this, we need to add the   namespace, ''System.Xml.Linq''. First lets create a new [http://msdn.microsoft.com/en-us/library/system.xml.linq.xelement.aspx XElement] object that holds our XML data.   
+
Once we get the data from the web service we need to display the content in list view.  I am not going to focus on this part here, rather we will see how to parse the XML using LINQ . To do this, we need to add the namespace, ''System.Xml.Linq''. First lets create a new [http://msdn.microsoft.com/en-us/library/system.xml.linq.xelement.aspx XElement] object that holds our XML data.   
 
   
 
   
<code cpp>
+
<code csharp>
 
XElement xmlTweets = XElement.Parse(e.Result);
 
XElement xmlTweets = XElement.Parse(e.Result);
 
</code>
 
</code>
For displaying content in list view we can refer [[ListBox_in_WP7]].
+
For displaying content in list view we can refer [[ListBox in WP7]].
 +
 
 
When we get the data in {{Icode|xmlTweets}} we need to bind the data in the listbox  
 
When we get the data in {{Icode|xmlTweets}} we need to bind the data in the listbox  
<code cpp>
+
<code csharp>
 
+
+
 
TwitterItemList.ItemsSource = from tweet in xmlTweets.Descendants("status")
 
TwitterItemList.ItemsSource = from tweet in xmlTweets.Descendants("status")
 
                                       select new TwitterData
 
                                       select new TwitterData
Line 114: Line 111:
 
   
 
   
 
Just above the list we display the profile image, user name and location of the user
 
Just above the list we display the profile image, user name and location of the user
<code cpp>
+
<code csharp>
 
string image = xmlTweets.Element("status").Element("user").Element("profile_image_url").Value;
 
string image = xmlTweets.Element("status").Element("user").Element("profile_image_url").Value;
            ImageSource source = new BitmapImage(new Uri(image));
+
ImageSource source = new BitmapImage(new Uri(image));
            UserImage.Source = source;
+
UserImage.Source = source;
+
            string name = xmlTweets.Element("status").Element("user").Element("name").Value;
+
            UserName.Text = name;
+
+
            string location = xmlTweets.Element("status").Element("user").Element("location").Value;
+
            UserLocation.Text = location;
+
 
   
 
   
 +
string name = xmlTweets.Element("status").Element("user").Element("name").Value;
 +
UserName.Text = name;
 
   
 
   
 +
string location = xmlTweets.Element("status").Element("user").Element("location").Value;
 +
UserLocation.Text = location;
 
</code>
 
</code>
+
 
+
+
+
+
+
 
==Source Code==
 
==Source Code==
 
The full source code of the example is available here: [[File: TwitterWebService.zip]]
 
The full source code of the example is available here: [[File: TwitterWebService.zip]]

Revision as of 14:10, 8 November 2012

This article demonstrates how to check a network interface using NetworkInterface, request data from a web service (twitter) using WebClient and then parse the XML data returned for display.

WP Metro Icon Web.png
SignpostIcon XAML 40.png
WP Metro Icon WP8.png
SignpostIcon WP7 70px.png
Article Metadata
Code ExampleTested with
Devices(s): WP7 Emulator
CompatibilityArticle
Keywords: Web Service/WebClient/NetworkInterface/Twitter
Created: somnathbanik (10 Oct 2011)
Last edited: joaocardoso (08 Nov 2012)

Introduction

WebClient class provides common methods for sending and receiving data from a resource identified by a URI where as NetworkInterface class provides a information about the network. In this example we use both the classes, getting data from web service and using it in the application.

The code example is a basic Twitter Client that can display information about a particular user. In this case we add a SearchBox where user can put the UserName and as the user clicks on the SearchButton, we make a web request (http://api.twitter.com/1/statuses/user_timeline.xml?screen_name=<username>) to fetch the XML data about the user. More information about Twitter’s API can be found here.

Twitter User Data

Implementation

First create a project with Windows Phone Application Template. Once the project is being created we add a TextBox, Button, Image, two TextBlock and a ListBox which has the text message in the MainPage.xaml file.

<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="350" />
<ColumnDefinition Width="100" />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="100" />
<RowDefinition Height="100" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<TextBox x:Name="UserSearchBox" Margin="0,0,37,0" />
<Button x:Name="SearchButton" Content="Search" Click="SearchButton_Click" HorizontalAlignment="Right" Width="131" Grid.ColumnSpan="2" />
<StackPanel Orientation="Horizontal" Grid.Row="1" Grid.ColumnSpan="2">
<Image x:Name="UserImage" Width="100" Height="100" Margin="0,0,12,0" />
<StackPanel Width="370">
<TextBlock x:Name="UserName" Foreground="Orange" FontSize="50" />
<TextBlock x:Name="UserLocation" Foreground="Orange" FontSize="25" />
</StackPanel>
</StackPanel>
<ListBox x:Name="TwitterItemList" Grid.Row="2" Grid.ColumnSpan="2">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel>
<TextBlock Margin="0,0,40,0" Text="{Binding textMessage}" TextWrapping="Wrap" Width="450" />
<Rectangle Height="20" />
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>
 
</Grid>

We create a class name TwitterData.cs which holds the text message of the status.

public class TwitterData
{
public string textMessage { get; set; }
}

When we click on the SearchButton NetworkInterface::GetIsNetworkAvailable() method is called to see whether any network connection is available or not. If we have a network connection then we create a new WebClient object, and make an asynchronous call with DownloadStringAsync() out to the Twitter API (http://api.twitter.com/1/statuses/user_timeline.xml?screen_name=<username>). First, we create a new event handler DownloadStringCompleted() for when our data retrieval is complete, and second we make the asynchronous call. In this example, we will get the user name that user has entered in the serarch box. When the data returns, our event handler fires twitter_DownloadStringCompleted()

private void SearchButton_Click(object sender, RoutedEventArgs e)
{
if (NetworkInterface.GetIsNetworkAvailable())
{
WebClient twitter = new WebClient();
 
twitter.DownloadStringCompleted += new DownloadStringCompletedEventHandler(twitter_DownloadStringCompleted);
twitter.DownloadStringAsync(new Uri("http://api.twitter.com/1/statuses/user_timeline.xml?screen_name=" + UserSearchBox.Text));
}
}

Once we get the data from the web service we need to display the content in list view. I am not going to focus on this part here, rather we will see how to parse the XML using LINQ . To do this, we need to add the namespace, System.Xml.Linq. First lets create a new XElement object that holds our XML data.

XElement xmlTweets = XElement.Parse(e.Result);

For displaying content in list view we can refer ListBox in WP7.

When we get the data in xmlTweets we need to bind the data in the listbox

TwitterItemList.ItemsSource = from tweet in xmlTweets.Descendants("status")
select new TwitterData
{
textMessage = tweet.Element("text").Value
};


Just above the list we display the profile image, user name and location of the user

string image = xmlTweets.Element("status").Element("user").Element("profile_image_url").Value;
ImageSource source = new BitmapImage(new Uri(image));
UserImage.Source = source;
 
string name = xmlTweets.Element("status").Element("user").Element("name").Value;
UserName.Text = name;
 
string location = xmlTweets.Element("status").Element("user").Element("location").Value;
UserLocation.Text = location;

Source Code

The full source code of the example is available here: File:TwitterWebService.zip

163 page views in the last 30 days.

Was this page helpful?

Your feedback about this content is important. Let us know what you think.

 

Thank you!

We appreciate your feedback.

×