blog.dashpoint.com

Twitter Conversations : First Refactoring

clock December 20, 2008 04:47 by author Administrator

Thanks for the feedback and encouragement so far. This project has been fun and I hope you keep enjoying it so far.

Refactoring Required

I knew going in that the first cut of this application needed some serious refactoring. The project had dependencies on internet connections , numerous classes contained redundant code and the user interface was lacking. In this first set of refactorings I hope to demonstrate how you can design your applications to be more testable and how to make the code cleaner at the same time. I will also attempt to make the UI better with my feeble UI skills.

First Refactoring: Extracting Interfaces

The first cut of the Twitter Conversations application took a dependency on being connected to the Internet for testing. In order to remove this dependency I decided to extract the an interface from the Twitter.Communications.TwitterRequest class. This process is simple  when using a tool like ReSharper. I simply opened the class source code file, Right Clicked, Selected Refactor->Extract Interface from the popup menu. The following screen shows the Extract Interface dialog from ReSharper.

TwitterConversationRefactor

This process yielded the following interface

   1: Public interface ITwitterRequest
   2:     Function GetTwitterRequest(ByVal URL As String) As String
   3: end interface

After refactoring the interface from the Twitter.Communication.TwitterRequest class I created a new Twitter.Interfaces project. This project would all interfaces for this project including another new interface ITwitterCredentials. I created the ITwitterCredentials interface in order to provide a slightly cleaner design for creating instances of the TwitterRequest class.

   1: Public Interface ITwitterCredential
   2:     Property UserName() As String
   3:     Property Password() As String
   4: End Interface

Once I created the ITwitterCredentials interface I implemented it on a new class Twitter.Communication.TwitterCredentials. I also needed to refactor the guts of the TwitterRequest class. The new code for this class now looks like:

   1: Public Class TwitterRequest
   2:     Implements Twitter.Interfaces.ITwitterRequest
   3:     Private _Credentials As Twitter.Interfaces.ITwitterCredential
   4:  
   5:     Sub New(ByVal Credentials As Twitter.Interfaces.ITwitterCredential)
   6:         Me._Credentials = Credentials
   7:     End Sub
   8:  
   9:     Public Function GetTwitterRequest(ByVal URL As String) As String Implements Twitter.Interfaces.ITwitterRequest.GetTwitterRequest
  10:         Dim Credentials As New NetworkCredential(Me._Credentials.UserName, Me._Credentials.Password)
  11:  
  12:         Dim Request As HttpWebRequest = HttpWebRequest.Create(URL)
  13:         Request.Method = "POST"
  14:         Request.Credentials = Credentials
  15:  
  16:         Dim Response As WebResponse = Request.GetResponse
  17:         Dim Reader As New StreamReader(Response.GetResponseStream)
  18:         Dim Results As String = Reader.ReadToEnd
  19:         Return Results
  20:  
  21:     End Function
  22: End Class

After extracting these interfaces I changed the constructors for Twitter.API.User and Twitter.Message.API to receive an ITwitterRequest rather than a concrete class.The following code demonstrates the constructor for the Twitter.API.User class.

   1: Public Class User
   2:  
   3:     Dim Communicator As Twitter.Interfaces.ITwitterRequest = Nothing
   4:     Dim JsonSerializer As New System.Web.Script.Serialization.JavaScriptSerializer
   5:  
   6:     Sub New(ByVal TwitterCommunicator As Twitter.Interfaces.ITwitterRequest)
   7:         Me.Communicator = TwitterCommunicator
   8:     End Sub

Of course at this point all of our tests were broken but I waited to do a little more refactoring before fixing the tests.

Second Refactoring: Creating the Disconnected Twitter Service

The next step in the process was to create a disconnected version of Twitter. To accomplish this I took the following steps:

  1. Extracted JSON strings from the various calls to Twitter and put them into our testing project as embedded resource files.
  2. Added code to the testing project that could be used to extract the embedded text files
  3. Implemented the ITwitterRequest interface on a new class called TwitterRequestMock.
  4. Implemented the function GetTwitterRequest to return the appropriate text resource based on the URL.

The first item on the list was to extract the JSON data from actual calls to Twitter. To satisfy the unit tests I created three file extracts:

  • singleuser.txt  - Contains the information for my user account
  • friends.txt – A list of people I follow
  • messages.txt – A list of twitter updates

All three of these files were marked as Embedded Resource files in the Visual Studio project.

The next step was to add code that would allow these files to be extracted from the testing assembly. the following code extracts resources from the currently running assembly (i.e. our unit tests)

   1: Imports System.IO
   2: Imports System.Reflection
   3:  
   4: Public Class ObjectMother
   5:     Public Shared Function GetEmbeddedResource(ByVal ResourceName As String) As String
   6:         Dim ResStream As Stream = System.Reflection.Assembly.GetExecutingAssembly.GetManifestResourceStream(ResourceName)
   7:         Dim oStreamReader As New StreamReader(ResStream)
   8:         Dim RetVal As String = oStreamReader.ReadToEnd
   9:         Return RetVal
  10:     End Function
  11: End Class

