Namespaces

Variants
Actions

Please note that as of October 24, 2014, the Nokia Developer Wiki will no longer be accepting user contributions, including new entries, edits and comments, as we begin transitioning to our new home, in the Windows Phone Development Wiki. We plan to move over the majority of the existing entries over the next few weeks. Thanks for all your past and future contributions.

Twitter using TweetSharp Library on Windows Phone

From Wiki
Jump to: navigation, search
Featured Article
30 Mar
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
Code ExampleTested with
SDK: Windows Phone 7.1 SDK, Windows Phone 8 SDK
Devices(s): Lumia 710, Lumia 520, Lumia 720
Compatibility
Dependencies: TweetSharp
Article
Created: rgunawans (04 Feb 2014)
Last edited: croozeus (31 Mar 2014)

Contents

Introduction

There are 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. In this article I'll explain how to integrate Windows Phone app to Twitter using TweetSharp.

Required files

  1. create new folder, name it Common
    Common Files
  2. add files like picture above
  3. Below is for Helper.cs
    using System;
    using System.IO;
    using System.IO.IsolatedStorage;
    using System.Runtime.Serialization;
    using System.Windows;
     
    namespace TweetSharpSample.Common
    {
    class Helper
    {
    private static Object _thisLock = new Object();
    public static T LoadSetting<T>(string fileName)
    {
    using (var store = IsolatedStorageFile.GetUserStoreForApplication())
    {
    if (!store.FileExists(fileName))
    return default(T);
    lock (_thisLock)
    {
    try
    {
    using (var stream = store.OpenFile(fileName, FileMode.Open, FileAccess.Read))
    {
    var serializer = new DataContractSerializer(typeof(T));
    return (T)serializer.ReadObject(stream);
    }
    }
    catch (SerializationException se)
    {
    Deployment.Current.Dispatcher.BeginInvoke(
    () => MessageBox.Show(String.Format("Serialize file error {0}:{1}", se.Message, fileName)));
    return default(T);
    }
    catch (Exception e)
    {
    Deployment.Current.Dispatcher.BeginInvoke(
    () => MessageBox.Show(String.Format("Load file error {0}:{1}", e.Message, fileName)));
    return default(T);
    }
    }
    }
    }
    public static void SaveSetting<T>(string fileName, T dataToSave)
    {
    using (var store = IsolatedStorageFile.GetUserStoreForApplication())
    {
    lock (_thisLock)
    {
    try
    {
    using (var stream = store.CreateFile(fileName))
    {
    var serializer = new DataContractSerializer(typeof(T));
    serializer.WriteObject(stream, dataToSave);
    }
    }
    catch (Exception e)
    {
    MessageBox.Show(String.Format("Save file error {0}:{1}", e.Message, fileName));
    return;
    }
    }
    }
    }
    public static void DeleteFile(string fileName)
    {
    using (var store = IsolatedStorageFile.GetUserStoreForApplication())
    {
    if (store.FileExists(fileName))
    store.DeleteFile(fileName);
    }
    }
    public static DateTime ParseDateTime(string date)
    {
    var dayOfWeek = date.Substring(0, 3).Trim();
    var month = date.Substring(4, 3).Trim();
    var dayInMonth = date.Substring(8, 2).Trim();
    var time = date.Substring(11, 9).Trim();
    var offset = date.Substring(20, 5).Trim();
    var year = date.Substring(25, 5).Trim();
    var dateTime = string.Format("{0}-{1}-{2} {3}", dayInMonth, month, year, time);
    var ret = DateTime.Parse(dateTime).ToLocalTime();
    return ret;
    }
    public static void ShowMessage(string message)
    {
    Deployment.Current.Dispatcher.BeginInvoke(() => MessageBox.Show(message));
    }
     
    }
    }
  4. Below code for Constants.cs
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
     
    namespace TweetSharpSample.Common
    {
    class Constants
    {
    public static string TwitterAccess = "TweetSamples";
     
    }
    }
  5. Below code for TwitterSettings.cs
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
     
    namespace TweetSharpSample
    {
    public class TwitterSettings
    {
    public static string ConsumerKey = "your consumer key";
    public static string ConsumerKeySecret = "your consumer key secret";
    public static string RequestTokenUri = "https://api.twitter.com/oauth/request_token";
    public static string OAuthVersion = "1.1";
    public static string CallbackUri = "http://www.bing.com";
    public static string AuthorizeUri = "https://api.twitter.com/oauth/authorize";
    public static string AccessTokenUri = "https://api.twitter.com/oauth/access_token";
    }
    public class TwitterAccess
    {
    public string AccessToken { get; set; }
    public string AccessTokenSecret { get; set; }
    public string UserId { get; set; }
    public string ScreenName { get; set; }
    }
    }

Note.pngNote: Please remember to change ConsumerKey and ConsumerKeySecret with yours.

If got error on DataContractSerializer, please import System.Runtime.Serialization.

  1. Project -> Add Reference, find System.Runtime.Serialiation
    Adding System.Runtime.Serialization
  2. click OK


Step by step

  1. Register your app with Twitter
    • go to http://dev.twitter.com/apps
    • Click on the Register a new app button
    • 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
  2. Create New Project
  3. From the Tools menu, select Library Package Manager and then click Package Manager Console
  4. type Install-Package TweetSharp, wait until finish install
  5. Add new page TwitterAuthPage.xaml
  6. 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>
  7. 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]);
    }
  8. 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));
    }

The above procedure will direct you to the twitter page to ask user enter their username and password and then authenticate with apps.

Screenshot Access Twitter Services

After user enter 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 authenticate with Twitter service, it's time to access/display user's timeline.

  1. 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>
  2. use using TweetSharp in your page
  3. Create a class, I called it TwitterItem
     public class TwitterItem
    {
    public string UserName { get; set; }
    public string Message { get; set; }
    public string ImageSource { get; set; }
    public string CreatedAt { get; set; }
    }
  4. Define variable to use TwitterService
     public TwitterService service;
  5. Get your AccessToken and AccessTokenSecret
    IsolatedStorageSettings mysetting = IsolatedStorageSettings.ApplicationSettings;
    try
    {
    mysetting.TryGetValue("twitter_token", out value);
    mysetting.TryGetValue("twitter_tokensecret", out value2);
    }
    catch
    {
    }
  6. 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 have AccessToken and AccessTokenSecret. If you don't have, it will redirect you to the authentication page. If you 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]]

This page was last modified on 31 March 2014, at 06:15.
522 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.

×