×
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 1: Line 1:
[[Category:Draft]]
+
[[Category:Windows Phone 8]][[Category:Windows Phone 7.5]][[Category:Tools for Windows Phone]]
 
{{Abstract|This article explains how to use Twitter services using TweetSharp, post new tweet and get friends's timeline }}  
 
{{Abstract|This article explains how to use Twitter services using TweetSharp, post new tweet and get friends's timeline }}  
  
Line 301: Line 301:
 
</code>
 
</code>
  
== Summary ==
 
  
+
===== Sending tweet =====
''Remove Category:Draft when the page is complete or near complete''
+
Below code is how to send tweet from your apps:
 +
<code csharp>
 +
IsolatedStorageSettings mysetting = IsolatedStorageSettings.ApplicationSettings;
 +
            try
 +
            {
 +
                mysetting.TryGetValue("twitter_token", out value);
 +
                mysetting.TryGetValue("twitter_tokensecret", out value2);
 +
            }
 +
            catch
 +
            {
 +
            }
 +
            if (value == null)
 +
            { NavigationService.Navigate(new Uri("/Pages/TwitterAuthPage.xaml", UriKind.Relative)); }
 +
            else
 +
            {
 +
                if (txtInfo.Text.Trim().Length > 0)
 +
                {
 +
                    service.SendTweet(new SendTweetOptions { Status =  txtInfo.Text },
 +
                      (statuses, response) =>
 +
                      {
 +
                          if (response.StatusCode == HttpStatusCode.OK)
 +
                          {
 +
                             
 +
                              dispatcher.BeginInvoke(() =>
 +
                              {
 +
                                  MessageBox.Show("Tweet sent!");
 +
                                  txtInfo.Text = "";
 +
                                  txtInfo.Focus();
  
 +
                              }
 +
                              );
  
''The "platform categories" will be displayed here in '''preview''' only - Copy paste relevant categories into text here''
+
                          }
 +
                          else
 +
                          {
 +
                              throw new Exception(response.StatusCode.ToString());
 +
                          }
 +
 
 +
                      });
 +
                }
 +
            }
 +
</code>
 +
Above code will check if you already had AccessToken and AccessTokenSecret, if you don't have, then it will redirect to authenticate page, if already have, then you can send the tweet, quite simple.
 +
 
 +
== Summary ==
 +
This article shows how to authenticate with Twitter API in the detail, if you're have Infragistics license, you can use [[Authenticating_to_Social_Services_using_Infragistics|Infragistics Access Control]] to get AccessToken and AccessTokenSecret.
 +
 
{{VersionHint}}
 
{{VersionHint}}
  
 
''Add categories below using category selector. ''
 
''Add categories below using category selector. ''

Revision as of 21:17, 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();
});
}
}
});


Sending tweet

Below code is how to send tweet from your apps:

 IsolatedStorageSettings mysetting = IsolatedStorageSettings.ApplicationSettings;
try
{
mysetting.TryGetValue("twitter_token", out value);
mysetting.TryGetValue("twitter_tokensecret", out value2);
}
catch
{
}
if (value == null)
{ NavigationService.Navigate(new Uri("/Pages/TwitterAuthPage.xaml", UriKind.Relative)); }
else
{
if (txtInfo.Text.Trim().Length > 0)
{
service.SendTweet(new SendTweetOptions { Status = txtInfo.Text },
(statuses, response) =>
{
if (response.StatusCode == HttpStatusCode.OK)
{
 
dispatcher.BeginInvoke(() =>
{
MessageBox.Show("Tweet sent!");
txtInfo.Text = "";
txtInfo.Focus();
 
}
);
 
}
else
{
throw new Exception(response.StatusCode.ToString());
}
 
});
}
}

Above code will check if you already had AccessToken and AccessTokenSecret, if you don't have, then it will redirect to authenticate page, if already have, then you can send the tweet, quite simple.

Summary

This article shows how to authenticate with Twitter API in the detail, if you're have Infragistics license, you can use Infragistics Access Control to get AccessToken and AccessTokenSecret.

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.

359 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.

×