Creating a Twitter Client in C#, Part 3

Posted by Matt | Filed under , , , ,

In previous articles, Creating a Twitter Client in C# and Creating a Twitter Client in C#, Part 2, I showed you the basics of creating a Twitter client using C# and WCF.  We also saw problems with the Xml data and so we switched to the Json data format.

Today, we’ll continue and add another method call.  This call is one of the fundamental methods used in a Twitter Client:  Friends Timeline.

The Friends Timeline returns back an array of data.  This adds a bit of extra complication to the method.  The return value is an array of status objects.  For this, we’ll need to create two new data structures:  Status and Statuses.

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

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

  [DataMember(Name = "user")]
  public User User { get; set; }
}

[CollectionDataContract(Name = "statuses", 
  ItemName = "status", Namespace = "")]
public class Statuses : List<Status>
{
}

The Status class is set up very similar to the User class that we created last time.  We have Id and Text fields which are present in the resulting Json data.  Also, we’re including our previous User class since some user data is returned as well.  You could create another class (for example, BasicUser) since not all of the information is included here as was in the VerifyCredentials call.

The Statuses class is a bit different.  Since it’s a list, we need to declare it as a CollectionDataContract instead of just a simple DataContract.  Also, we’re defining the type of items in the collection with the ItemName parameter.

Next, we need to add our new function to the interface.

public interface ITwitterClient
{
  [OperationContract(Name = "FriendsTimeline")]
  [WebGet(UriTemplate = "statuses/friends_timeline.json",
    BodyStyle = WebMessageBodyStyle.Bare,
    RequestFormat = WebMessageFormat.Json,
    ResponseFormat = WebMessageFormat.Json)]
  Statuses FriendsTimeline();
}

And to the client class.

public class TwitterClient
{
  public Statuses FriendsTimeline()
  {
    return base.Channel.FriendsTimeline();
  }
}

Now we can retrieve the timeline from the client.

User user = client.VerifyCredentials();
Statuses statuses = client.FriendsTimeline();

Creating a Twitter Client in C#, Part 2

Posted by Matt | Filed under , , , ,

In my previous article, Creating a Twitter Client in C#, I showed you the basics of creating a Twitter client using C# and WCF.

After doing some investigation, it turns out that for some reason, C# WCF does not want to correctly parse some of the Xml data returned. For example, if we add profile_image_url to the User class

class User
{
  [DataMember(Name = "profile_image_url")]
  public string ProfileImageUrl { get; set; }
}

and then call our VerifyCredentials method, the profile_image_url parameter always ends up null after it’s parsed from the Xml data.

However, if we switch from Xml to Json formatted data, these fields do correctly get parsed.  To do the switch, just change the following in our ITwitterClient interface

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

to

[OperationContract]
[WebGet(UriTemplate = "/account/verify_credentials.json",
  BodyStyle = WebMessageBodyStyle.Bare,
  RequestFormat = WebMessageFormat.Json,
  ResponseFormat = WebMessageFormat.Json)]
User VerifyCredentials();

Now it retrieves the data correctly.

From here on, we’ll be using the Json format instead of Xml for the client.

If anyone has any ideas on why it’s failing reading the Xml data, I’d be very interested in hearing them.

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.