Latest Twitter Integration in windows phone 8

This article will help you in posting your tweets/ updating your timeline status in Twitter using Hammock library...You may get this library from http://www.nuget.org/packages/Hammock.

To work with Twitter, we have to register our app at Twitter Developer Site. To do so, after we successfully logged in in Twitter, we've to go to My Applications | Create a New Application. Now we have to fill the details of our app.

After registering the app, we will be provided with some URLs that we will be using in making OAuth requests and Consumer key and Consumer Secret Key. Save the two keys somewhere as we will require them later in the project.

  • The MainPage.xaml file has the following contents now.

<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">

<Grid.RowDefinitions>

<RowDefinition Height="*"/>

</Grid.RowDefinitions>

 

<phone:WebBrowser Grid.Row="0" Margin="-6,3,0,1" Name="loginBrowserControl" Visibility="Collapsed"

Navigated="loginBrowserControl_Navigated" Navigating="loginBrowserControl_Navigating"

IsScriptEnabled="True"/>

 

<Grid x:Name="TweetPanel" Grid.Row="0" Visibility="Collapsed">

<Grid.RowDefinitions>

<RowDefinition Height=".15*"/>

<RowDefinition Height=".10*"/>

<RowDefinition Height=".60*"/>

<RowDefinition Height=".15*"/>

</Grid.RowDefinitions>

 

<TextBlock Grid.Row="0" x:Name="txtUserName" VerticalAlignment="Center" HorizontalAlignment="Center" FontSize="26" FontFamily="Segoe WP Bold" Foreground="Red"/>

<TextBlock Grid.Row="1" Margin="10" VerticalAlignment="Center" HorizontalAlignment="Left" Text="Enter your Tweet" FontSize="24" FontFamily="Segoe WP Bold"/>

<TextBox Grid.Row="2" x:Name="txtTweetContent" Margin="20,-10,20,100" TextWrapping="Wrap" Text="" FontSize="24" FontFamily="Segoe WP Bold" />

<Button Grid.Row="3" x:Name="btnPostTweet" Content="Post Tweet" HorizontalAlignment="Center" Click="btnPostTweet_Click"/>

</Grid>

</Grid>

Note: It is important to use path like this  Path = "/1.1/statuses/update.json", If you are using 1.0 version path it will never work at all because of Twitter API 1.0 was retired recently and API 1.1 available at present.

 

using System; 

using System.Collections.Generic; 

using System.Linq; 

using Hammock.Web; 

using System.IO; 

using Hammock; 

using System.Text; 

using Hammock.Authentication.OAuth; 

using Microsoft.Phone.Controls; 

using System.Windows; 

using System.Net; 

 

