Posts Tagged ‘C#’

.Net C# – Log in to Website Programmatically

28 Comments

In this tutorial, will show how to log into a website through code.  I am going to use Twitter in my example.

THIS IS FOR EDUCATIONAL PURPOSES ONLY.  I WOULD NOT ADVISE THE USE OF THIS TO ALWAYS LOG-IN TO TWITTER.

First, you will need to download and install Tamper Data.  It’s an add-on for Firefox that allows you to view and tamper with GET/POST web request data.  We won’t be doing any tampering.  We will be using it to view what POST parameters the page is expecting.

Next, navigate to the log in page for Twitter(http://twitter.com/login).  Once the page has loaded, go to Tools –> Tamper Data to open Tamper Data.  At the top of Tamper Data, click the Start Tamper button.  After clicking the button, click the “Sign In” button on Twitter’s log in page.  Once you hit the Sign In button, Tamper Data will prompt you with this popup….

Tamper Data Popup

Click “Tamper”.  You will then be presented with this window…

Tamper Data

If you notice on the right-hand side of the window, you will see the POST parameters.  These are:

authenticity_token
session[username_or_email]
session[password]
commit

Now that we have those, we can close the Tamper Data window, and close Firefox.

Now for the code.  The code is actually fairly simple.  We are just going to use the WebBrowser class to make the requests to the server to get the html source of the page.  This will give us the “authenticity_token” for us to use in the POST request.

string url = "https://twitter.com/login";
string username = "someUserName";
string password = "somePassword";
string commit = "Sign+In"; //this matches the data from Tamper Data

private void Login()
{
     WebBrowser b = new WebBrowser();
     b.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(b_DocumentCompleted);
     b.Navigate(url);
}

private void b_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
     WebBrowser b = sender as WebBrowser;
     string response = b.DocumentText;

     // looks in the page source to find the authenticity token.
     // could also use regular expressions here.
     int index = response.IndexOf("authenticity_token");
     int startIndex = index + 41;
     string authenticityToken = response.Substring(startIndex, 40);

     // unregisters the first event handler
     // adds a second event handler
     b.DocumentCompleted -= new WebBrowserDocumentCompletedEventHandler(b_DocumentCompleted);
     b.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(b_DocumentCompleted2);

     // format our data that we are going to post to the server
     // this will include our post parameters.  They do not need to be in a specific
     //    order, as long as they are concatenated together using an ampersand ( & )
     string postData = string.Format("authenticity_token={2}&session[username_or_email]={0}&session[password]={1}&commit={3}", username, password, authenticityToken, commit);

     ASCIIEncoding enc = new ASCIIEncoding();

     //  we are encoding the postData to a byte array
     b.Navigate("https://twitter.com/sessions", "", enc.GetBytes(postData), "Content-Type: application/x-www-form-urlencoded\r\n");
}

private void b_DocumentCompleted2(object sender, WebBrowserDocumentCompletedEventArgs e)
{
     WebBrowser b = sender as WebBrowser;
     string response = b.DocumentText;

     if (response.Contains("Sign out"))
     {
         MessageBox.Show("Login Successful");
     }
}

And that’s all you need to do.  You can now use the response variable to see the tweets that are in your timeline.

Tags: , , , ,

.Net C# – Twitter API For Desktop

10 Comments

I made a post almost 3 months ago about a .Net Twitter API that I had done.  Since then, I have made some modifications to the API.  I have added a couple of more features.  I also included various classes from the System.Web namespace so that I wouldn’t need a reference to that namespace.  This allows the API to be used on a mobile device with a very small footprint(the System.Web.dll file is 5MB in size, my .dll is 52KB).

I am missing a few features from my API.  Most notably the new “Retweet” functionality and the “Lists” functionality.  I am also missing some of the account methods.  Other than that, I believe I have most, if not all, of the other methods.

This API supports both Basic Auth and OAuth.  I would advise to use OAuth, since Twitter will be depreciating Basic Auth in June 2010.  To learn more about how OAuth works, check out my other blog post where I try to explain OAuth.

Remember that this API is for the Desktop OAuth only.  Feel free to download it and make changes to allow OAuth from a web application(yes, they are different “workflows”).   Basic Auth should work for both Desktop and Web applications.

I give credit to Shannon Whitley for his original OAuth code.  I made some modifications to it, but the base code of the OAuth is his.

Here is a code snippet on using the API for OAuth authorization.

// creats instance and sets Consumer and ConsumerSecret values
TwitEclipseAPI twit = new TwitEclipseAPI();
twit.OAuthConsumerKey = "yourConsumerKey";
twit.OAuthConsumerSecret = "yourConsumerSecret";

// makes request to get unauthorized request token
// The method will concatenate the request token to Twitter's Desktop OAuth
//    url (http://twitter.com/oauth/authorize)
string url = twit.OAuthGetUnauthorizedRequestToken();

// opens the user's default browser and browses to Twitter's OAuth page
Process.Start(url);

//  You will need to get the PIN from the user
//  I just created a popup and have the user enter the PIN
//       into a textbox in the popup
frmPinPopup popup = new frmPinPopup();
popup.ShowDialog();

string PIN = popup.PIN;
popup.Dispose();

// Gets the Token and TokenSecret that will be needed for all
//   subsequent requests.  You will need to save these values to keep
//   from forcing the user to authorize your application everytime they
//   open your application.
twit.OAuthRequestAccessToken(PIN);

// You can check for success by checking the OAuthAccessToken
//    and OAuthAccessTokenSecret values.  If they are populated, then
//    it was successful.  If they are empty, then it failed.
if (!string.IsNullOrEmpty(twit.OAuthAccessToken) && !string.IsNullOrEmpty(twit.OAuthAccessTokenSecret))
{
    MessageBox.Show("Authorization Successful");
}

Each method of the API will check the OAuthAccessToken and OAuthAccessTokenSecret values to determine whether it needs to do the request using OAuth or Basic Auth.

I have put the code on CodePlex.  It will contain both the .dll file, and the source code.  I felt it was easier to keep up with using CodePlex.

If you have code questions, you can post here.  However, if you are on Google Wave, you can go here.  If you would like Google Wave, I have about 20 invitations that I can send out.  Using Google Wave would be much better since we could exchange code using a code snippet tool.

Tags: , , , ,

.Net TwitEclipse – My Twitter Desktop Client

3 Comments

I have released a BETA version of my Twitter Desktop Client called TwitEclipse.  I have been writing a Twitter API library in .Net for a while now, and figured I might as well write a desktop client also.

The client uses .Net 3.5 SP1 and WPF.  It was a great learning experience to learn WPF since I had almost no previous experience with it.

If you want to download it and test it out, you can download it from here.  Remember that it is a BETA.  You could run into issues.  If you do, be sure to let me know so I can fix them.  I will also be adding additional features to the app once I get a chance.

I will be releasing my Twitter API library soon also.

Tags: , , , , ,