Finally a new class TwitterRequestMock was created. The purpose of this class was to return the proper embedded resource files based on the URL passed to a request. The following code demonstrates the implementation of this:

   1: Public Class TwitterRequestMock
   2:     Implements Twitter.Interfaces.ITwitterRequest
   3:  
   4:     Private _Credentials As Twitter.Interfaces.ITwitterCredential
   5:  
   6:     Sub New(ByVal Credentials As Twitter.Interfaces.ITwitterCredential)
   7:         Me._Credentials = Credentials
   8:     End Sub
   9:  
  10:     Public Function GetTwitterRequest(ByVal URL As String) As String Implements Interfaces.ITwitterRequest.GetTwitterRequest
  11:         Dim ReturnValue As String = ""
  12:  
  13:         '-- urls we use so far
  14:         'Const UserMessageURL As String = "http://twitter.com/statuses/user_timeline/<<USERID>>.json"
  15:         'Const MyMessagesURL As String = "http://twitter.com/statuses/friends_timeline.json?count=200"
  16:         'Const FriendsURL As String = "http://twitter.com/statuses/friends.json"
  17:         'Const GetUserURL As String = "http://twitter.com/users/show/<<USERID>>.json"
  18:         'Const CredentialURL As String = "http://twitter.com/account/verify_credentials.json"
  19:  
  20:         If URL.Contains("verify_credentials") OrElse URL.Contains("users/show/") Then
  21:             ReturnValue = ObjectMother.GetEmbeddedResource("Twitter.UnitTests.singleuser.txt")
  22:         ElseIf URL.Contains("friends_timeline") OrElse URL.Contains("user_timeline") Then
  23:             ReturnValue = ObjectMother.GetEmbeddedResource("Twitter.UnitTests.messages.txt")
  24:         ElseIf URL.Contains("friends.json") Then
  25:             ReturnValue = ObjectMother.GetEmbeddedResource("Twitter.UnitTests.friends.txt")
  26:         End If
  27:  
  28:         Return ReturnValue
  29:     End Function
  30: End Class

I discussed this method with Jeremy Miller and his comment was if possible the text for the JSON strings should be embedded into the unit test if at all possible. I didn’t follow this recommendation because the JSON returns strings are long and very ugly. What are your thoughts on this ?

Third Refactoring: Fixing the Unit Tests

Once this class was implemented I went in and fixed up the unit tests. This was actually pretty simple. Basically I refactored the constructor and <Setup()> of the UnitTests class.

   1: <TestFixture()> _
   2: Public Class UnitTests
   3:  
   4:     Dim UserAPI As Twitter.API.User = Nothing
   5:     Dim MessageAPI As Twitter.API.Message = Nothing
   6:     Dim Communicator As Twitter.Interfaces.ITwitterRequest = Nothing
   7:  
   8:     <SetUp()> _
   9:     Sub Setup()
  10:         Me.Communicator = New TwitterRequestMock(New Twitter.Communication.TwitterCredentials)
  11:  
  12:         Me.UserAPI = New Twitter.API.User(Me.Communicator)
  13:         Me.MessageAPI = New Twitter.API.Message(Me.Communicator)
  14:     End Sub

 

Now the tests for this application can be run in a disconnected mode.

Fourth Refactoring: Removing Redundant Code

The next step in this refactoring process was to clean up redundant code from the Twitter.API.User and Twitter.API.Message classes. In the first version each method was responsible for parsing data and creating collections of Messages and Users. The code started like the following snippet:

   1: Function GetUserMessages(ByVal UserID As String) As Twitter.Domain.Message()
   2:     Dim ReturnMessages As New List(Of Twitter.Domain.Message)
   3:  
   4:     Dim UserObjects As Object = JsonSerializer.DeserializeObject(Me.Communicator.GetTwitterRequest(UserMessageURL.Replace("<<USERID>>", UserID)))
   5:  
   6:     For Each UserObject As Object In CType(UserObjects, Array)
   7:         ReturnMessages.Add(New Twitter.Domain.Message With { _
   8:                            .MessageID = UserObject("id"), _
   9:                            .MessageDate = UserObject("created_at"), _
  10:                            .MessageContent = UserObject("text"), _
  11:                            .UserID = UserObject("user")("id"), _
  12:                            .UserName = UserObject("user")("name"), _
  13:                            .ImageURL = UserObject("user")("profile_image_url")})
  14:     Next
  15:     Return ReturnMessages.ToArray
  16:  
  17: End Function

