C# Simple Twitter Update

Posted by mroberts on Geeks with Blogs See other posts from Geeks with Blogs or by mroberts
Published on Mon, 22 Mar 2010 11:07:26 GMT Indexed on 2010/03/23 1:01 UTC
Read the original article Hit count: 452

Filed under:

For what it's worth a simple twitter update.

   1:  using System;
   2:  using System.IO;
   3:  using System.Net;
   4:  using System.Text;
   5:   
   6:  namespace Server.Actions
   7:  {
   8:      public class TwitterUpdate
   9:      {
  10:          public string Body { get; set; }
  11:          public string Login { get; set; }
  12:          public string Password { get; set; }
  13:   
  14:          public override void Execute()
  15:          {
  16:              try
  17:              {
  18:                  //encode user name and password 
  19:                  string creds = Convert.ToBase64String(Encoding.ASCII.GetBytes(string.Format("{0}:{1}", this.Login, this.Password)));
  20:   
  21:                  //encode tweet 
  22:                  byte[] tweet = Encoding.ASCII.GetBytes("status=" + this.Body);
  23:   
  24:                  //setup request 
  25:                  HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://twitter.com/statuses/update.xml");
  26:                  request.Method = "POST";
  27:                  request.ServicePoint.Expect100Continue = false;
  28:                  request.Headers.Add("Authorization", string.Format("Basic {0}", creds));
  29:                  request.ContentType = "application/x-www-form-urlencoded";
  30:                  request.ContentLength = tweet.Length;
  31:   
  32:                  //write to stream 
  33:                  Stream reqStream = request.GetRequestStream();
  34:                  reqStream.Write(tweet, 0, tweet.Length);
  35:                  reqStream.Close();
  36:   
  37:                  //check response 
  38:                  HttpWebResponse response = (HttpWebResponse)request.GetResponse();
  39:   
  40:                  //... 
  41:              }
  42:              catch (Exception e)
  43:              {
  44:                  //... 
  45:              }
  46:          }
  47:      }
  48:  }

 

BTW, this is my first blog post.  Nothing earth shattering, I admit, but I needed to figure out how to post formatted code.  In the past I’ve used Alex Gorbatchev’s Syntax Highlighter with great success, but here at GWB I couldn’t get it to work.

Windows Live Writer though, being a stand alone writer, worked with no problems.  For now, that’s what I’ll use.

© Geeks with Blogs or respective owner