namespace TwitterPost 

    public partial class MainPage : PhoneApplicationPage 

    { 

        //http://developer.nokia.com/Community/Wiki/Twitter:_OAuth_1.0_Authentication_using_Hammock 

        string OAuthTokenKey = string.Empty; 

        string tokenSecret = string.Empty; 

        string accessToken = string.Empty; 

        string accessTokenSecret = string.Empty; 

        string userID = string.Empty; 

        string userScreenName = string.Empty; 

 

        public MainPage() 

        { 

            InitializeComponent(); 

            if (isAlreadyLoggedIn()) 

            { 

                userLoggedIn(); 

            } 

            else 

            { 

                var requestTokenQuery = OAuthUtil.GetRequestTokenQuery(); 

                requestTokenQuery.RequestAsync(AppSettings.RequestTokenUri, null); 

                requestTokenQuery.QueryResponse += new EventHandler<WebQueryResponseEventArgs>(requestTokenQuery_QueryResponse); 

            }             

        } 

 

        private Boolean isAlreadyLoggedIn() 

        { 

            accessToken = MainUtil.GetKeyValue<string>("AccessToken"); 

            accessTokenSecret = MainUtil.GetKeyValue<string>("AccessTokenSecret"); 

            userScreenName = MainUtil.GetKeyValue<string>("ScreenName"); 

 

            if (string.IsNullOrEmpty(accessToken) || string.IsNullOrEmpty(accessTokenSecret)) 

                return false

            else 

                return true

        } 

 

        private void userLoggedIn() 

        { 

            Dispatcher.BeginInvoke(() => 

            { 

               // var SignInMenuItem = (Microsoft.Phone.Shell.ApplicationBarMenuItem)this.ApplicationBar.MenuItems[0]; 

               // SignInMenuItem.IsEnabled = false; 

 

               // var SignOutMenuItem = (Microsoft.Phone.Shell.ApplicationBarMenuItem)this.ApplicationBar.MenuItems[1]; 

                //SignOutMenuItem.IsEnabled = true; 

 

                TweetPanel.Visibility = System.Windows.Visibility.Visible; 

                txtUserName.Text = "Welcome " + userScreenName; 

            }); 

        } 

        private void MenuItemSignOut_Click(object sender, EventArgs e) 

        { 

            MainUtil.SetKeyValue<string>("AccessToken"string.Empty); 

            MainUtil.SetKeyValue<string>("AccessTokenSecret"string.Empty); 

            Dispatcher.BeginInvoke(() => 

            { 

               // var SignInMenuItem = (Microsoft.Phone.Shell.ApplicationBarMenuItem)this.ApplicationBar.MenuItems[0]; 

                //SignInMenuItem.IsEnabled = true; 

 

                //var SignOutMenuItem = (Microsoft.Phone.Shell.ApplicationBarMenuItem)this.ApplicationBar.MenuItems[1]; 

               // SignOutMenuItem.IsEnabled = false; 

 

                TweetPanel.Visibility = System.Windows.Visibility.Collapsed; 

 

                MessageBox.Show("You have been signed out successfully."); 

            }); 

        } 

        private void btnPostTweet_Click(object sender, RoutedEventArgs e) 

        { 

            var credentials = new OAuthCredentials 

            { 

                Type = OAuthType.ProtectedResource, 

                SignatureMethod = OAuthSignatureMethod.HmacSha1, 

                ParameterHandling = OAuthParameterHandling.HttpAuthorizationHeader, 

                ConsumerKey = AppSettings.consumerKey, 

                ConsumerSecret = AppSettings.consumerKeySecret, 

                Token = this.accessToken, 

                TokenSecret = this.accessTokenSecret, 

                Version = "1.0" 

            }; 

 

            var restClient = new RestClient 

            { 

                Authority = "https://api.twitter.com"

                HasElevatedPermissions = true 

            }; 

 

            var restRequest = new RestRequest 

            { 

                Credentials = credentials, 

                Path = "/1.1/statuses/update.json"

                Method = WebMethod.Post 

            }; 

 

            restRequest.AddParameter("status", txtTweetContent.Text); 

            restClient.BeginRequest(restRequest, new RestCallback(PostTweetRequestCallback)); 

        } 

        private void PostTweetRequestCallback(RestRequest request, RestResponse response, object obj) 

        { 

            Deployment.Current.Dispatcher.BeginInvoke(() => 

            { 

                if (response.StatusCode == HttpStatusCode.OK) 

                { 

                    MessageBox.Show("TWEET_POSTED_SUCCESSFULLY"); 

                } 

                else if (response.StatusCode == HttpStatusCode.Forbidden) 

                { 

                    MessageBox.Show("TWEET_POST_ERR_UPDATE_LIMIT"); 

                } 

                else 

                { 

                    MessageBox.Show("WEET_POST_ERR_FAILED"); 

                } 

                txtTweetContent.Text = ""

            }); 

            //var requestTokenQuery = OAuthUtil.GetRequestTokenQuery(); 

            //requestTokenQuery.RequestAsync(AppSettings.RequestTokenUri, null); 

            //requestTokenQuery.QueryResponse += new EventHandler<WebQueryResponseEventArgs>(requestTokenQuery_QueryResponse); 

        } 

 

        void requestTokenQuery_QueryResponse(object sender, WebQueryResponseEventArgs e) 

        { 

            try 

            { 

                StreamReader reader = new StreamReader(e.Response); 

                string strResponse = reader.ReadToEnd(); 

                var parameters = MainUtil.GetQueryParameters(strResponse); 

                OAuthTokenKey = parameters["oauth_token"]; 

                tokenSecret = parameters["oauth_token_secret"]; 

                var authorizeUrl = AppSettings.AuthorizeUri + "?oauth_token=" + OAuthTokenKey; 

 

                Dispatcher.BeginInvoke(() => 

                { 

                    this.loginBrowserControl.Navigate(new Uri(authorizeUrl, UriKind.RelativeOrAbsolute)); 

                }); 

            } 

            catch (Exception ex) 

            { 

                Dispatcher.BeginInvoke(() => 

                { 

                    MessageBox.Show(ex.Message); 

                }); 

            } 

        } 


        private void loginBrowserControl_Navigated(object sender, System.Windows.Navigation.NavigationEventArgs e) 

        { 

            this.loginBrowserControl.Visibility = Visibility.Visible; 

            this.loginBrowserControl.Navigated -= loginBrowserControl_Navigated; 

        } 

 

        private void loginBrowserControl_Navigating(object sender, NavigatingEventArgs e) 

        { 

            if (e.Uri.ToString().StartsWith(AppSettings.CallbackUri)) 

            { 

                var AuthorizeResult = MainUtil.GetQueryParameters(e.Uri.ToString()); 

                var VerifyPin = AuthorizeResult["oauth_verifier"]; 

                this.loginBrowserControl.Visibility = Visibility.Collapsed; 

                var AccessTokenQuery = OAuthUtil.GetAccessTokenQuery(OAuthTokenKey, tokenSecret, VerifyPin); 

                AccessTokenQuery.QueryResponse += new EventHandler<WebQueryResponseEventArgs>(AccessTokenQuery_QueryResponse); 

                AccessTokenQuery.RequestAsync(AppSettings.AccessTokenUri, null); 

            } 

        } 

 

        void AccessTokenQuery_QueryResponse(object sender, WebQueryResponseEventArgs e) 

        { 

            try 

            { 

                StreamReader reader = new StreamReader(e.Response); 

                string strResponse = reader.ReadToEnd(); 

                var parameters = MainUtil.GetQueryParameters(strResponse); 

                accessToken = parameters["oauth_token"]; 

                accessTokenSecret = parameters["oauth_token_secret"]; 

                userID = parameters["user_id"]; 

                userScreenName = parameters["screen_name"]; 

 

                MainUtil.SetKeyValue<string>("AccessToken", accessToken); 

                MainUtil.SetKeyValue<string>("AccessTokenSecret", accessTokenSecret); 

                MainUtil.SetKeyValue<string>("ScreenName", userScreenName); 

                userLoggedIn(); 

            } 

            catch (Exception ex) 

            { 

                Dispatcher.BeginInvoke(() => 

                { 

                    MessageBox.Show(ex.Message); 

                }); 

            } 

        } 

    } 

 

