You are on page 1of 28

C# Lab: Write a Simple Twitter Client Using the Twitter API

Jennifer Lewis

Notes for Instructors:


You can use this as a project or lab assignment. If you are going to use this as a project assignment, I suggest that you enhance the original lab assignment by doing one or a few of the following things: Make the application more graphically appealing. Add more user-friendly functionality, such as keeping track of the number of characters entered by the user. Refactor the code by moving the calls to the API to a separate class. Refactor the code for more flexibility, such as move the URLs to the settings file, and change to code to get the URLs from the settings file.

Notes for Students:


If you are going to use this as a project for your programming class, you may want to enhance the original lab assignment by doing one or a few of the following things: Make the application more graphically appealing. Add more user-friendly functionality, such as keeping track of the number of characters entered by the user. Refactor the code by moving the calls to the API to a separate class. Refactor the code for more flexibility, such as move the URLs to the settings file, and change to code to get the URLs from the settings file. If you are going to use this as a project assignment, you should also have a strong understanding of how this works. You should read the Twitter API documentation (mentioned in the lab) as well as understand how the .NET classes used in this lab assignment works.

C# Lab: Write a Simple Twitter Client Using the Twitter API Page 3

Skill Level
Students who are performing this lab should have an intermediate level knowledge of C#, as well as a basic level knowledge of HTTP.

