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

19570670 C Lab Write a Simple Twitter Client Using the Twitter API

Embed Size (px)

Citation preview

Page 1: 19570670 C Lab Write a Simple Twitter Client Using the Twitter API

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

Jennifer Lewis

Page 2: 19570670 C Lab Write a Simple Twitter Client Using the Twitter API

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.

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

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

Date Written: 9/7/2009

Link to documentation about the Twitter APIs: http://apiwiki.twitter.com/Twitter-API-Documentation

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 fastest-growing 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. 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

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

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

Date Written: 9/7/2009

o 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

Figure 2: A sketch of the send message 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

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

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

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

Date Written: 9/7/2009

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:

(Name) frmMain Text Twitter Client Size 398, 227

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) pnlLogin Size 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 (Name) lblMessage Font Size Bold

12 True

ForeColor Blue (or another color of your choice)

Text Please log in to Twitter

Label (name) lblID

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

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

Date Written: 9/7/2009

Text User ID

Textbox (name) txtID

Label (name) lblPasswd Text Password

Textbox (Name) txtPasswd PasswordChar *

Button (Name) btnLogin Text Log In Size 105, 23

Button (Name) btnClear Text Clear Screen Size 105, 23

Button (Name) btnClose Text Close Application Size 105, 23

Your form should look similar to this.

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

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

Date Written: 9/7/2009

Coding Shortcut If you are working in an IDE, you can easily get to the code window by double-clicking on any of the buttons on your form. This will automatically add the code block for the event that you have to code.

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. 2. The first button that we will code for is the Clear Screen (btnClear) button. When the user clicks on this button, the application should clear the contents of the ID (txtID) and password (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 System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using 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 = "";

In Visual Studio: right-click on the form in the Solution Explorer and select View Code.

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

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

Date Written: 9/7/2009

// 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(); } } }

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 Don’t continue If password is blank Display a message indicating that password is required Put cursor on password Don’t 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)

{ }

Before you continue, it is a good idea to save your code and run your application to test the code.

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

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

Date Written: 9/7/2009

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 System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using System.Net; using System.IO; using 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

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

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

Date Written: 9/7/2009

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

}

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

Before you continue, it is a good idea to save your code and run your application to test the code.

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

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

Date Written: 9/7/2009

} 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 System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using System.Net; using System.IO; using 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) {

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

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

Date Written: 9/7/2009

// 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);

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

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

Date Written: 9/7/2009

// 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

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

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

Date Written: 9/7/2009

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

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

Date Written: 9/7/2009

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.

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

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

Date Written: 9/7/2009

4. Change the following properties on the panel:

(Name) pnlMessage Size 369,164 Visible 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 (Name) lblMessage2 Font Size Bold

12 True

ForeColor Blue (or another color of your choice)

Text Enter your message (140 characters max)

Textbox (Name) txtTweet MaxLength 140 Multiline True Size 329, 37

Button (Name) btnSend Size 105, 23

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

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

Date Written: 9/7/2009

Text Send Message

Button (Name) btnClearTweet Size 105, 23 Text Clear Tweet

Button (Name) btnLogout Size 105, 23 Text 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 System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using System.Net; using System.IO; using 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

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

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

Date Written: 9/7/2009

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);

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

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

Date Written: 9/7/2009

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

We are going to start by coding the events for the Log Out (btnLogout) and the Clear Tweet (btnClearTweet) buttons.

Before you continue, it is a good idea to save your code and run your application to test the code.

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

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

Date Written: 9/7/2009

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 System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using System.Net; using System.IO; using 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 }

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

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

Date Written: 9/7/2009

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 + "!";

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

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

Date Written: 9/7/2009

// 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

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

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

Date Written: 9/7/2009

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."; txtTweet.Text = ""; txtTweet.Focus(); } 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

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

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

Date Written: 9/7/2009

Figure: Testing the Code – Sending the Message

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

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

Date Written: 9/7/2009

Appendix: The Source Code (Code-Behind) using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using System.Net; using System.IO; using 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();

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

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

Date Written: 9/7/2009

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")) {

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

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

Date Written: 9/7/2009

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.";

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

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

Date Written: 9/7/2009

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