***************************** 

Note:Before going to use above code you must be add following classes 

 

using Hammock.Authentication.OAuth; 

using Hammock.Web; 

using System; 

using System.Collections.Generic; 

using System.IO.IsolatedStorage; 

using System.Linq; 

using System.Text; 

 

namespace TwitterPost 

    public class AppSettings 

    { 

        // twitter 

        public static string RequestTokenUri = "https://api.twitter.com/oauth/request_token"

        public static string AuthorizeUri = "https://api.twitter.com/oauth/authorize"

        public static string AccessTokenUri = "https://api.twitter.com/oauth/access_token"

        public static string CallbackUri = "http://www.google.com";   // we've mentioned Google.com as our callback URL. 

 

//#error TODO REGISTER YOUR APP WITH TWITTER TO GET YOUR KEYS AND FILL THEM IN HERE 

        public static string consumerKey = ""

        public static string consumerKeySecret = ""

 

        public static string oAuthVersion = "1.0a"

    } 

    public class MainUtil 

    { 

        public static Dictionary<stringstring> GetQueryParameters(string response) 

        { 

            Dictionary<stringstring> nameValueCollection = new Dictionary<stringstring>(); 

            string[] items = response.Split('&'); 

            foreach (string item in items) 

            { 

                if (item.Contains("=")) 

                { 

                    string[] nameValue = item.Split('='); 

                    if (nameValue[0].Contains("?")) 

                        nameValue[0] = nameValue[0].Replace("?"""); 

                    nameValueCollection.Add(nameValue[0], System.Net.HttpUtility.UrlDecode(nameValue[1])); 

                } 

            } 

            return nameValueCollection; 

        } 

 

        internal static T GetKeyValue<T>(string key) 

        { 

            if (IsolatedStorageSettings.ApplicationSettings.Contains(key)) 

                return (T)IsolatedStorageSettings.ApplicationSettings[key]; 

            else 

                return default(T); 

        } 

 

        internal static void SetKeyValue<T>(string key, T value) 

        { 

            if (IsolatedStorageSettings.ApplicationSettings.Contains(key)) 

                IsolatedStorageSettings.ApplicationSettings[key] = value; 

            else 

                IsolatedStorageSettings.ApplicationSettings.Add(key, value); 

            IsolatedStorageSettings.ApplicationSettings.Save(); 

        } 

    } 

    public class OAuthUtil 

    { 

        internal static OAuthWebQuery GetRequestTokenQuery() 

        { 

            var oauth = new OAuthWorkflow 

            { 

                ConsumerKey = AppSettings.consumerKey, 

                ConsumerSecret = AppSettings.consumerKeySecret, 

                SignatureMethod = OAuthSignatureMethod.HmacSha1, 

                ParameterHandling = OAuthParameterHandling.HttpAuthorizationHeader, 

                RequestTokenUrl = AppSettings.RequestTokenUri, 

                Version = AppSettings.oAuthVersion, 

                CallbackUrl = AppSettings.CallbackUri 

            }; 

 

            var info = oauth.BuildRequestTokenInfo(WebMethod.Get); 

            var objOAuthWebQuery = new OAuthWebQuery(info, false); 

            objOAuthWebQuery.HasElevatedPermissions = true

            objOAuthWebQuery.SilverlightUserAgentHeader = "Hammock"

            return objOAuthWebQuery; 

        } 

 

        internal static OAuthWebQuery GetAccessTokenQuery(string requestToken, string RequestTokenSecret, string oAuthVerificationPin) 

        { 

            var oauth = new OAuthWorkflow 

            { 

                AccessTokenUrl = AppSettings.AccessTokenUri, 

                ConsumerKey = AppSettings.consumerKey, 

                ConsumerSecret = AppSettings.consumerKeySecret, 

                ParameterHandling = OAuthParameterHandling.HttpAuthorizationHeader, 

                SignatureMethod = OAuthSignatureMethod.HmacSha1, 

                Token = requestToken, 

                Verifier = oAuthVerificationPin, 

                Version = AppSettings.oAuthVersion 

            }; 

            var info = oauth.BuildAccessTokenInfo(WebMethod.Post); 

            var objOAuthWebQuery = new OAuthWebQuery(info, false); 

            objOAuthWebQuery.HasElevatedPermissions = true

            objOAuthWebQuery.SilverlightUserAgentHeader = "Hammock"

            return objOAuthWebQuery; 

        } 

    }  

Next Recommended Reading How To Reset Windows Phone Emulator(XDE)