×
Namespaces

Variants
Actions
(Difference between revisions)

Twitter using TweetSharp Library on Windows Phone

From Nokia Developer Wiki
Jump to: navigation, search
rgunawans (Talk | contribs)
(Rgunawans -)
rgunawans (Talk | contribs)
(Rgunawans -)
Line 26: Line 26:
  
 
Here is the steps:
 
Here is the steps:
# Register your app with Twitter
+
* Register your app with Twitter
 
## go to http://dev.twitter.com/apps
 
## go to http://dev.twitter.com/apps
 
## Click on the Register a new app button
 
## Click on the Register a new app button
 
## Fill out the form
 
## Fill out the form
 
## You need the ApplicationType to be Client and Default Access Type: should be Read & Writer we do want to be able to Tweet afterall
 
## You need the ApplicationType to be Client and Default Access Type: should be Read & Writer we do want to be able to Tweet afterall
# Create New Project
+
* Create New Project
# From the '''Tools''' menu, select '''Library Package Manager''' and then click '''Package Manager Console'''
+
* From the '''Tools''' menu, select '''Library Package Manager''' and then click '''Package Manager Console'''
# type Install-Package TweetSharp, wait until finish install
+
* type Install-Package TweetSharp, wait until finish install
# Add new page TwitterAuthPage.xaml
+
* Add new page TwitterAuthPage.xaml
# Add Webbrowser control to the page
+
* Add Webbrowser control to the page
  
 
<code xml>
 
<code xml>
Line 56: Line 56:
 
</code>
 
</code>
  
# put the code below '''BrowserControl_Navigating''':
+
* put the code below '''BrowserControl_Navigating''':
  
 
<code csharp>
 
<code csharp>
Line 78: Line 78:
 
</code>
 
</code>
  
# set event OnNavigatedTo and BrowserControl_Navigated
+
* set event OnNavigatedTo and BrowserControl_Navigated
  
 
<code csharp>
 
<code csharp>
Line 220: Line 220:
 
</code>
 
</code>
  
 +
===== Get other user timeline =====
 +
Once you already authenticate with Twitter service, now it's time to access/display user's timeline
 +
 +
* add Listbox to your page
 +
<code xml>
 +
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="0,0,0 ,0" >
 +
                    <Button Height="100" Width="300" x:Name="btnTwitter" Content="Sign In Twitter" Visibility="Visible" Click="btnTwitter_Click" Foreground="Black" BorderBrush="Black"/>
 +
                    <ListBox Height="592"  Margin="0,5,0,0" x:Name="listTweets" VerticalAlignment="Top" Width="450" Tap="tweet_Tap" Visibility="Collapsed" Foreground="Black">
 +
                        <ListBox.ItemTemplate>
 +
                            <DataTemplate>
 +
                                <StackPanel Orientation="Horizontal" Height="150">
 +
                                    <Image Source="{Binding ImageSource}" Height="48" Width="48" VerticalAlignment="Top" Margin="0,4,8,0"/>
 +
                                    <StackPanel Width="350">
 +
                                        <TextBlock Text="{Binding UserName}" Foreground="GreenYellow" FontSize="22" />
 +
                                        <TextBlock Text="{Binding CreatedAt}" Foreground="White" FontSize="18" />
 +
                                        <TextBlock Text="{Binding Message}" TextTrimming="WordEllipsis" TextWrapping="Wrap" FontSize="18"  />
 +
                                    </StackPanel>
 +
                                </StackPanel>
 +
                            </DataTemplate>
 +
                        </ListBox.ItemTemplate>
 +
                    </ListBox>
 +
 +
                </Grid>
 +
</code>
 +
* use '''using TweetSharp;''' in your page
 +
* Create a class, I called it TwitteItem
 +
<code csharp>
 +
public class TwitterItem
 +
        {
 +
            public string UserName { get; set; }
 +
            public string Message { get; set; }
 +
            public string ImageSource { get; set; }
 +
            public string CreatedAt { get; set; }
 +
        }
 +
</code>
 +
* Define variabel to use TwitterService
 +
<code csharp>
 +
public TwitterService service;
 +
</code>
 +
* Get your AccessToken and AccessTokenSecret
 +
<code csharp>
 +
IsolatedStorageSettings mysetting = IsolatedStorageSettings.ApplicationSettings;
 +
                        try
 +
                        {
 +
                            mysetting.TryGetValue("twitter_token", out value);
 +
                            mysetting.TryGetValue("twitter_tokensecret", out value2);
 +
                        }
 +
                        catch
 +
                        {
 +
                        }
 +
