0 Replies - 11943 Views - Last Post: 15 July 2009 - 08:07 AM Rate Topic: -----

#1 eclipsed4utoo  Icon User is offline

  • Not Your Ordinary Programmer
  • member icon

Reputation: 1524
  • View blog
  • Posts: 5,957
  • Joined: 21-March 08

[C#] Twitter API: Get User Timeline

Posted 15 July 2009 - 08:07 AM

So I am currently writing a .Net library for the Twitter API, so I decided to post a tutorial on getting the User Timeline. This tutorial will include a custom UserStatus class and a custom User class. Combined, the two classes contains properties for all of the data that will be part of the XML files that Twitter sends. In some instances, not all of the properties will be used.

So if you wanted to start your own .Net library of the Twitter API, this could be a good place to start.

First, here is the custom UserStatus class.
public class UserStatus
{
    #region Private variables

    private DateTime m_statusCreatedAt;
    private Int64 m_statusID = 0;
    private string m_text = string.Empty;
    private string m_source = string.Empty;
    private bool m_truncated = false;
    private Int64 m_inReplyToStatusID = 0;
    private Int64 m_inReplyToUserID = 0;
    private bool m_favorited = false;
    private string m_inReplyToScreenName = string.Empty;
    private User m_user;

    #endregion

    #region Public Properties

    public User User
    {
        get { return m_user; }
        set { m_user = value; }
    }

    public DateTime StatusCreatedAt
    {
        get { return m_statusCreatedAt; }
        set { m_statusCreatedAt = value; }
    }

    public Int64 StatusID
    {
        get { return m_statusID; }
        set { m_statusID = value; }
    }

    public string Text
    {
        get { return m_text; }
        set { m_text = value; }
    }

    public string Source
    {
        get { return m_source; }
        set { m_source = value; }
    }

    public bool Truncated
    {
        get { return m_truncated; }
        set { m_truncated = value; }
    }

    public Int64 InReplyToStatusID
    {
        get { return m_inReplyToStatusID; }
        set { m_inReplyToStatusID = value; }
    }

    public Int64 InReplyToUserID
    {
        get { return m_inReplyToUserID; }
        set { m_inReplyToUserID = value; }
    }

    public bool Favorited
    {
        get { return m_favorited; }
        set { m_favorited = value; }
    }

    public string InReplyToScreenName
    {
        get { return m_inReplyToScreenName; }
        set { m_inReplyToScreenName = value; }
    }

    #endregion
}



Custom User class
public class User
{
    #region Private Variables
    private Int64 m_userID = 0;
    private string m_name = string.Empty;
    private Int64 m_friendsCount = 0;
    private DateTime m_createdAt;
    private Int64 m_favoritesCount = 0;
    private string m_UTCOffset = string.Empty;
    private string m_timeZone = string.Empty;
    private string m_profileBackgroundImageURL = string.Empty;
    private bool m_profileBackgroundTile = false;
    private Int64 m_statusesCount = 0;
    private bool m_notifications = false;
    private bool m_following = false;
    private bool m_protected = false;
    private Int64 m_followersCount = 0;
    private string m_profileBackgroundColor = string.Empty;
    private string m_profileTextColor = string.Empty;
    private string m_profileLinkColor = string.Empty;
    private string m_profileSidebarFillColor = string.Empty;
    private string m_profileSidebarBorderColor = string.Empty;
    private string m_screenName = string.Empty;
    private string m_location = string.Empty;
    private string m_description = string.Empty;
    private string m_profileImageURL = string.Empty;
    private string m_url = string.Empty;

    #endregion

    #region Public Properties

    public Int64 UserID
    {
        get { return m_userID; }
        set { m_userID = value; }
    }

    public string Name
    {
        get { return m_name; }
        set { m_name = value; }
    }
    
    public string ScreenName
    {
        get { return m_screenName; }
        set { m_screenName = value; }
    }
    
    public string Location
    {
        get { return m_location; }
        set { m_location = value; }
    }
   
    public string Description
    {
        get { return m_description; }
        set { m_description = value; }
    }
    
    public string ProfileImageURL
    {
        get { return m_profileImageURL; }
        set { m_profileImageURL = value; }
    }

    public string Url
    {
        get { return m_url; }
        set { m_url = value; }
    }
    
    public bool Protected
    {
        get { return m_protected; }
        set { m_protected = value; }
    }
    
    public Int64 FollowersCount
    {
        get { return m_followersCount; }
        set { m_followersCount = value; }
    }
    
    public string ProfileBackgroundColor
    {
        get { return m_profileBackgroundColor; }
        set { m_profileBackgroundColor = value; }
    }
    
    public string ProfileTextColor
    {
        get { return m_profileTextColor; }
        set { m_profileTextColor = value; }
    }
    
    public string ProfileLinkColor
    {
        get { return m_profileLinkColor; }
        set { m_profileLinkColor = value; }
    }
    
    public string ProfileSidebarFillColor
    {
        get { return m_profileSidebarFillColor; }
        set { m_profileSidebarFillColor = value; }
    }

    public string ProfileSidebarBorderColor
    {
        get { return m_profileSidebarBorderColor; }
        set { m_profileSidebarBorderColor = value; }
    }
    
    public Int64 FriendsCount
    {
        get { return m_friendsCount; }
        set { m_friendsCount = value; }
    }
    
    public DateTime CreatedAt
    {
        get { return m_createdAt; }
        set { m_createdAt = value; }
    }
    
    public Int64 FavoritesCount
    {
        get { return m_favoritesCount; }
        set { m_favoritesCount = value; }
    }
    
    public string UTCOffset
    {
        get { return m_UTCOffset; }
        set { m_UTCOffset = value; }
    }
    
    public string TimeZone
    {
        get { return m_timeZone; }
        set { m_timeZone = value; }
    }
    
    public string ProfileBackgroundImageURL
    {
        get { return m_profileBackgroundImageURL; }
        set { m_profileBackgroundImageURL = value; }
    }
    
    public bool ProfileBackgroundTile
    {
        get { return m_profileBackgroundTile; }
        set { m_profileBackgroundTile = value; }
    }
    
    public Int64 StatusesCount
    {
        get { return m_statusesCount; }
        set { m_statusesCount = value; }
    }
    
    public bool Notifications
    {
        get { return m_notifications; }
        set { m_notifications = value; }
    }

    public bool Following
    {
        get { return m_following; }
        set { m_following = value; }
    }

    #endregion

    #region Constructor

    public User(XElement e)
    {
        m_userID = Int64.Parse(e.Element("user").Element("id").Value);
        Name = e.Element("user").Element("name").Value;
        ScreenName = e.Element("user").Element("screen_name").Value;
        Location = e.Element("user").Element("location").Value;
        Description = e.Element("user").Element("description").Value;
        ProfileImageURL = e.Element("user").Element("profile_image_url").Value;
        Url = e.Element("user").Element("url").Value;
        Protected = (!string.IsNullOrEmpty(e.Element("user").Element("protected").Value)) ? bool.Parse(e.Element("user").Element("protected").Value) : false;
        FollowersCount = Int64.Parse(e.Element("user").Element("followers_count").Value);
        ProfileBackgroundColor = e.Element("user").Element("profile_background_color").Value;
        ProfileTextColor = e.Element("user").Element("profile_text_color").Value;
        ProfileLinkColor = e.Element("user").Element("profile_link_color").Value;
        ProfileSidebarFillColor = e.Element("user").Element("profile_sidebar_fill_color").Value;
        ProfileSidebarBorderColor = e.Element("user").Element("profile_sidebar_border_color").Value;
        FriendsCount = Int64.Parse(e.Element("user").Element("friends_count").Value);
        CreatedAt = Common.ParseDateTime(e.Element("user").Element("created_at").Value);
        FavoritesCount = Int64.Parse(e.Element("user").Element("favourites_count").Value);
        UTCOffset = e.Element("user").Element("utc_offset").Value;
        TimeZone = e.Element("user").Element("time_zone").Value;
        ProfileBackgroundImageURL = e.Element("user").Element("profile_background_image_url").Value;
        ProfileBackgroundTile = (!string.IsNullOrEmpty(e.Element("user").Element("profile_background_tile").Value)) ? bool.Parse(e.Element("user").Element("profile_background_tile").Value) : false;
        StatusesCount = Int64.Parse(e.Element("user").Element("statuses_count").Value);
        Notifications = (!string.IsNullOrEmpty(e.Element("user").Element("notifications").Value)) ? bool.Parse(e.Element("user").Element("notifications").Value) : false;
        Following = (!string.IsNullOrEmpty(e.Element("user").Element("following").Value)) ? bool.Parse(e.Element("user").Element("following").Value) : false;
    }

    #endregion
}



Since this is from my Twitter API library, I have created a few methods to make it easier to make the REST API calls from different public methods.

Custom Twitter class
public class Twitter
{
    #region Local Variables and Properties

    private string m_userName = string.Empty;
    private string m_password = string.Empty;

    public string UserName
    {
        get { return m_userName; }
        set { m_userName = value; }
    }

    public string Password
    {
        get { return m_password; }
        set { m_password = value; }
    }

    #endregion

    // .......
    //  Other code that is shown in this tutorial
}



Post method
private string Post(string url)
{
    return PerformRequest("POST", url);
}



Get method
private string Get(string url)
{
    return PerformRequest("GET", url);
}



PerformRequest method
/// <summary>
/// Gets the XML data from the request URL
/// </summary>
/// <param name="method">POST or GET</param>
/// <param name="url">URL of Twitter REST API</param>
/// <returns></returns>
private string PerformRequest(string method, string url)
{
    string responseString = string.Empty;
    WebResponse response = null;
    try
    {
        HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
        request.Method = method;
        request.Credentials = new NetworkCredential(m_userName, m_password);
        response = request.GetResponse();
        using (StreamReader reader = new StreamReader(response.GetResponseStream()))
        {
            responseString = reader.ReadToEnd();
        }
    }
    catch (Exception ex)
    {
        responseString = "***ERROR :: " + ex.Message;
    }

    return responseString;
}



ParseDateTime method
/// <summary>
/// Parses the DateTime from Twitter into a usable DateTime object
/// </summary>
/// <param name="date">Date from Twitter</param>
/// <returns></returns>
private DateTime ParseDateTime(string date)
{
    // Twitter's dates are formatted as:
    //       Tue Apr 07 22:52:51 +0000 2009
    string dayOfWeek = date.Substring(0, 3).Trim();
    string month = date.Substring(4, 3).Trim();
    string dayInMonth = date.Substring(8, 2).Trim();
    string time = date.Substring(11, 9).Trim();
    string offset = date.Substring(20, 5).Trim();
    string year = date.Substring(25, 5).Trim();
    string dateTime = string.Format("{0}-{1}-{2} {3}", dayInMonth, month, year, time);
    DateTime ret = DateTime.Parse(dateTime);
    return ret;
}



So now we will get down to the meat-and-potatoes of the Twitter API.

/// <summary>
/// Gets user's timeline
/// </summary>
/// <returns>Returns a List of UserStatus or null if user is not found</returns>
public List<UserStatus> GetUserTimeLine()
{
    string url = string.Format("http://twitter.com/statuses/user_timeline/{0}.xml", m_userName);
    string response = Get(url);

    List<UserStatus> users = null;

    if (!response.Contains("ERROR"))
    {
        XDocument document = Xdocument.Parse(response, LoadOptions.None);

        var query = from e in document.Root.Descendants("status")
                    select new UserStatus
                    {
                        User = new User(e),
                        StatusCreatedAt = Common.ParseDateTime(e.Element("created_at").Value),
                        StatusID = Int64.Parse(e.Element("id").Value),
                        Text = HttpUtility.HtmlDecode(e.Element("text").Value),
                        Source = e.Element("source").Value,
                        Truncated = (!string.IsNullOrEmpty(e.Element("truncated").Value)) ? bool.Parse(e.Element("truncated").Value) : false,
                        InReplyToStatusID = (!string.IsNullOrEmpty(e.Element("in_reply_to_status_id").Value)) ? Int64.Parse(e.Element("in_reply_to_status_id").Value) : 0,
                        InReplyToUserID = (!string.IsNullOrEmpty(e.Element("in_reply_to_user_id").Value)) ? Int64.Parse(e.Element("in_reply_to_user_id").Value) : 0,
                        Favorited = (!string.IsNullOrEmpty(e.Element("favorited").Value)) ? bool.Parse(e.Element("favorited").Value) : false,
                        InReplyToScreenName = e.Element("in_reply_to_screen_name").Value,
                    };

        users = (from u in query
                 where u.Text != ""
                 orderby u.StatusCreatedAt descending
                 select u).ToList();
    }

    return users;
}



Now to put it all together, we create a simple Form with a button. In that button's click event...
private void btnUserTimeLine_Click(object sender, EventArgs e)
{
    Twitter twit = new Twitter();
    twit.UserName = "someUserName";
    twit.Password = "somePassword";

    List<UserStatus> userStatuses = twit.GetUserTimeLine();

    if (userStatuses == null)
    {
        MessageBox.Show("User not found");
        return;
    }
    
    foreach (UserStatus us in userStatuses)
    {
        MessageBox.Show(us.User.ScreenName + ": " + us.Text);
    }
}



So you now have a foundation for writing your own library for the Twitter API.

**** NOTE ****
The ParseDateTime, PerformRequest, Post, and Get methods were taken from this site:

http://blogs.microso...-time-line.aspx

Is This A Good Question/Topic? 0
  • +

Page 1 of 1