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();
}
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; 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();
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;
}
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);
}
}
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;
}
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;
return true;
}
catch (Exception)
{
return false;
}
}
private bool AlreadyLoggedIn()
{
try
{
List<string> LoginInfo = myXML.readFromXml();
TwitterStuff.screenName = LoginInfo[1];
if (!SetLocalTokens(LoginInfo[2], LoginInfo[3]))
return false;
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...!