Professional Documents
Culture Documents
C Lab Write A Simple Twitter Client Using The Twitter API
C Lab Write A Simple Twitter Client Using The Twitter API
Jennifer Lewis
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.
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
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
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.
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
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 *
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 = "";
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) { }
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 }
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
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); }
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; } }
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) {
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);
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
C# Lab: Write a Simple Twitter Client Using the Twitter API Page 14
C# Lab: Write a Simple Twitter Client Using the Twitter API Page 15
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.
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)
btnSend 105, 23
C# Lab: Write a Simple Twitter Client Using the Twitter API Page 17
Text
Send Message
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();
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
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);
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.
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"; }
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 }
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 + "!";
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
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();
} catch (Exception ex) { // Display the error in the status lblMessage2.Text = "The following error has occurred:" + ex.Message; } } }
C# Lab: Write a Simple Twitter Client Using the Twitter API Page 24
C# Lab: Write a Simple Twitter Client Using the Twitter API Page 25
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();
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")) {
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.
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; } } } }