Click here to Skip to main content
15,867,141 members
Articles / Desktop Programming / WPF

Twitter Client - Login to C# application using twitter oAuth using Twitterizer library

Rate me:
Please Sign up or sign in to vote.
4.93/5 (13 votes)
28 Apr 2013CPOL3 min read 55K   3.1K   28   9
C# Twitter Integration using Twitterizer

Introduction 

This article describes WPF application integration with twitter and a simple twitter client with all basic functionalities(tweet, direct messages etc.)  using Twitterizer library. 

The idea is to provide an easy way to use twitter to sign in to an app, and to perform basic operations that may be useful to developers.  

Background 

There is already a good article there on codeproject that describes twitter and facebook integration named "C# Application integration with facebook and twitter with oAuth".  

Please create your own secretKey and token as described in above mentioned article.

But the purpose of this article is to provide most used functions of twitter using Twitterizer. I was searching for twitterizer help and faced many problems, so i decide to write an article for someone else who is using twitterizer for C#.

This article uses xml and browser in WPF. So before continuing, make sure you know about these. There are many articles for xml and browser control, e.g. XML for Beginners So i will not discuss about these.

How it works

Image 1 Image 2

When the app runs, it checks whether user is already logged in or not. If not, then display a browser window to authenticate from twitter. User logs in to twitter, twitter generates a pin that user pastes to textbox provided there. Now main windows launches where all operations are performed. 

Login/Out

When user logs in to twitter, twitter sends a key value pair to the application called tokens. These tokens are then saved to an xml. Whenever user want to update status, send direct message or check for followers etc, these tokens must be sent to twitter with request.

When user first time logs in, this token is saved to xml, and next time when user launches app, the app first checks whether the tokens are saved in xml file or not. If tokens are already saved, it means user is logged in already, otherwise browser is displayed. 

When user want to logout, then simply delete that xml file by clicking log out button in main window. Next time, the user is again prompted to login.

Using the code  

Code contains three WPF windows and two classes. 

Browser Window & Class : 
C#
public partial class Browser : Window
{
    public Browser()
    {
        InitializeComponent();
    }
    XMLStuff myXML;

    private void btnRefresh_Click(object sender, RoutedEventArgs e)
    {
        browserControl.Refresh();
    }
    // checks whether already logged in or not. if logged in then goto main window, else goto twitter
    private void Window_Loaded_1(object sender, RoutedEventArgs e)
    {
        myXML = new XMLStuff();
        statusBarMessage.Text = "Checking for login info..";
        bool loggedIn = AlreadyLoggedIn();
        statusBarMessage.Text = "Not logged in, shifting to login page.";
        if (!loggedIn)
        {
            Login();
            statusBarMessage.Text = "";
        }
        else
        {
            MainWindow mw = new MainWindow();
            mw.Show();
            this.Close();
        }
    }
 
    private void btnSend_Click(object sender, RoutedEventArgs e)
    {
        TwitterStuff.pin = tbPin.Text; //when user enters pin, it is saved to TwitterStuff class
        Properties.Settings.Default.Save();
        TwitterStuff.tokenResponse2 = OAuthUtility.GetAccessToken(TwitterStuff.consumerKey, 
          TwitterStuff.consumerSecret, TwitterStuff.tokenResponse.Token, tbPin.Text);
        myXML.writeToXML(TwitterStuff.tokenResponse2.ScreenName.ToString(), 
          TwitterStuff.tokenResponse2.Token, TwitterStuff.tokenResponse2.TokenSecret);
        TwitterStuff.screenName = TwitterStuff.tokenResponse2.ScreenName.ToString();
        SetLocalTokens();
        //MessageBox.Show("Logged In and local tokens are set");
        statusBarMessage.Text = "Successfuly logged in.";
        MainWindow mw = new MainWindow();
        mw.Show();
        this.Close();
    }

