×
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 34: Line 34:
 
# 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 AuthPage.xaml
+
# Add new page TwitterAuthPage.xaml
# put the code below:
+
# Add Webbrowser control to the page
  
 +
<code xml>
 +
    <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>
 +
</code>
  
 +
# put the code below '''BrowserControl_Navigating''':
  
 +
<code csharp>
 +
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]);
 +
        }
 +
</code>
 +
 +
# set event OnNavigatedTo and BrowserControl_Navigated
 +
 +
<code csharp>
 +
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));
 +
        }
 +
</code>
 +
 +
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'''
 +
 +
<code csharp>
 +
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();
 +
                }
 +
            });
 +
        }
 +
</code>
 +
 +
 +
 
== Summary ==
 
== Summary ==
  

Revision as of 20:53, 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)

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:

  1. 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
  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>
  1. 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]);
}
  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();
}
});
}


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.

503 page views in the last 30 days.
×