</code>
 +
* Access the timeline
 +
<code csharp>
 +
service = new TwitterService("consumerkey", "consumersecret", value, value2);
 +
                            //tampilkan data
 +
                            var options = new ListTweetsOnUserTimelineOptions { ScreenName = "dvlup"};
 +
 +
                            service.ListTweetsOnUserTimeline(options, (status, response) =>
 +
                            {
 +
                                if (response.StatusCode == HttpStatusCode.OK)
 +
                                {
 +
                                    TwitterItem mytweet = new TwitterItem();
 +
 +
                                    foreach (var status1 in status)
 +
                                    {
 +
 +
                                        //Console.WriteLine(status1.Text);
 +
                                        dispatcher.BeginInvoke(() =>
 +
                                        {
 +
                                            mytweet.CreatedAt = status1.CreatedDate.AddHours(7).ToString();
 +
                                            mytweet.ImageSource = status1.User.ProfileImageUrl;
 +
                                            mytweet.Message = status1.Text;
 +
                                            mytweet.UserName = status1.Author.ScreenName;
 +
                                            listTweets.Items.Add(mytweet);
 +
                                            mytweet = new TwitterItem();
 +
                                        });
 +
                                    }
 +
                                }
 +
                            });
 +
</code>
  
 
 
== Summary ==
 
== Summary ==
  

Revision as of 21:07, 5 February 2014

This article explains how to use Twitter services using TweetSharp, post new tweet and get friends's timeline

WP Metro Icon Web.png
SignpostIcon XAML 40.png
WP Metro Icon WP8.png
SignpostIcon WP7 70px.png
Article Metadata
Tested with
SDK: Windows Phone 7.1 SDK, Windows Phone 8 SDK
Devices(s): Lumia 710, Lumia 520, Lumia 720
CompatibilityArticle
Created: (06 Feb 2014)
Last edited: rgunawans (05 Feb 2014)

Contents

Introduction

There's many way to integrate Twitter into our Windows Phone application, first we can use Infragistics Access Control, it's only takes 5-10 minutes OR we can do it manually.

Here is the steps:

  • Register your app with Twitter
    1. go to http://dev.twitter.com/apps
    2. Click on the Register a new app button
    3. Fill out the form
    4. You need the ApplicationType to be Client and Default Access Type: should be Read & Writer we do want to be able to Tweet afterall
  • Create New Project
  • From the Tools menu, select Library Package Manager and then click Package Manager Console
  • type Install-Package TweetSharp, wait until finish install
  • Add new page TwitterAuthPage.xaml
  • Add Webbrowser control to the page
    <Grid x:Name="LayoutRoot" Background="Transparent">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<ProgressBar x:Name="ProgressBar" VerticalAlignment="Top" IsIndeterminate="False" Visibility="Collapsed"/>
<!--TitlePanel contains the name of the application and page title-->
<!--<StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="12,17,0,28">
<TextBlock x:Name="ApplicationTitle" Text="MY APPLICATION" Style="{StaticResource PhoneTextNormalStyle}"/>
<TextBlock x:Name="PageTitle" Text="page name" Margin="9,-7,0,0" Style="{StaticResource PhoneTextTitle1Style}"/>
</StackPanel>-->
<!--ContentPanel - place additional content here-->
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
<phone:WebBrowser x:Name="BrowserControl" Navigated="BrowserControl_Navigated" Navigating="BrowserControl_Navigating" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" />
</Grid>
</Grid>
  • put the code below BrowserControl_Navigating:
private void BrowserControl_Navigating(object sender, NavigatingEventArgs e)
{
ProgressBar.IsIndeterminate = true;
ProgressBar.Visibility = Visibility.Visible;
if (e.Uri.AbsoluteUri.CompareTo("https://api.twitter.com/oauth/authorize") == 0)
{
ProgressBar.IsIndeterminate = true;
ProgressBar.Visibility = Visibility.Visible;
}
if (!e.Uri.AbsoluteUri.Contains(TwitterSettings.CallbackUri))
return;
e.Cancel = true;
var arguments = e.Uri.AbsoluteUri.Split('?');
if (arguments.Length < 1)
return;
GetAccessToken(arguments[1]);
}
  • set event OnNavigatedTo and BrowserControl_Navigated