The redundant code is the code contained in the For loop. I decided to extract this code into its own method.

   1: Sub PopulateMessages(ByVal ListToPopulate As List(Of Twitter.Domain.Message), ByVal Contents As Object)
   2:         For Each UserObject As Object In CType(Contents, Array)
   3:             ListToPopulate.Add(New Twitter.Domain.Message With { _
   4:                                .MessageID = UserObject("id"), _
   5:                                .MessageDate = UserObject("created_at"), _
   6:                                .MessageContent = UserObject("text"), _
   7:                                .UserID = UserObject("user")("id"), _
   8:                                .UserName = UserObject("user")("name"), _
   9:                                .ImageURL = UserObject("user")("profile_image_url")})
  10:  
  11:         Next
  12:     End Sub

Now the code for parsing off message looks like this:

   1: Function GetUserMessages(ByVal UserID As String) As Twitter.Domain.Message()
   2:     Dim ReturnMessages As New List(Of Twitter.Domain.Message)
   3:     Dim UserObjects As Object = JsonSerializer.DeserializeObject(Me.Communicator.GetTwitterRequest(UserMessageURL.Replace("<<USERID>>", UserID)))
   4:     Me.PopulateMessages(ReturnMessages, UserObjects)
   5:     Return ReturnMessages.ToArray
   6: End Function

The Twitter.API.User Class is had a slightly different refactoring. Because this API returns a lot of single user information it was necessary to create a function to return a single user object. When a method returned multiople user records a looping structure similar to the one for messages was used.

   1: Public Function GetUsers() As Twitter.Domain.User()
   2:     Dim Users As New List(Of Twitter.Domain.User)
   3:     Dim UserObjects As Object = JsonSerializer.DeserializeObject(Me.Communicator.GetTwitterRequest(FriendsURL))
   4:     Me.PopulateUsers(Users, UserObjects)
   5:     Return Users.ToArray
   6: End Function
   7:  
   8: Public Function GetUser(ByVal id As String) As Twitter.Domain.User
   9:     Dim Users As New List(Of Twitter.Domain.User)
  10:     Dim UserObject As Object = JsonSerializer.DeserializeObject(Me.Communicator.GetTwitterRequest(GetUserURL.Replace("<<USERID>>", id.ToString)))
  11:     Return Me.GetUserFromObject(UserObject)
  12: End Function
  13: Public Function GetMyUser() As Twitter.Domain.User
  14:     Dim UserObject As Object = JsonSerializer.DeserializeObject(Me.Communicator.GetTwitterRequest(CredentialURL))
  15:     Return Me.GetUserFromObject(UserObject)
  16: End Function
  17: Function GetUserFromObject(ByVal UserObject As Object) As Twitter.Domain.User
  18:     Return New Twitter.Domain.User With { _
  19:       .UserID = UserObject("id"), _
  20:       .UserName = UserObject("name"), _
  21:       .ScreenName = UserObject("screen_name"), _
  22:       .ImageURL = UserObject("profile_image_url"), _
  23:       .Followers = UserObject("followers_count")}
  24: End Function
  25: Sub PopulateUsers(ByVal ListToPopulate As List(Of Twitter.Domain.User), ByVal Contents As Object)
  26:     For Each UserObject As Object In CType(Contents, Array)
  27:         ListToPopulate.Add(Me.GetUserFromObject(UserObject))
  28:     Next
  29: End Sub

The nice thing about these refactoring is that when a new property is added to a domain object you only need to change the code in one place.

Fourth Refactoring: The WPF Interface