Overview
Twitter (http://www.twitter.com) is one of the fastestgrowing Internet applications being used by everyone from technical experts to celebrities. Twitter is a way for people to send updates via the web, a mobile phone, or an application on a PC or Mac.
Link to documentation about the Twitter APIs: http://apiwiki.twitter.com/TwitterAPI-Documentation

Twitter also has a set of APIs that allow developers to create their own client applications to interface with Twitter. A developer can write a simple application that will send Twitter messages, or a developer can write a more elaborate dashboard application that not only will allow people to send messages, but it will also allow them to manage their profile, who is following them and who they are following. This lab is going to demonstrate how to use the Twitter APIs to write a simple client that allows a person to send Twitter messages. In this lab, we will have the user log in to Twitter. After logging in, the user can then send a message through the application.

The Twitter APIs and the C# Libraries


The two Twitter APIs that will be used in this demonstration are: statuses/update account/verify_credentials The statuses/update API is the API that sends messages to Twitter. The account/verify_credentials API checks whether the user ID and password are valid, and if so, it returns all the profile information about the user, including: description followers count following count last message added The three C# libraries that will be used in the project are: System.Net System.IO System.Xml The System.Net library contains the classes that we need to make a call to the APIs. The class that we will be using to call the APIs is HttpWebRequest. The System.IO library contains the classes that we need to capture the responses from the APIs. We will be using the Stream class to capture the responses. The System.Xml library contains the classes that we need to allow us to convert the responses to XML so we can navigate through the responses, since the responses are actually in XML format.

What You Need


In order to perform this lab, you will need the following: The .NET SDK (2.0 or higher) or a .NET IDE, such as Visual Studio o This lab will be using Visual Studio 2005 for the illustrations. If you are not using Visual Studio 2005, please adjust the directions accordingly to your environment. Access to the Internet A Twitter account to use for practicing

Date Written: 9/7/2009

C# Lab: Write a Simple Twitter Client Using the Twitter API Page 4

If you do not have a Twitter account, go to http://www.twitter.com and sign up for a free account.

Special Notes
This lab is a simple example for demonstration purposes only. o It will not contain any elaborate user interface designs. o While the code may be used as-is, you may want to refactor for your environment or purposes.

Instructions
What we are going to do is have a simple design where we have two panels on our form: a login panel and a message panel. When one panel is visible, the other panel is invisible. The following two sketches below are a blueprint that can be used to illustrate what should be in the panels.
Figure 1: A sketch of the log in screen

What we need for this panel: 1 panel 2 text boxes (1 for ID, 1 for password)

3 buttons (one for log in, one for clear, one for close app) 1 label for the status message

Figure 2: A sketch of the send message screen

What we need for this panel: 1 panel

1 text box (for the message) 3 buttons (one for send message, one for clear, one for log out) 1 label for the status message

Date Written: 9/7/2009

C# Lab: Write a Simple Twitter Client Using the Twitter API Page 5

To keep this simple, the lab will demonstrate the log in part first. Then, it will demonstrate how to send the message.

Part 1: Logging Into Twitter


1. Create a new C# Windows Application. Call the project TwitterClientLab. 2. Change the following properties on the form: frmMain (Name) Twitter Client Text 398, 227 Size 3. Add a panel to the form. Drag the panel to the top-left corner of the form.

4. Change the following properties on the panel: (Name) Size pnlLogin 369,164

5. Add the following components to the panel and change the following properties of the respective component. Use the Figure 1 sketch in this lab as a guide on where the components should go. Label lblMessage (Name) Font 12 Size True Bold ForeColor Blue (or another color of your choice) Please log in to Text Twitter Label (name)

lblID

Date Written: 9/7/2009

C# Lab: Write a Simple Twitter Client Using the Twitter API Page 6

Text Textbox (name) Label (name) Text Textbox (Name) PasswordChar Button (Name) Text Size Button (Name) Text Size Button (Name) Text Size Your form should look similar to this.

User ID

txtID

lblPasswd Password

txtPasswd *

btnLogin Log In 105, 23

btnClear Clear Screen 105, 23

btnClose Close Application 105, 23

Date Written: 9/7/2009

C# Lab: Write a Simple Twitter Client Using the Twitter API Page 7

Now we are ready to code! We are going to start by coding the events for the Close Application and the Clear Screen buttons. 1. If you are working in an IDE, go to the Code view.
In Visual Studio: right-click on the form in the Solution Explorer and select View Code.

Coding Shortcut 2. The first button that we will code for is the If you are working in an IDE, you can easily Clear Screen (btnClear) button. When the user get to the code window by double-clicking on clicks on this button, the application should clear any of the buttons on your form. This will the contents of the ID (txtID) and password automatically add the code block for the event that you have to code. (txtPasswd) fields, and then put the cursor back on the ID (txtID) field so the user can try again. Add the following code within the public partial class Form1 : Form code block: private void btnClear_Click(object sender, EventArgs e) { // Clear the information in the ID and Password fields txtID.Text = ""; txtPasswd.Text = ""; // Reset the message lblMessage.Text = "Please log in to Twitter"; // Put the focus back on the ID txtID.Focus(); }

3. The next button that we will code for is the Close Application (btnClose) button. When the user clicks on this button, the application should close. Add the following code within the public partial class Form1 : Form code block:
private void btnClose_Click(object sender, EventArgs e) { // Closes the application this.Close(); }

4. Save your work. At this stage, your code should look similar to this:
using using using using using using using System; System.Collections.Generic; System.ComponentModel; System.Data; System.Drawing; System.Text; System.Windows.Forms;

namespace TwitterClientLab { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void btnClear_Click(object sender, EventArgs e) { // Clear the information in the ID and Password fields txtID.Text = ""; txtPasswd.Text = "";

Date Written: 9/7/2009

C# Lab: Write a Simple Twitter Client Using the Twitter API Page 8

// Reset the message lblMessage.Text = "Please log in to Twitter"; // Put the focus back on the ID txtID.Focus(); } private void btnClose_Click(object sender, EventArgs e) { // Closes the application this.Close(); } } }

Before you continue, it is a good idea to save your code and run your application to test the code.
Now we are ready to add the logic to call the Twitter API to validate the ID and password. This is the pseudocode for how the log in process should work: If user id is blank Display a message indicating that ID is required Put cursor on user ID Dont continue If password is blank Display a message indicating that password is required Put cursor on password Dont continue Call the Twitter API to validate the ID and password Analyze the response If the results contain an error If the error contains the word Unauthorized Display an Invalid ID/Password message Else if the error contains the word Service Unavailable Display a too many people tweeting message Else Display the message text Else Get the Name from the results Hide the login panel Display the message panel You should still be in the code view if you are working in an IDE. 5. At the top of the code, add the following lines:
using System.Net; using System.IO; using System.Xml;

6. Add the following code within the public partial class Form1 : Form code block:
private void btnLogin_Click(object sender, EventArgs e) { }

Date Written: 9/7/2009

C# Lab: Write a Simple Twitter Client Using the Twitter API Page 9

7. The first thing that we will do is add the validation logic (making sure that the user entered an ID and password). Add the following code within the private void btnLogin_Click(object sender, EventArgs e) code block:
// the trim function makes sure that all extraneous spaces are // cleared before checking to see if a user entered a value if (txtID.Text.Trim().Length == 0) { lblMessage.Text = "Please enter a User ID"; txtID.Focus(); return; // this exits from the function } if (txtPasswd.Text.Trim().Length == 0) { lblMessage.Text = "Please enter a Password"; txtPasswd.Focus(); return; // this exits from the function }

Your code should look similar to this:


using using using using using using using using using using System; System.Collections.Generic; System.ComponentModel; System.Data; System.Drawing; System.Text; System.Windows.Forms; System.Net; System.IO; System.Xml;

namespace TwitterClientLab { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void btnClear_Click(object sender, EventArgs e) { // Clear the information in the ID and Password fields txtID.Text = ""; txtPasswd.Text = ""; // Reset the message lblMessage.Text = "Please log in to Twitter"; // Put the focus back on the ID txtID.Focus(); } private void btnClose_Click(object sender, EventArgs e) { // Closes the application this.Close(); } private void btnLogin_Click(object sender, EventArgs e) { // the trim function makes sure that all extraneous spaces are // cleared before checking to see if a user entered a value if (txtID.Text.Trim().Length == 0) { lblMessage.Text = "Please enter a User ID"; txtID.Focus(); return; // this exits from the function

Date Written: 9/7/2009

C# Lab: Write a Simple Twitter Client Using the Twitter API Page 10

} if (txtPasswd.Text.Trim().Length == 0) { lblMessage.Text = "Please enter a Password"; txtPasswd.Focus(); return; // this exits from the function }

} } }

Before you continue, it is a good idea to save your code and run your application to test the code.
8. Now we are going to set up the code to call the API. Add the following code within the private void btnLogin_Click(object sender, EventArgs e) code block and after the closing block of the if (txtPasswd.Text.Trim().Length == 0) block:
/* * Call the API to make sure that the ID and password are valid in Twitter. * You should put this is a try-catch loop since errors returned from the API * will trigger an exception in the application. */ try { String personName = ""; // Set up the variables to get the information back StringBuilder sb = new StringBuilder(); byte[] buf = new byte[8192]; // encode the username/password string user = Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(txtID.Text + ":" + txtPasswd.Text)); // connect with the verify page HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://twitter.com/account/verify_credentials.xml"); // set the method to GET - this API expects a GET method call request.Method = "GET"; // set the authorization levels request.Headers.Add("Authorization", "Basic " + user); request.ContentType = "application/x-www-form-urlencoded"; // set the response from the GET command HttpWebResponse response = (HttpWebResponse)request.GetResponse(); Stream resStream = response.GetResponseStream(); // Collect the information returned from the GET call string tempStream = null; int count = 0; do { count = resStream.Read(buf, 0, buf.Length); if (count != 0) { tempStream = Encoding.ASCII.GetString(buf, 0, count); sb.Append(tempStream); }

Date Written: 9/7/2009

C# Lab: Write a Simple Twitter Client Using the Twitter API Page 11

} while (count > 0); // Convert the results to XML XmlDocument doc = new XmlDocument(); doc.LoadXml(sb.ToString()); // Go through the XML to get the name of the person XmlNodeList nodeList = doc.SelectNodes("/user/name"); foreach (XmlNode node in nodeList) { personName = node.InnerText; } lblMessage.Text = "Welcome, " + personName + "!"; } catch (Exception ex) { // Check the message to find out which error to display if (ex.Message.Contains("Unauthorized")) { lblMessage.Text = "Invalid User ID and/or Password."; } else if (ex.Message.Contains("Service Unavailable")) { lblMessage.Text = "Too many people tweeting. Try again later."; } else { lblMessage.Text = ex.Message; } }

Your code should now look like this:


using using using using using using using using using using System; System.Collections.Generic; System.ComponentModel; System.Data; System.Drawing; System.Text; System.Windows.Forms; System.Net; System.IO; System.Xml;

namespace TwitterClientLab { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void btnClear_Click(object sender, EventArgs e) { // Clear the information in the ID and Password fields txtID.Text = ""; txtPasswd.Text = ""; // Reset the message lblMessage.Text = "Please log in to Twitter"; // Put the focus back on the ID txtID.Focus(); } private void btnClose_Click(object sender, EventArgs e) {

Date Written: 9/7/2009

C# Lab: Write a Simple Twitter Client Using the Twitter API Page 12

// Closes the application this.Close(); } private void btnLogin_Click(object sender, EventArgs e) { // the trim function makes sure that all extraneous spaces are // cleared before checking to see if a user entered a value if (txtID.Text.Trim().Length == 0) { lblMessage.Text = "Please enter a User ID"; txtID.Focus(); return; // this exits from the function } if (txtPasswd.Text.Trim().Length == 0) { lblMessage.Text = "Please enter a Password"; txtPasswd.Focus(); return; // this exits from the function } /* * Call the API to make sure that the ID and password are valid in Twitter. * You should put this is a try-catch loop since errors returned from the API * will trigger an exception in the application. */ try { String personName = ""; // Set up the variables to get the information back StringBuilder sb = new StringBuilder(); byte[] buf = new byte[8192]; // encode the username/password string user = Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(txtID.Text + ":" + txtPasswd.Text)); // connect with the verify page HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://twitter.com/account/verify_credentials.xml"); // set the method to GET - this API expects a GET method call request.Method = "GET"; // set the authorization levels request.Headers.Add("Authorization", "Basic " + user); request.ContentType = "application/x-www-form-urlencoded"; // set the response from the GET command HttpWebResponse response = (HttpWebResponse)request.GetResponse(); Stream resStream = response.GetResponseStream(); // Collect the information returned from the GET call string tempStream = null; int count = 0; do { count = resStream.Read(buf, 0, buf.Length); if (count != 0) { tempStream = Encoding.ASCII.GetString(buf, 0, count); sb.Append(tempStream); } } while (count > 0);

Date Written: 9/7/2009

C# Lab: Write a Simple Twitter Client Using the Twitter API Page 13

// Convert the results to XML XmlDocument doc = new XmlDocument(); doc.LoadXml(sb.ToString()); // Go through the XML to get the name of the person XmlNodeList nodeList = doc.SelectNodes("/user/name"); foreach (XmlNode node in nodeList) { personName = node.InnerText; } lblMessage.Text = "Welcome, " + personName + "!"; } catch (Exception ex) { // Check the message to find out which error to display if (ex.Message.Contains("Unauthorized")) { lblMessage.Text = "Invalid User ID and/or Password."; } else if (ex.Message.Contains("Service Unavailable")) { lblMessage.Text = "Too many people tweeting. Try again later."; } else { lblMessage.Text = ex.Message; } } } } }

9. Save and test your code. Test by entering an invalid user ID and password combination. Then, test with a valid user ID and password combination.
Example: Testing with an invalid user ID and password

Example: Testing with a valid user ID and password

Date Written: 9/7/2009

C# Lab: Write a Simple Twitter Client Using the Twitter API Page 14

Date Written: 9/7/2009

C# Lab: Write a Simple Twitter Client Using the Twitter API Page 15

Part 2: Posting a Message to Twitter


Remember from our pseudocode that if we have a successful login, the program is supposed to do the following: Hide the login panel Display the message panel In this part, we are going to code for posting a message to Twitter. 1. If you are working in an IDE, return to design view. 2. For easier coding, expand the size of the form by clicking on the lower right hand corner of the form and dragging until your desired size.

Before you begin, note the location of the top left corner of pnlLogin. The value of the Location property should be 12, 12. You will need this value a little bit later. 3. Add a panel to the form.

Date Written: 9/7/2009

C# Lab: Write a Simple Twitter Client Using the Twitter API Page 16

4. Change the following properties on the panel: (Name) Size Visible pnlMessage 369,164 False

5. Add the following components to the panel and change the following properties of the respective component. Use the Figure 2 sketch in this lab as a guide on where the components should go. Label lblMessage2 (Name) Font 12 Size True Bold Blue (or another ForeColor color of your choice) Enter your message Text (140 characters max)

Textbox (Name) MaxLength Multiline Size Button (Name) Size

txtTweet 140 True 329, 37

btnSend 105, 23

Date Written: 9/7/2009

C# Lab: Write a Simple Twitter Client Using the Twitter API Page 17

Text

Send Message

Button (Name) Size Text

btnClearTweet 105, 23 Clear Tweet

Button (Name) Size Text

btnLogout 105, 23 Log Out

6. If you are working in an IDE, return to code view. 7. Add the following code within the private void btnLogin_Click(object sender, EventArgs e) code block:
private void Form1_Load(object sender, EventArgs e) { // Set the size of the form at load this.Size = new System.Drawing.Size(398, 227); }

8. Add the following code within the private void btnLogin_Click(object sender, EventArgs e) code block after the lblMessage.Text = "Welcome, " + personName + "!"; statement:
// hide the login panel and show the message panel. Also change // the location of the message panel. pnlLogin.Visible = false; pnlMessage.Location = new System.Drawing.Point(12, 12); pnlMessage.Visible = true; // Put the cursor on the tweet box txtTweet.Focus();

Your code should look like this:


using using using using using using using using using using System; System.Collections.Generic; System.ComponentModel; System.Data; System.Drawing; System.Text; System.Windows.Forms; System.Net; System.IO; System.Xml;

namespace TwitterClientLab { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void btnClear_Click(object sender, EventArgs e) { // Clear the information in the ID and Password fields txtID.Text = ""; txtPasswd.Text = ""; // Reset the message

Date Written: 9/7/2009

C# Lab: Write a Simple Twitter Client Using the Twitter API Page 18

lblMessage.Text = "Please log in to Twitter"; // Put the focus back on the ID txtID.Focus(); } private void btnClose_Click(object sender, EventArgs e) { // Closes the application this.Close(); } private void btnLogin_Click(object sender, EventArgs e) { // the trim function makes sure that all extraneous spaces are // cleared before checking to see if a user entered a value if (txtID.Text.Trim().Length == 0) { lblMessage.Text = "Please enter a User ID"; txtID.Focus(); return; // this exits from the function } if (txtPasswd.Text.Trim().Length == 0) { lblMessage.Text = "Please enter a Password"; txtPasswd.Focus(); return; // this exits from the function } /* * Call the API to make sure that the ID and password are valid in Twitter. * You should put this is a try-catch loop since errors returned from the API * will trigger an exception in the application. */ try { String personName = ""; // Set up the variables to get the information back StringBuilder sb = new StringBuilder(); byte[] buf = new byte[8192]; // encode the username/password string user = Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(txtID.Text + ":" + txtPasswd.Text)); // connect with the verify page HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://twitter.com/account/verify_credentials.xml"); // set the method to GET - this API expects a GET method call request.Method = "GET"; // set the authorization levels request.Headers.Add("Authorization", "Basic " + user); request.ContentType = "application/x-www-form-urlencoded"; // set the response from the GET command HttpWebResponse response = (HttpWebResponse)request.GetResponse(); Stream resStream = response.GetResponseStream(); // Collect the information returned from the GET call string tempStream = null; int count = 0; do { count = resStream.Read(buf, 0, buf.Length);

Date Written: 9/7/2009

C# Lab: Write a Simple Twitter Client Using the Twitter API Page 19

if (count != 0) { tempStream = Encoding.ASCII.GetString(buf, 0, count); sb.Append(tempStream); } } while (count > 0); // Convert the results to XML XmlDocument doc = new XmlDocument(); doc.LoadXml(sb.ToString()); // Go through the XML to get the name of the person XmlNodeList nodeList = doc.SelectNodes("/user/name"); foreach (XmlNode node in nodeList) { personName = node.InnerText; } lblMessage.Text = "Welcome, " + personName + "!"; // hide the login panel and show the message panel. Also change // the location of the message panel. pnlLogin.Visible = false; pnlMessage.Location = new System.Drawing.Point(12, 12); pnlMessage.Visible = true; // Put the cursor on the tweet box txtTweet.Focus(); } catch (Exception ex) { // Check the message to find out which error to display if (ex.Message.Contains("Unauthorized")) { lblMessage.Text = "Invalid User ID and/or Password."; } else if (ex.Message.Contains("Service Unavailable")) { lblMessage.Text = "Too many people tweeting. Try again later."; } else { lblMessage.Text = ex.Message; } } } private void Form1_Load(object sender, EventArgs e) { // Set the size of the form at load this.Size = new System.Drawing.Size(398, 227); } } }

Before you continue, it is a good idea to save your code and run your application to test the code.
We are going to start by coding the events for the Log Out (btnLogout) and the Clear Tweet (btnClearTweet) buttons.

Date Written: 9/7/2009

C# Lab: Write a Simple Twitter Client Using the Twitter API Page 20

9. Add the following code within the public partial class Form1 : Form code block:
private void btnClearTweet_Click(object sender, EventArgs e) { txtTweet.Text = ""; txtTweet.Focus(); }

10. Add the following code within the public partial class Form1 : Form code block:
private void btnLogout_Click(object sender, EventArgs e) { // Close the message panel pnlMessage.Visible = false; pnlLogin.Visible = true; lblStatus.Text = "Please Log In to Twitter"; }

Your code should look like this:


using using using using using using using using using using System; System.Collections.Generic; System.ComponentModel; System.Data; System.Drawing; System.Text; System.Windows.Forms; System.Net; System.IO; System.Xml;

namespace TwitterClientLab { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void btnClear_Click(object sender, EventArgs e) { // Clear the information in the ID and Password fields txtID.Text = ""; txtPasswd.Text = ""; // Reset the message lblMessage.Text = "Please log in to Twitter"; // Put the focus back on the ID txtID.Focus(); } private void btnClose_Click(object sender, EventArgs e) { // Closes the application this.Close(); } private void btnLogin_Click(object sender, EventArgs e) { // the trim function makes sure that all extraneous spaces are // cleared before checking to see if a user entered a value if (txtID.Text.Trim().Length == 0) { lblMessage.Text = "Please enter a User ID"; txtID.Focus(); return; // this exits from the function }

Date Written: 9/7/2009

C# Lab: Write a Simple Twitter Client Using the Twitter API Page 21

if (txtPasswd.Text.Trim().Length == 0) { lblMessage.Text = "Please enter a Password"; txtPasswd.Focus(); return; // this exits from the function } /* * Call the API to make sure that the ID and password are valid in Twitter. * You should put this is a try-catch loop since errors returned from the API * will trigger an exception in the application. */ try { String personName = ""; // Set up the variables to get the information back StringBuilder sb = new StringBuilder(); byte[] buf = new byte[8192]; // encode the username/password string user = Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(txtID.Text + ":" + txtPasswd.Text)); // connect with the verify page HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://twitter.com/account/verify_credentials.xml"); // set the method to GET - this API expects a GET method call request.Method = "GET"; // set the authorization levels request.Headers.Add("Authorization", "Basic " + user); request.ContentType = "application/x-www-form-urlencoded"; // set the response from the GET command HttpWebResponse response = (HttpWebResponse)request.GetResponse(); Stream resStream = response.GetResponseStream(); // Collect the information returned from the GET call string tempStream = null; int count = 0; do { count = resStream.Read(buf, 0, buf.Length); if (count != 0) { tempStream = Encoding.ASCII.GetString(buf, 0, count); sb.Append(tempStream); } } while (count > 0); // Convert the results to XML XmlDocument doc = new XmlDocument(); doc.LoadXml(sb.ToString()); // Go through the XML to get the name of the person XmlNodeList nodeList = doc.SelectNodes("/user/name"); foreach (XmlNode node in nodeList) { personName = node.InnerText; } lblMessage.Text = "Welcome, " + personName + "!";

Date Written: 9/7/2009

C# Lab: Write a Simple Twitter Client Using the Twitter API Page 22

// hide the login panel and show the message panel. Also change // the location of the message panel. pnlLogin.Visible = false; pnlMessage.Location = new System.Drawing.Point(12, 12); pnlMessage.Visible = true; // Put the cursor on the tweet box txtTweet.Focus(); } catch (Exception ex) { // Check the message to find out which error to display if (ex.Message.Contains("Unauthorized")) { lblMessage.Text = "Invalid User ID and/or Password."; } else if (ex.Message.Contains("Service Unavailable")) { lblMessage.Text = "Too many people tweeting. Try again later."; } else { lblMessage.Text = ex.Message; } } } private void Form1_Load(object sender, EventArgs e) { // Set the size of the form at load this.Size = new System.Drawing.Size(398, 227); } private void btnClearTweet_Click(object sender, EventArgs e) { txtTweet.Text = ""; txtTweet.Focus(); } private void btnLogout_Click(object sender, EventArgs e) { // Close the message panel pnlMessage.Visible = false; pnlLogin.Visible = true; lblMessage.Text = "Please Log In to Twitter"; } } }

We are now going to write the code to send the message. 11. Add the following code within the public partial class Form1 : Form code block:
private void btnSend_Click(object sender, EventArgs e) { try { // encode the username/password string user = Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(txtID.Text + ":" + txtPasswd.Text)); // determine what we want to upload as a status byte[] bytes = System.Text.Encoding.ASCII.GetBytes("status=" + txtTweet.Text); // connect with the update page

Date Written: 9/7/2009

C# Lab: Write a Simple Twitter Client Using the Twitter API Page 23

HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://twitter.com/statuses/update.xml"); // set the method to POST request.Method = "POST"; request.ServicePoint.Expect100Continue = false; // thanks to argodev for this recent change! // set the authorisation levels request.Headers.Add("Authorization", "Basic " + user); request.ContentType = "application/x-www-form-urlencoded"; // set the length of the content request.ContentLength = bytes.Length; // set up the stream Stream reqStream = request.GetRequestStream(); // write to the stream reqStream.Write(bytes, 0, bytes.Length); // close the stream reqStream.Close(); // Set up the status message lblMessage2.Text = "Tweet Sent. txtTweet.Text = ""; txtTweet.Focus();

Enter another tweet or log out.";

} catch (Exception ex) { // Display the error in the status lblMessage2.Text = "The following error has occurred:" + ex.Message; } } }

Finally, save and test the code.


Figure: Testing the Code Initial Log-In Screen

Figure: Testing the Code Logging in to Twitter

Date Written: 9/7/2009

C# Lab: Write a Simple Twitter Client Using the Twitter API Page 24

Figure: Testing the Code Sending the Message

Date Written: 9/7/2009

C# Lab: Write a Simple Twitter Client Using the Twitter API Page 25

Appendix: The Source Code (Code-Behind)


using using using using using using using using using using System; System.Collections.Generic; System.ComponentModel; System.Data; System.Drawing; System.Text; System.Windows.Forms; System.Net; System.IO; System.Xml;

namespace TwitterClientLab { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void btnClear_Click(object sender, EventArgs e) { // Clear the information in the ID and Password fields txtID.Text = ""; txtPasswd.Text = ""; // Reset the message lblMessage.Text = "Please log in to Twitter"; // Put the focus back on the ID txtID.Focus(); } private void btnClose_Click(object sender, EventArgs e) { // Closes the application this.Close(); } private void btnLogin_Click(object sender, EventArgs e) { // the trim function makes sure that all extraneous spaces are // cleared before checking to see if a user entered a value if (txtID.Text.Trim().Length == 0) { lblMessage.Text = "Please enter a User ID"; txtID.Focus(); return; // this exits from the function } if (txtPasswd.Text.Trim().Length == 0) { lblMessage.Text = "Please enter a Password"; txtPasswd.Focus(); return; // this exits from the function } /* * Call the API to make sure that the ID and password are valid in Twitter. * You should put this is a try-catch loop since errors returned from the API * will trigger an exception in the application. */ try { String personName = ""; // Set up the variables to get the information back StringBuilder sb = new StringBuilder();

Date Written: 9/7/2009

C# Lab: Write a Simple Twitter Client Using the Twitter API Page 26

byte[] buf = new byte[8192]; // encode the username/password string user = Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(txtID.Text + ":" + txtPasswd.Text)); // connect with the verify page HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://twitter.com/account/verify_credentials.xml"); // set the method to GET - this API expects a GET method call request.Method = "GET"; // set the authorization levels request.Headers.Add("Authorization", "Basic " + user); request.ContentType = "application/x-www-form-urlencoded"; // set the response from the GET command HttpWebResponse response = (HttpWebResponse)request.GetResponse(); Stream resStream = response.GetResponseStream(); // Collect the information returned from the GET call string tempStream = null; int count = 0; do { count = resStream.Read(buf, 0, buf.Length); if (count != 0) { tempStream = Encoding.ASCII.GetString(buf, 0, count); sb.Append(tempStream); } } while (count > 0); // Convert the results to XML XmlDocument doc = new XmlDocument(); doc.LoadXml(sb.ToString()); // Go through the XML to get the name of the person XmlNodeList nodeList = doc.SelectNodes("/user/name"); foreach (XmlNode node in nodeList) { personName = node.InnerText; } lblMessage.Text = "Welcome, " + personName + "!"; // hide the login panel and show the message panel. Also change // the location of the message panel. pnlLogin.Visible = false; pnlMessage.Location = new System.Drawing.Point(12, 12); pnlMessage.Visible = true; // Put the cursor on the tweet box txtTweet.Focus(); } catch (Exception ex) { // Check the message to find out which error to display if (ex.Message.Contains("Unauthorized")) { lblMessage.Text = "Invalid User ID and/or Password."; } else if (ex.Message.Contains("Service Unavailable")) {

Date Written: 9/7/2009

C# Lab: Write a Simple Twitter Client Using the Twitter API Page 27

lblMessage.Text = "Too many people tweeting. Try again later."; } else { lblMessage.Text = ex.Message; } } } private void Form1_Load(object sender, EventArgs e) { // Set the size of the form at load this.Size = new System.Drawing.Size(398, 227); } private void btnClearTweet_Click(object sender, EventArgs e) { txtTweet.Text = ""; txtTweet.Focus(); } private void btnLogout_Click(object sender, EventArgs e) { // Close the message panel pnlMessage.Visible = false; pnlLogin.Visible = true; lblMessage.Text = "Please Log In to Twitter"; } private void btnSend_Click(object sender, EventArgs e) { try { // encode the username/password string user = Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(txtID.Text + ":" + txtPasswd.Text)); // determine what we want to upload as a status byte[] bytes = System.Text.Encoding.ASCII.GetBytes("status=" + txtTweet.Text); // connect with the update page HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://twitter.com/statuses/update.xml"); // set the method to POST request.Method = "POST"; request.ServicePoint.Expect100Continue = false; // thanks to argodev for this recent change! // set the authorisation levels request.Headers.Add("Authorization", "Basic " + user); request.ContentType = "application/x-www-form-urlencoded"; // set the length of the content request.ContentLength = bytes.Length; // set up the stream Stream reqStream = request.GetRequestStream(); // write to the stream reqStream.Write(bytes, 0, bytes.Length); // close the stream reqStream.Close(); // Set up the status message lblMessage2.Text = "Tweet Sent.

Enter another tweet or log out.";

Date Written: 9/7/2009

C# Lab: Write a Simple Twitter Client Using the Twitter API Page 28

txtTweet.Text = ""; txtTweet.Focus(); } catch (Exception ex) { // Display the error in the status lblMessage2.Text = "The following error has occurred:" + ex.Message; } } } }

Date Written: 9/7/2009

You might also like