protected override void OnNavigatedTo(NavigationEventArgs e)
{
//check status, apakah token dan token scret ada
 
 
GetTwitterToken();
ProgressBar.Visibility = Visibility.Visible;
ProgressBar.IsIndeterminate = true;
}
private void BrowserControl_Navigated(object sender, NavigationEventArgs e)
{
ProgressBar.IsIndeterminate = false;
ProgressBar.Visibility = Visibility.Collapsed;
}
 
private void GetTwitterToken()
{
var credentials = new OAuthCredentials
{
Type = OAuthType.RequestToken,
SignatureMethod = OAuthSignatureMethod.HmacSha1,
ParameterHandling = OAuthParameterHandling.HttpAuthorizationHeader,
ConsumerKey = TwitterSettings.ConsumerKey,
ConsumerSecret = TwitterSettings.ConsumerKeySecret,
Version = TwitterSettings.OAuthVersion,
CallbackUrl = TwitterSettings.CallbackUri
};
var client = new RestClient
{
Authority = "https://api.twitter.com/oauth",
Credentials = credentials,
HasElevatedPermissions = true,
SilverlightAcceptEncodingHeader = "gizp",
DecompressionMethods = DecompressionMethods.GZip,
};
 
var request = new RestRequest
{
Path = "/request_token"
};
client.BeginRequest(request, new RestCallback(TwitterRequestTokenCompleted));
}
private void TwitterRequestTokenCompleted(RestRequest request, RestResponse response, object userstate)
{
_oAuthToken = GetQueryParameter(response.Content, "oauth_token");
_oAuthTokenSecret = GetQueryParameter(response.Content, "oauth_token_secret");
 
var authorizeUrl = TwitterSettings.AuthorizeUri + "?oauth_token=" + _oAuthToken;
if (String.IsNullOrEmpty(_oAuthToken) || String.IsNullOrEmpty(_oAuthTokenSecret))
{
Dispatcher.BeginInvoke(() => MessageBox.Show("error calling twitter"));
return;
}
Dispatcher.BeginInvoke(() => BrowserControl.Navigate(new Uri(authorizeUrl)));
}
private static string GetQueryParameter(string input, string parameterName)
{
foreach (string item in input.Split('&'))
{
var parts = item.Split('=');
if (parts[0] == parameterName)
{
return parts[1];
}
}
return String.Empty;
}
private void GetAccessToken(string uri)
{
var requestToken = GetQueryParameter(uri, "oauth_token");
if (requestToken != _oAuthToken)
{
MessageBox.Show("Twitter auth tokens don't match");
}
var requestVerifier = GetQueryParameter(uri, "oauth_verifier");
var credentials = new OAuthCredentials
{
Type = OAuthType.AccessToken,
SignatureMethod = OAuthSignatureMethod.HmacSha1,
ParameterHandling = OAuthParameterHandling.HttpAuthorizationHeader,
ConsumerKey = TwitterSettings.ConsumerKey,
ConsumerSecret = TwitterSettings.ConsumerKeySecret,
Token = _oAuthToken,
TokenSecret = _oAuthTokenSecret,
Verifier = requestVerifier
};
var client = new RestClient
{
Authority = "https://api.twitter.com/oauth",
Credentials = credentials,
HasElevatedPermissions = true
};
var request = new RestRequest
{
Path = "/access_token"
};
client.BeginRequest(request, new RestCallback(RequestAccessTokenCompleted));
}

Above procedure will direct to twitter page to ask user enter their username and password then authenticate with apps

After userenter the username and password, save the twitter AccessToken and AccessTokenSecret

private void RequestAccessTokenCompleted(RestRequest request, RestResponse response, object userstate)
{
var twitteruser = new TwitterAccess
{
AccessToken = GetQueryParameter(response.Content, "oauth_token"),
AccessTokenSecret = GetQueryParameter(response.Content, "oauth_token_secret"),
UserId = GetQueryParameter(response.Content, "user_id"),
ScreenName = GetQueryParameter(response.Content, "screen_name")
};
if (String.IsNullOrEmpty(twitteruser.AccessToken) || String.IsNullOrEmpty(twitteruser.AccessTokenSecret))
{
Dispatcher.BeginInvoke(() => MessageBox.Show(response.Content));
return;
}
Helper.SaveSetting(Constants.TwitterAccess, twitteruser);
IsolatedStorageSettings mysetting = IsolatedStorageSettings.ApplicationSettings;
mysetting.Remove("twitter_token");
mysetting.Remove("twitter_tokensecret");
 
mysetting.Add("twitter_token", twitteruser.AccessToken);
mysetting.Add("twitter_tokensecret", twitteruser.AccessTokenSecret);
 
mysetting.Save();
 
Dispatcher.BeginInvoke(() =>
{
if (NavigationService.CanGoBack)
{
NavigationService.GoBack();
}
});
}
Get other user timeline