The final refactoring I added was to implement a slightly improved interface.  This basically consisted of changing the code that calls the Twitter API’s we write and adding three user interface elements. The elements added to the screen consisted of two fields for capturing username and password respectively and a new display element for the showing the Twitter users image. The VB code and XAML code now looks like this:

   1: Private Sub cmdGetThread_Click(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles cmdGetThread.Click
   2:     Dim Communicator As Twitter.Interfaces.ITwitterRequest = New Twitter.Communication.TwitterRequest(New Twitter.Communication.TwitterCredentials With {.UserName = Me.txtUserName.Text, .Password = Me.txtPassword.Password})
   3:     Me.lstResults.ItemsSource = Me.LoadConversation(New Twitter.API.Message(Communicator), New Twitter.API.User(Communicator), Me.txtCriteria.Text)
   4: End Sub
   5:  
   6:  
   7: Function LoadConversation(ByVal MessageAPI As Twitter.API.Message, ByVal UserAPI As Twitter.API.User, ByVal TextCriteria As String) As Twitter.Domain.Message()
   8:  
   9:     '-- create list of users from comma (,) delimited list of names in text box
  10:     '-- TODO we should scrub this
  11:     Dim UserQuery As New List(Of Twitter.Domain.User)
  12:     For Each UserName As String In TextCriteria.Split(",")
  13:         UserQuery.Add(UserAPI.GetUser(UserName))
  14:     Next
  15:  
  16:     '-- get messages for these users 
  17:     Dim messages As Twitter.Domain.Message() = MessageAPI.GetMultipleUserMessages(UserQuery.ToArray())
  18:  
  19:     '-- filter messages based on who is in the contents
  20:     Dim FilteredMessages = _
  21:        From Message _
  22:          In messages _
  23:      Where MatchesCriteria(Message.MessageContent, Me.txtCriteria.Text.Split(",")) _
  24:      Order By Message.MessageDate Descending
  25:  
  26:     Return FilteredMessages.ToArray
  27:  
  28:  
  29: End Function
   1: <Grid x:Name="LayoutRoot">
   2:         <StackPanel >
   3:             <StackPanel Width="Auto"  Orientation="Horizontal">
   4:                 <TextBlock Text="User Name" Height="22" Width="80"/>
   5:                 <TextBox Text="" TextWrapping="Wrap" x:Name="txtUserName" Width="151" Height="27"/>
   6:                 <TextBlock Text="Password" Height="22" Width="67.957"/>
   7:                 <PasswordBox  x:Name="txtPassword" Width="143" Height="27"/>
   8:             </StackPanel>
   9:                         
  10:             <StackPanel Width="Auto"  Orientation="Horizontal">
  11:             <TextBlock Text="Screen Names" Height="22" Width="80"/>
  12:             <TextBox Text="rodpaddock,bellware" TextWrapping="Wrap" x:Name="txtCriteria" Width="500" Height="22"/>
  13:             <Button Content="Get Thread" x:Name="cmdGetThread"/>
  14:             </StackPanel>
  15:             <StackPanel>
  16:                 <ScrollViewer Width="Auto" Height="600">
  17:                 <ListBox Width="Auto" Height="600" IsSynchronizedWithCurrentItem="True" x:Name="lstResults"    >
  18:                     <ListBox.ItemTemplate>
  19:                         <DataTemplate>
  20:                             <StackPanel Orientation="Horizontal" >
  21:                                 <Image Height="100" Width="100" Source="{Binding Path=ImageURL}"/>
  22:                                     <StackPanel>
  23:                                         <TextBlock Text="{Binding Path=MessageContent}"/>
  24:                                         <TextBlock Text="{Binding Path=MessageDate}"/>
  25:                                         <TextBlock Text="{Binding Path=UserName}"/>
  26:                                         <TextBlock Text="----------"/>
  27:                                     </StackPanel>
  28:  
  29:                             </StackPanel>
  30:                             
  31:                         </DataTemplate>
  32:                     </ListBox.ItemTemplate>
  33:             
  34:                 </ListBox>
  35:             </ScrollViewer>
  36:             </StackPanel>
  37:         </StackPanel>
  38:     </Grid>

One item to notice is that all of the code for calling the Twitter API is no longer embedded in the Click() event of the Search button. It has been extracted into its own method and no longer relies on user interface elements. This refactoring was done with integration testing in mind. In a later installment we will be looking at testing the user interface along with just the API calls.

Now the user interface looks like:

TwitterConversationWindowRefactor

Google Code

The source code for this project can now be found on Google Code  The URL for this project is:

http://twitterplayground.googlecode.com/svn/trunk/twitterplayground-read-only

More Coming

I hope you have enjoyed these posts so far.  Lets take a look at the list from the last post and strike out some tasks that were accomplished in this post:

1. Introduce a Dependency Injection container. For this application I want to use StructureMap.
2. Introduce more mocking to remove dependencies on Twitter (maybe we can write a Twitter mock layer)
3. Further refine the design of the libraries. There’s still redundant code left we can remove.
4. Improve the UI and create some alternate UI’s with MVC  or maybe Silverlight
5. Open up the code to contributions from other developers.

We accomplished quite a bit in this post. Is all of the code done? Not by any stretch. I plan on revisiting all of the items on the list in every refactoring (rinse-lather-repeat)… I will also add new items to the list, like:

  1. Adding Proxy code to the communications class.
  2. Adding error handling to the communications class.
  3. Creating some mechanism for preserving credentials and other settings

RE #5: I did put it in Google code and would be happy to have other contributors. I would especially appreciate help with the UI. 

NOTE: One of the cool things about this process so far is the confidence I have in changes I make to the code. Having a repeatable set of tests is invaluable.

Thanks
Rodman



Twitter Conversations an Agile Case Study

clock December 12, 2008 04:33 by author Administrator

Twitter Conversations

From time to time Twitter Users engage in conversations. It is a royal pain to follow these conversations using the native Twitter programs including the web version of Twitter.  As an exercise I began creating an application that would allow me to follow Twitter conversations. This is the story of creating that application.

User Story
     As a Twitter user I want to be able to follow conversations between other Twitter users.

This post will accomplish two things.
1. Fulfill the requirements of the user story.
2. Create a small application that can be used by the ALT.NET/Agile/Lean community to learn numerous agile software development concepts including:  test driven development, dependency injection, how good design affects testing, etc.

Note: The second item in the list came from conversations at KaizenConf (www.kaizenconf.com  kaizenconf.pbwiki.com). These conversations centered on the need to create a learning application. I am submitting this application as a case study so that we all may learn from it.
To accomplish the story we need the following parts:

1. A mechanism for communicating with Twitter.
2. Query Twitter UserID’s based on list of screen names.
3. Query messages for each user in list of screen names.
4. Filter messages where the message content contains any of the names in the list of screen names.
The first step is to define a domain model. The following domain model represents the different elements that will help in fulfilling the requirements of the user story.

• User
    o UserID(int)
    o ScreenName(string)
    o UserName (string)
    o Followers (int)
• Message
    o MessageID(int)
    o MessageDate(string)
    o MessageContent(string)
    o UserID (int)
    o UserName(string)

Unit Tests (Part 1)
After creating the domain model began creating unit tests for my API. I decided to divide my API into two subject areas: Users and Messages. The User API is used to query Twitter User information. The Message API is used to query Twitter Status(s) aka messages. The following code is the first set of unit tests.

<TestFixture()> _
Public Class UnitTests

  <Test()> _
  Sub Should_Return_My_Following()
    Dim UserAPI As New Twitter.API.User
    Assert.That(UserAPI.GetUsers().count > 0)
  End Sub

  <Test()> _
  Sub Should_Return_Single_User()
    Dim UserAPI As New Twitter.API.User
    Assert.That(UserAPI.GetUser(UserAPI.GetMyUser().UserID.ToString).ScreenName _
       = "rodpaddock")
    End Sub

  <Test()> _
  Sub Should_Return_Single_User_ByName()
      Dim UserAPI As New Twitter.API.User
      Assert.That(UserAPI.GetUser("rodpaddock").ScreenName = "rodpaddock")
  End Sub

  <Test()> _
  Sub Should_Return_My_User()
      Dim UserAPI As New Twitter.API.User
      Dim User As Twitter.Domain.User = UserAPI.GetMyUser
      Assert.That(UserAPI.GetMyUser().ScreenName = "rodpaddock")
  End Sub

  <Test()> _
  Sub Should_Return_My_Messages()
      Dim MessageAPI As New Twitter.API.Message
      Assert.That(MessageAPI.GetMyMessages().Count > 0)
  End Sub

  <Test()> _
  Sub Should_Return_Messages_By_User()
      Dim MessageAPI As New Twitter.API.Message
      Assert.That(MessageAPI.GetUserMessages("rodpaddock").Count > 0)
  End Sub

  <Test()> _
  Sub Should_Return_Messages_From_MultipleUsers()
      Dim MessageAPI As New Twitter.API.Message
      Dim UserAPI As New Twitter.API.User
      Dim UserQuery As New List(Of Twitter.Domain.User)
      UserQuery.Add(UserAPI.GetUser("rodpaddock"))
      UserQuery.Add(UserAPI.GetUser("chriswilliams"))
      Assert.That(MessageAPI.GetMultipleUserMessages(UserQuery.ToArray).Count > 0)
  End Sub
End Class

This set of unit tests does a good job of covering our API’s and insuring they all work as planned. But the tests do have a number of design flaws. For now we’ll leave them alone and look at some of the code they are testing.

Twitter Basics

Now that you have looked at the domain model and the unit tests, take a look at the process of fulfilling these unit tests. For this exercise consider the following unit test.

<Test()> _
Sub Should_Return_Single_User_ByName()
   Dim UserAPI As New Twitter.API.User
   Assert.That(UserAPI.GetUser("rodpaddock").ScreenName = "rodpaddock")
End Sub

To fulfill the requirements of this test the following things must occur:
1. Application must connect to Twitter
2. Application must retrieve user data based on the passed in username
3. The data returned must be transformed into a usable User domain object.

The following code fulfills the requirements of this test:

Const GetUserURL As String = "http://twitter.com/users/show/<<USERID>>.json"
Public Function GetUser(ByVal id As String) As Twitter.Domain.User

    Dim Credentials As New NetworkCredential("<<YourUserName>>", "<<YourPassword>>")
    Dim Request As HttpWebRequest = _
        HttpWebRequest.Create(GetUserURL.Replace("<<USERID>>", id.ToString))
    Request.Method = "GET"
    Request.Credentials = Credentials

    Dim Response As WebResponse = Request.GetResponse
    Dim Reader As New StreamReader(Response.GetResponseStream)
    Dim Results As String = Reader.ReadToEnd

    Dim JsonSerializer As New System.Web.Script.Serialization.JavaScriptSerializer
    Dim UserObject As Object = JsonSerializer.DeserializeObject(Results)

    Return New Twitter.Domain.User With { _
       .UserID = UserObject("id"), _
       .UserName = UserObject("name"), _
       .ScreenName = UserObject("screen_name"), _
       .Followers = UserObject("followers_count")}

    End Function

This code performs the following tasks:
1. Created a  NetworkCredentials object with your Twitter user name and password. All twitter requests use basic authentication.
      Dim Credentials As New NetworkCredential("<<YourUserName>>", "<<YourPassword>>")
2. Created an HttpWebRequest based on Twitter’s REST API. This call will return data in JSON format as specified via the .json extension on the URL.
     Dim Request As HttpWebRequest = _
      HttpWebRequest.Create(GetUserURL.Replace("<<USERID>>", id.ToString))
      Request.Method = "GET"
      Request.Credentials = Credentials

3. Read data from the web request stream using a Stream Reader.
       Const GetUserURL As String = "http://twitter.com/users/show/<<USERID>>.json"
       Dim Response As WebResponse = Request.GetResponse
       Dim Reader As New StreamReader(Response.GetResponseStream)
       Dim Results As String = Reader.ReadToEnd

4. Deserialize the JSON data into an array of Name/Value pair data using the .Net JSON serializer.
       Dim JsonSerializer As New System.Web.Script.Serialization.JavaScriptSerializer
       Dim UserObject As Object = JsonSerializer.DeserializeObject(Results)
5. Turn the returned user information into a User domain object
       Return New Twitter.Domain.User With { _
         .UserID = UserObject("id"), _
         .UserName = UserObject("name"), _
         .ScreenName = UserObject("screen_name"), _
         .Followers = UserObject("followers_count")}
 
That’s pretty much how all communication works with Twitter. If you closely examine the code you will find a number of design flaws. Basically this code was developed as a spike: “Let’s see how we can pull data from Twitter”. The basic pattern: authenticate, request and parse was cut and pasted into each API call. I did this knowing that that the code (and tests) would be refactored into a proper design.

Refactoring the Code

After completing the first run through the code (getting it working) it was time to refactor. I gave myself some of goals:
1. Reduce the amount of redundant code.
2. Create a better designed set of test code (remove redundancy)
3. Prepare the code for dependency injection (current tests require internet connections)

The “authenticate and request” process received the first refactoring. This process can be pseudo coded as follows:

Given a valid set of user credentials and a REST URL return a string result.

From this pseudo code we created a Twitter communication class.

Imports System.Web
Imports System.Net
Imports System.IO

Public Class TwitterRequest
    Private UserName As String = ""
    Private Password As String = ""
    Sub New(ByVal UserName As String, ByVal Password As String)
        Me.UserName = UserName
        Me.Password = Password
    End Sub

    Function GetTwitterRequest(ByVal URL As String) As String
        Dim Credentials As New NetworkCredential(Me.UserName, Me.Password)

        Dim Request As HttpWebRequest = HttpWebRequest.Create(URL)
        Request.Method = "POST"
        Request.Credentials = Credentials

        Dim Response As WebResponse = Request.GetResponse
        Dim Reader As New StreamReader(Response.GetResponseStream)
        Dim Results As String = Reader.ReadToEnd
        Return Results

    End Function
End Class

Now we have a wrapped class that needs two items in its constructor (UserName , Password) and has a single method GetTwitterRequest(URL). The GetTwitterRequest(URL)’s job is to return a JSON string that will be used by the subsequent API call.

All of the code necessary for  communicating with Twitter is encapsulated into this class.

Next step was to refactor the User and Message API’s.  The first step involved creating a constructor that accepted a TwitterRequest object. The constructor for the Message API changed to: 

 Dim Communicator As Twitter.Communication.TwitterRequest = Nothing
 Dim JsonSerializer As New System.Web.Script.Serialization.JavaScriptSerializer

  Sub New(ByVal TwitterCommunicator As Twitter.Communication.TwitterRequest)
      Me.Communicator = TwitterCommunicator
  End Sub

These two refactorings reduced the code radically. The following code shows the new GetUser() method.


Public Function GetUser(ByVal id As String) As Twitter.Domain.User
 Dim UserObject As Object = JsonSerializer.DeserializeObject(_
   Me.Communicator.GetTwitterRequest(GetUserURL.Replace("<<USERID>>", id.ToString)))

   Return New Twitter.Domain.User With { _
      .UserID = UserObject("id"), _
      .UserName = UserObject("name"), _
      .ScreenName = UserObject("screen_name"), _
      .Followers = UserObject("followers_count")}

End Function

The code went from 10 lines of code to 2.  The same results were seen across the entire API. 
Refactoring Tests
Once the API’s were refactored  the tests were then refactored. The following code shows the new set of tests.

Imports NUnit.Core
Imports NUnit.Framework

<TestFixture()> _
Public Class UnitTests
    Dim UserAPI As Twitter.API.User = Nothing
    Dim MessageAPI As Twitter.API.Message = Nothing
    Dim Communicator As New Twitter.Communication.TwitterRequest("", "”)

    <SetUp()> _
    Sub Setup()
        Me.UserAPI = New Twitter.API.User(Me.Communicator)
        Me.MessageAPI = New Twitter.API.Message(Me.Communicator)
    End Sub

    <Test()> _
    Sub Should_Return_My_Following()
        Assert.That(UserAPI.GetUsers().Count > 0)
    End Sub

    <Test()> _
    Sub Should_Return_Single_User()
     Assert.That(UserAPI.GetUser(UserAPI.GetMyUser().UserID.ToString).ScreenName _
        = "rodpaddock")
    End Sub

    <Test()> _
    Sub Should_Return_Single_User_ByName()
        Assert.That(UserAPI.GetUser("rodpaddock").ScreenName = "rodpaddock")
    End Sub

    <Test()> _
    Sub Should_Return_My_User()
        Assert.That(UserAPI.GetMyUser().ScreenName = "rodpaddock")
    End Sub

    <Test()> _
    Sub Should_Return_My_Messages()
        Assert.That(MessageAPI.GetMyMessages().Count > 0)
    End Sub

    <Test()> _
    Sub Should_Return_Messages_By_User()
        Assert.That(MessageAPI.GetUserMessages("rodpaddock").Count > 0)
    End Sub

    <Test()> _
    Sub Should_Return_Messages_From_MultipleUsers()
        Dim UserQuery As New List(Of Twitter.Domain.User)
        UserQuery.Add(UserAPI.GetUser("rodpaddock"))
        UserQuery.Add(UserAPI.GetUser("chriswilliams"))
        Assert.That(MessageAPI.GetMultipleUserMessages(UserQuery.ToArray).Count > 0)
    End Sub
End Class

As you can see the testing class now has member variables for each API class and the <Setup()> section instantiates the APIs with the injected communication class.

User Interface

Finally a small WPF application was built to track conversations between users. The following code creates instances of the User and Message APIs, creates an array of user objects from a string (split by commas), retrieves messages for the specified users and finally queries them using LINQ to ferret out a conversation. This code is as follows:
Partial Public Class Main

    Dim UserAPI As Twitter.API.User = Nothing
    Dim MessageAPI As Twitter.API.Message = Nothing
    Dim Communicator As New Twitter.Communication.TwitterRequest("", "")

    Public Sub New()
        MyBase.New()

        Me.InitializeComponent()

        ' Insert code required on object creation below this point.
        ' Add any initialization after the InitializeComponent() call.
        Me.UserAPI = New Twitter.API.User(Me.Communicator)
        Me.MessageAPI = New Twitter.API.Message(Me.Communicator)
    End Sub

 

Private Sub cmdGetThread_Click(ByVal sender As Object, _
   ByVal e As System.Windows.RoutedEventArgs) Handles cmdGetThread.Click

        '-- create list of users from comma (,) delimited list of names in text box
        '-- TODO we should scrub this
        Dim UserQuery As New List(Of Twitter.Domain.User)
        For Each UserName As String In Me.txtCriteria.Text.Split(",")
            UserQuery.Add(UserAPI.GetUser(UserName))
        Next

        '-- get messages for these users
        Dim messages As Twitter.Domain.Message() = _
           MessageAPI.GetMultipleUserMessages(UserQuery.ToArray())

        '-- filter messages based on who is in the contents
        Dim FilteredMessages = _
           From Message _
             In messages _
         Where MatchesCriteria(Message.MessageContent, Me.txtCriteria.Text.Split(","))
        Order By Message.MessageDate Descending


        Me.lstResults.ItemsSource = FilteredMessages.ToArray
    End Sub


    Function MatchesCriteria(ByVal Content As String, _
         ByVal SearchCriteria As String()) As Boolean
        Dim llRetVal As Boolean = False
        For Each SearchString In SearchCriteria
            If Content.ToLower.Contains(SearchString) Then
                llRetVal = True
                Exit For
            End If
        Next
        Return llRetVal
    End Function

Lastly the information is displayed using the following XAML code:


<Window
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
x:Class="Main"
x:Name="Window"
Title="Main"
 xmlns:Custom="http://schemas.microsoft.com/wpf/2008/toolkit">

<Grid x:Name="LayoutRoot">
  <StackPanel Margin="0,0,0,37">
    <Button Content="Get Thread" x:Name="cmdGetThread"/>
   <TextBox Text="bellware,pandamonial,chadmyers" 
     TextWrapping="Wrap" x:Name="txtCriteria" Width="622.627"/>
    <ScrollViewer>
    <ListBox Width="Auto" Height="500"
      IsSynchronizedWithCurrentItem="True" x:Name="lstResults"    >
      <ListBox.ItemTemplate>
  <DataTemplate>
                <StackPanel>
                   <TextBlock Text="{Binding Path=MessageDate}"/>
                   <TextBlock Text="{Binding Path=UserName}"/>
                   <TextBlock Text="----------"/>
                </StackPanel>
  </DataTemplate>
 </ListBox.ItemTemplate>
 </ListBox>
</ScrollViewer>
</StackPanel>
</Grid>
</Window>

The following screen shot demonstrates a conversation that occurred today between three people I follow on Twitter:

Twitter Conversation Window 

Next Steps
There is more work to be done here. In the future posts I hope to do the following:

1. Introduce a Dependency Injection container. For this application I want to use StructureMap.
2. Introduce more mocking to remove dependencies on Twitter (maybe we can write a Twitter mock layer)
3. Further refine the design of the libraries. There’s still redundant code left we can remove.
4. Improve the UI and create some alternate UI’s with MVC  or maybe Silverlight
5. Open up the code to contributions from other developers.

Summary

What I hoped to accomplish in this post was a brief introduction to building a useful tool using the agile principles of Test Driven Development and Dependency Injection. Another goal of this post is to open a conversation on these agile principles. A lot of these practices may seem simple to a lot of the folks I blog with here but a lot of folks out there they seem foreign. I appreciate the comments.

The full code for this post can be found at www.dashpoint.com/downloads/TwitterPlayGround.Zip

Note: There are two sections where you will need to use your own username and password.

Thanks
Rodman

 



MSDN Canada Speaking Engagements and INETA

clock September 11, 2007 11:37 by author Administrator
 

I have a couple of speaking engagements coming up in British Columbia.

 

Tuesday October 9th, 2007

Vancouver BC

http://www.netbc.ca/DNCal/NetBcEvents.aspx

 Silverlight Adventures

At MIX 07 in Las Vegas Microsoft released a new web development platform known as Silverlight. This session will demonstrate a number of features of Silverlight.

Come prepared to learn: How to create a basic Silverlight application, how to control the Browser DOM with Silverlight, how to retrieve data into your Silverlight application using web services and finally how to send data to your web services from Silverlight. You should walk away from this session with a good understanding of the capabilities and limitations of Silverlight.

  

Wed October 10th, 2007

Victoria, BC

http://vicdotnet.org/Default.aspx

 Ajaxing Your Applications

Last Year Microsoft released a set of ASP.NET Ajax extensions. These extensions enable you to add Web 2.0 Style features to your ASP.NET Applications with little or no effort. In this session you will learn how to create new ASP.NET Ajax applications, how to incorporate Ajax into existing ASP.NET applications, what happens when you incorporate Ajax features into your web forms and overall how you can make your web forms smoother and more interactive. You will also learn how to incorporate the controls provided by the ASP.NET Ajax Control Toolkit.

 

November 26 to 30th

DevTeach

www.devteach.com

 INETA Bound

Also some good news… Last week I became an INETA speaker. I look forward to speaking at more user groups around the country and potentially the world. Thanks for all of those who helped make that happen.

 



Fiddler to the Rescue

clock September 3, 2007 17:58 by author Administrator

Fiddler to the Rescue

Last week I was working on a Sliverlight 1.1 article for the Visual Basic DevCenter (http://msdn2.microsoft.com/en-us/vbasic/default.aspx)  and ran into some problems making my Silverlight application communicate with a web service I included in my examples.

After some discussion with Rick Strahl (www.west-wind.com/weblog) he told me to use Fiddler to diagnose my problem. Fiddler is a free HTTP sniffer that can be found at http://www.fiddlertool.com/fiddler/

Fiddler is a tool that “sniffs” all HTTP traffic by inserting a proxy between the WinInet stack your web calls.  The proxy then outputs its results to a very cool windows application that will display your traffic real time. The following screen shows the output of the current version of fiddler.

Flddler 2.0 screen

 

After installing Fiddler it took me all of 5 minutes to see that I was not properly flushing a send buffer resulting in a bunch of “500” results calls. I added a single line of code and my code was working properly.

On item of note Fiddler will not trace calls made to 127.0.0.1 or localhost. If you are debugging local applications you will need to address them via your machine name.