    private void browserControl_Navigated(object sender, System.Windows.Navigation.NavigationEventArgs e)
    {
        lblUri.Content = browserControl.Source.AbsoluteUri.ToString();
        progressBar.IsIndeterminate = false;
        progressBar.Visibility = System.Windows.Visibility.Hidden;
        // MessageBox.Show(browserControl.Source.AbsoluteUri.ToString());
    }
    // open twitter site with our consumerKey and consumerSecret to login
    private void Login()
    {
        TwitterStuff.tokenResponse = OAuthUtility.GetRequestToken(TwitterStuff.consumerKey, 
                  TwitterStuff.consumerSecret, TwitterStuff.callbackAddy);
        string target = "http://twitter.com/oauth/authenticate?oauth_token=" + 
                  TwitterStuff.tokenResponse.Token;
        try
        {
            browserControl.Navigate(new Uri(target));
        }
        catch (System.ComponentModel.Win32Exception noBrowser)
        {
            if (noBrowser.ErrorCode == -2147467259)
                MessageBox.Show(noBrowser.Message);
        }
        catch (Exception other)
        {
            MessageBox.Show(other.Message);
        }
    }

 
    /// <summary>
    /// Initialize token
    /// </summary>
    private void SetLocalTokens()
    {
        TwitterStuff.tokens = new OAuthTokens();
        TwitterStuff.tokens.AccessToken = TwitterStuff.tokenResponse2.Token;
        TwitterStuff.tokens.AccessTokenSecret = TwitterStuff.tokenResponse2.TokenSecret;
        TwitterStuff.tokens.ConsumerKey = TwitterStuff.consumerKey;
        TwitterStuff.tokens.ConsumerSecret = TwitterStuff.consumerSecret;
    }
    // if already logged in, then tokens are loaded from xml file using this method.
    private bool SetLocalTokens(string accessToken, string tokenSec)
    {
        try
        {
            TwitterStuff.tokens = new OAuthTokens();
            TwitterStuff.tokens.AccessToken = accessToken;
            TwitterStuff.tokens.AccessTokenSecret = tokenSec;
            TwitterStuff.tokens.ConsumerKey = TwitterStuff.consumerKey;
            TwitterStuff.tokens.ConsumerSecret = TwitterStuff.consumerSecret;
            // MessageBox.Show("Tokens with arguments initialized.");
            return true;
        }
        catch (Exception)
        {
            return false;
        }
    }
    // this method checks whether xml file exists and reads data,
    // if so, it means that user is logged in. and true is returned 
    private bool AlreadyLoggedIn()
    {
        try
        {
            //MessageBox.Show("Trying to get login info");
            List<string> LoginInfo = myXML.readFromXml();

            TwitterStuff.screenName = LoginInfo[1];
            if (!SetLocalTokens(LoginInfo[2], LoginInfo[3]))
                return false;
            //MessageBox.Show("Already logged in.");
            return true;
        }
        catch (Exception e)
        {
            statusBarMessage.Text = "Not logged in.";
            return false;
        }
    }

    private void browserControl_Navigating(object sender, 
                     System.Windows.Navigation.NavigatingCancelEventArgs e)
    {
        progressBar.IsIndeterminate = true;
        progressBar.Visibility = System.Windows.Visibility.Visible;
    }
}

Image 3

XMLStuff class just writes token strings to xml file using writeToXML method and reads token using readFromXml.

When user clicks logout btn, then xml logout method is called that just deletes the XML file.

TwitterStuff

This class performs all twitter related functions.

C#
public static string consumerKey = "your consumer key here";
public static string consumerSecret = "your consumer secret here"

Obtain your consumerKey and consumerSecret from twitter by following above mentioned article.

C#
public static string pin = "xxxxxxx";

When user logins to twitter, twitter provides a pin, that pin is stored in this variable.

C#
public static OAuthTokens tokens;

These tokens are passed as argument to all main twitter functions. e.g. sending message function:

C#
TwitterDirectMessage.Send(tokens, receiverScreenName.Trim(), msg);

Method to Update Status: 

C#
public bool tweetIt(string status)
{
    try
    {
        TwitterStatus.Update(tokens, status);
        MessageBox.Show("Status updated successfuly");
        return true;
    }
    catch (TwitterizerException te)
    {
        MessageBox.Show(te.Message);
        return false;
    }
} 

This method takes a string variable and posts it as a tweet to twitter.

C#
public List<string> getMessages()
{
    List<string> temp = new List<string>();
    var receivedMessages = TwitterDirectMessage.DirectMessages(tokens);
    foreach (var v in receivedMessages.ResponseObject)
    {
        temp.Add(v.Recipient.ScreenName + " >> " + v.Text);
    }

    return temp;
}  

The above method gets all received messages of all users and then stores it to a string list.

Points of Interest 

If you want to integrate twitter in your app, then TwitterStuff and Browser class from this project will help you. 

Important Note

This project is created in VS2012 and maybe not open in previous versions. 

Twitterizer library is used to connect to twitter. Available at https://github.com/Twitterizer/Twitterizer

It is my first article so please...!

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer
United Kingdom United Kingdom
After development in PHP, now coming back to .Net world with love for front-end libs and my new love Silverlight..

Comments and Discussions

 
QuestionDoesn't work cannot tweet or retrieve message Pin
Abhisinha1712-Sep-15 0:26
Abhisinha1712-Sep-15 0:26 
Questionquestion Pin
Member 1027006116-May-14 5:05
Member 1027006116-May-14 5:05 
QuestionDoesn't work Pin
Member 104301272-Dec-13 13:03
Member 104301272-Dec-13 13:03 
GeneralMy vote of 5 Pin
Gun Gun Febrianza3-Sep-13 8:40
Gun Gun Febrianza3-Sep-13 8:40 
GeneralMy vote of 4 Pin
hebsiboy29-Apr-13 2:17
hebsiboy29-Apr-13 2:17 
SuggestionNice package but... Pin
Simon Jackson29-Apr-13 1:56
Simon Jackson29-Apr-13 1:56 
Looks like a really nice and simple system.

Only reason I didn't give it a 5 is because I've seen a lot of apps now able to bypass the code entering page and just return direct to the app.
If the article could include that as well, that would make it awesome
GeneralRe: Nice package but... Pin
Raza_theraaz29-Apr-13 2:01
Raza_theraaz29-Apr-13 2:01 
GeneralMy vote of 5 Pin
npdev1328-Apr-13 22:01
npdev1328-Apr-13 22:01 
GeneralMy vote of 5 Pin
GregoryW28-Apr-13 19:31
GregoryW28-Apr-13 19:31 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.