Once you already authenticate with Twitter service, now it's time to access/display user's timeline

  • add Listbox to your page
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="0,0,0 ,0" >
<Button Height="100" Width="300" x:Name="btnTwitter" Content="Sign In Twitter" Visibility="Visible" Click="btnTwitter_Click" Foreground="Black" BorderBrush="Black"/>
<ListBox Height="592" Margin="0,5,0,0" x:Name="listTweets" VerticalAlignment="Top" Width="450" Tap="tweet_Tap" Visibility="Collapsed" Foreground="Black">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal" Height="150">
<Image Source="{Binding ImageSource}" Height="48" Width="48" VerticalAlignment="Top" Margin="0,4,8,0"/>
<StackPanel Width="350">
<TextBlock Text="{Binding UserName}" Foreground="GreenYellow" FontSize="22" />
<TextBlock Text="{Binding CreatedAt}" Foreground="White" FontSize="18" />
<TextBlock Text="{Binding Message}" TextTrimming="WordEllipsis" TextWrapping="Wrap" FontSize="18" />
</StackPanel>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
 
</Grid>
  • use using TweetSharp; in your page
  • Create a class, I called it TwitteItem
 public class TwitterItem
{
public string UserName { get; set; }
public string Message { get; set; }
public string ImageSource { get; set; }
public string CreatedAt { get; set; }
}
  • Define variabel to use TwitterService
 public TwitterService service;
  • Get your AccessToken and AccessTokenSecret
IsolatedStorageSettings mysetting = IsolatedStorageSettings.ApplicationSettings;
try
{
mysetting.TryGetValue("twitter_token", out value);
mysetting.TryGetValue("twitter_tokensecret", out value2);
}
catch
{
}
  • Access the timeline
service = new TwitterService("consumerkey", "consumersecret", value, value2);
//tampilkan data
var options = new ListTweetsOnUserTimelineOptions { ScreenName = "dvlup"};
 
service.ListTweetsOnUserTimeline(options, (status, response) =>
{
if (response.StatusCode == HttpStatusCode.OK)
{
TwitterItem mytweet = new TwitterItem();
 
foreach (var status1 in status)
{
 
//Console.WriteLine(status1.Text);
dispatcher.BeginInvoke(() =>
{
mytweet.CreatedAt = status1.CreatedDate.AddHours(7).ToString();
mytweet.ImageSource = status1.User.ProfileImageUrl;
mytweet.Message = status1.Text;
mytweet.UserName = status1.Author.ScreenName;
listTweets.Items.Add(mytweet);
mytweet = new TwitterItem();
});
}
}
});

Summary

Remove Category:Draft when the page is complete or near complete


The "platform categories" will be displayed here in preview only - Copy paste relevant categories into text here

Version Hint

Windows Phone: [[Category:Windows Phone]]
[[Category:Windows Phone 7.5]]
[[Category:Windows Phone 8]]

Nokia Asha: [[Category:Nokia Asha]]
[[Category:Nokia Asha Platform 1.0]]

Series 40: [[Category:Series 40]]
[[Category:Series 40 1st Edition]] [[Category:Series 40 2nd Edition]]
[[Category:Series 40 3rd Edition (initial release)]] [[Category:Series 40 3rd Edition FP1]] [[Category:Series 40 3rd Edition FP2]]
[[Category:Series 40 5th Edition (initial release)]] [[Category:Series 40 5th Edition FP1]]
[[Category:Series 40 6th Edition (initial release)]] [[Category:Series 40 6th Edition FP1]] [[Category:Series 40 Developer Platform 1.0]] [[Category:Series 40 Developer Platform 1.1]] [[Category:Series 40 Developer Platform 2.0]]

Symbian: [[Category:Symbian]]
[[Category:S60 1st Edition]] [[Category:S60 2nd Edition (initial release)]] [[Category:S60 2nd Edition FP1]] [[Category:S60 2nd Edition FP2]] [[Category:S60 2nd Edition FP3]]
[[Category:S60 3rd Edition (initial release)]] [[Category:S60 3rd Edition FP1]] [[Category:S60 3rd Edition FP2]]
[[Category:S60 5th Edition]]
[[Category:Symbian^3]] [[Category:Symbian Anna]] [[Category:Nokia Belle]]

Add categories below using category selector.

491 page views in the last 30 days.
×