Click here to Skip to main content
Click here to Skip to main content

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

, 28 Apr 2013 CPOL
Rate this:
Please Sign up or sign in to vote.
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

 

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 : 
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;
    }
}

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.

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.

public static string pin = "xxxxxxx";

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

public static OAuthTokens tokens;

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

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

Method to Update Status: 

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.

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)

Share

About the Author

raza.ahmed.se
Engineer
Pakistan Pakistan
I am a software engineering student and love to code in C#. I'm specially interested in Form Applications and WPF as well as java for Android
Follow on   Twitter

Comments and Discussions

 
Questionquestion PinmemberMember 1027006116-May-14 6:05 
QuestionDoesn't work PinmemberMember 104301272-Dec-13 14:03 
GeneralMy vote of 5 Pinmember Gun Gun Febrianza3-Sep-13 9:40 
GeneralMy vote of 4 Pinmemberhebsiboy29-Apr-13 3:17 
SuggestionNice package but... PinmemberSimon Jackson29-Apr-13 2: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... Pinmemberraza.ahmed.se29-Apr-13 3:01 
GeneralMy vote of 5 PinmemberTechnoGeek00128-Apr-13 23:01 
GeneralMy vote of 5 PinmemberGregoryW28-Apr-13 20:31 

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

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

| Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.1411023.1 | Last Updated 28 Apr 2013
Article Copyright 2013 by raza.ahmed.se
Everything else Copyright © CodeProject, 1999-2014
Layout: fixed | fluid