Creating a Twitter Client in C#

Posted by Matt | Filed under , , , ,

Twitter seems to be the app-du-jour these days.  Twitter is today’s Facebook.  Everyone seems to be on Twitter these days:  Global News with Leslie Roberts, Ellen DeGeneres, Britney Spears, and even MC Hammer.

If you’re going to create a Twitter client application, there are many wrapper classes already created for Twitter using C# and other languages.  However, if you’re interested in creating your own Twitter client (as I was), it’s very easy using the C# Web Services client model.

1.  Bookmark and refer to the Twitter API

The Twitter API reference can be found here.  Bookmark it and refer to it when adding your function calls.  This will be invaluable as you add methods to your client.

2.  Add a Twitter section to your app.config file

Add the following section to your app.config file. 

<system.serviceModel>
  <bindings>
    <webHttpBinding>
      <binding name="TwitterHttpBinding">
        <security mode="TransportCredentialOnly">
          <transport clientCredentialType="Basic" />
        </security>
      </binding>
    </webHttpBinding>
  </bindings>
  <behaviors>
    <endpointBehaviors>
      <behavior name="WebHttp">
        <webHttp />
      </behavior>
    </endpointBehaviors>
  </behaviors>
  <client>
    <endpoint
      address="http://www.twitter.com"
      binding="webHttpBinding"
      bindingConfiguration="TwitterHttpBinding"
      behaviorConfiguration="WebHttp"
      contract="TwitterClient1.ITwitterClient" />
  </client>
</system.serviceModel>

This will define the Web Service client for use with Twitter.  You may need to modify the contract= value to match your application.

3.  Add necessary references

Add references to the following namespaces in your project:

  • System.Runtime.Serialization
  • System.ServiceModel
  • System.ServiceModel.Web

4.  Create a Twitter interface

Create a new interface for your Twitter client.  To start, it can be as simple as a single command:

[ServiceContract]
public interface ITwitterClient
{
  [OperationContract]
  [WebGet(UriTemplate = "/account/verify_credentials.xml",
    BodyStyle = WebMessageBodyStyle.Bare,
    RequestFormat = WebMessageFormat.Xml,
    ResponseFormat = WebMessageFormat.Xml)]
  User VerifyCredentials();
}

Here, we’re defining a call to the verify credentials command, and we’re using the Xml versions of the functions.  The ServiceContract attribute tells the compiler that the interface is for a web service client.  The UriTemplate parameter is the URL to the command relative to twitter.com (defined in the app.config file).  The OperationContract attribute tells the compiler that the function is for a web service function call.  The WebGet attribute tells the compiler that the function uses the standard http Get method for accessing the interface.

You’ll notice the use of a class called “User”.  That will be described in the next section.

5.  Create additional classes

In section 4, we used a class called “User”.  The verify credentials Twitter command returns data like the following:

<user>
  <id>12345</id>
  <name>Matt</name>
  <screen_name>Matt</screen_name>
  <!-- More Data -->
</user>

For this, we can take advantage of C# Xml automatic deserialization.  As I mentioned before, this is one of my favourite features of C#.  In this case, I created a class called “User”:

[DataContract(Name = "user", Namespace = "")]
public class User
{
  [DataMember(Name = "id")]
  public int Id { get; set; }

  [DataMember(Name = "name")]
  public string Name { get; set; }

  [DataMember(Name = "screen_name")]
  public string ScreenName { get; set; }
}

You’ll notice a correspondence between the members of my class and the contents of the Xml response.  C# will automatically deserialize the retrieved data into available classes where possible.

6.  Create your client class

Now you need to create your client class.  For this, we derive a class from ClientBase<> and our Twitter interface and then implement the functions required for the interface.  For each function, we can just call the same function on the channel.

public class TwitterClient : 
  ClientBase<ITwitterClient>, 
  ITwitterClient
{
  #region ITwitterClient Members

  public User VerifyCredentials()
  {
    return base.Channel.VerifyCredentials();
  }

  #endregion
}

The last thing we need to do is setup authentication against Twitter. 

7.  Authenticate your client class

Twitter allows for basic web http authentication.  We’ve already setup the client endpoint for this in our app.config file.  Now, we need to fill in the username and password.  This is easy in a constructor to our client:

public class TwitterClient
{
  public TwitterClient(string sUsername, string sPassword)
  {
    /*this.*/ClientCredentials.UserName.UserName = sUsername;
    /*this.*/ClientCredentials.UserName.Password = sPassword;
  }
}

8.  Use your class

Now you can use the client in your application:

TwitterClient client = new TwitterClient("login", "password");
User user = client.VerifyCredentials();

Now all you need to do is to add the other methods that you require from Twitter.

Comments are closed