|
ComposingQueries
Basic usage of the tweet# API
Required Namespaces You need to including the following namespaces to make full use of the TweetSharp library. // Provides access to the fluent API; required using Dimebrain.TweetSharp.Fluent; // Provides access to the data classes that represent Twitter results using Dimebrain.TweetSharp.Model; // Provides access to features like relative time, and casting from XML/JSON to // Twitter data classes using Dimebrain.TweetSharp.Extensions; All queries to twitter begin with a call to create a request. This call can accept a TwitterClientInfo object that provides the name, URL, and version of your own client to send with requests. If you don't provide any client info, default info identifying your client as a tweet# client is used. var request = FluentTwitter.CreateRequest(myClientInfo); Each major area of the REST API (including search) is represented by the next method in the query chain. These major areas are: Statuses(), Users(), DirectMessages(), Friendships(), Accounts(), Favorites(), Notifications(), Blocking(), Help(), and Search(). Use each of these method branches to perform specific actions. For example, to get statuses on the public timeline, you would create your request, step down into 'Statuses' and discover the correct method to use. You can also specify the format you wish to receive the request from Twitter (currently one of JSON, XML, RSS, or ATOM) with a call to AsJson(), AsXml(), AsRss(), or AsAtom(). If a particular format is unavailable for your specific query area, you won't be able to call that method. // Get the public timeline
var twitter = FluentTwitter.CreateRequest()
.Statuses().OnPublicTimeline().AsJson();
// Sequential call for data
var response = twitter.Request();
// Convert response to data classes
var statuses = response.AsStatuses(); Note: If you call the query's ToString() method, you will receive back a human-readable URL that the query will use when sending the call to the Twitter API. The actual, encoded URL is provided through the AsUrl() extension method. Asynchronous Requests Making asynchronous calls to the Twitter API for more advanced client usage scenarios is easy with tweet#. To make an asynchronous request, call {{{RequestAsync()}} and provide a callback method with a typical event argument signature. var block = new AutoResetEvent(false);
var twitter = FluentTwitter.CreateRequest()
.Statuses().OnPublicTimeline()
.CallbackTo((s, e) =>
{
// do stuff with the response
var users = e.Response.AsUsers();
block.Set();
}).AsJson();
twitter.RequestAsync();
block.WaitOne();Caching To design a client that is mindful of the number of API calls it makes, and particularly for community-based applications, you can cache requests to tweet# so that large numbers of requests are served from a cached response rather than from the API. You can specify sliding, absolute, or indefinite caching, and may override the ICache interface in order to provide your own caching client. Out of the box, tweet# supports ASP.NET cache, a simple in-memory dictionary, or memcached, with plans to support Velocity in the future. Helpful extension methods allow you to express cache expiration naturally, as in the following example // an absolute expiry cached request
var twitter = FluentTwitter.CreateRequest()
.Configuration.CacheUntil(2.Seconds().FromNow())
.Statuses().OnPublicTimeline()
.AsJson();
// this response comes from twitter
var one = twitter.Request();
// this response comes from cache
var two = twitter.Request();// a sliding expiry cached request
var twitter = FluentTwitter.CreateRequest()
.Configuration.CacheForInactivityOf(60.Seconds())
.Statuses().OnPublicTimeline()
.AsJson();
var response = twitter.Request();Handling Exceptions If the Twitter API returns an error during your request, the response returned in the request call will contain a string value for Twitter's reply, the same as if the response was successful. If the response is an error and not the expected data class type, attempts to cast to the data class will return a null instance, while attempts to cast to an error class will succeed.
// call will fail with no auth provided
var twitter = FluentTwitter.CreateRequest()
.Statuses.OnUserTimeline().AsJson();
var response = twitter.Request();
if(response.AsStatuses() == null)
{
// check and see if this came back in error
var error = response.AsError();
if(error != null)
{
Console.WriteLine("Request for {0} ended in {1}", error.Request, error.ErrorMessage);
}
}
You can also optionally use the HasError property on your FluentTwitter query instance to determine if the last Response was an error, and access the Response object itself for lower level details. If Twitter returns the 'Fail Whale', the content of the request text will contain the actual Fail Whale page. The next version of TweetSharp will include strongly typed errors, including the FailWhaleError, to make it easier to handle this event. Basic Authentication Queries that require basic authentication (username and password) can be called using the AuthenticateAs() method. var twitter = FluentTwitter.CreateRequest()
.AuthenticateAs(TWITTER_USERNAME, TWITTER_PASSWORD)
.Statuses().Update("testing, one, two, three!")
.AsJson();
var response = twitter.Request();OAuth Authentication Queries that require OAuth authentication (token exchange and user authorization) can be called using the AuthenticateWith() method. // This assumes you already possess the access token
var twitter = FluentTwitter.CreateRequest()
.AuthenticateWith(OAUTH_CONSUMER_KEY,
OAUTH_CONSUMER_SECRET,
OAUTH_TOKEN,
OAUTH_TOKEN_SECRET)
.Statuses().Update("testing, one, two, three!")
.AsJson();
var response = twitter.Request();Optionally, you may provide the consumer key and consumer secret in the TwitterClientInfo class details; after doing so you won't need to provide them with each OAuth-enabled method. OAuth Workflow 1. Requesting an unauthorized request token var twitter = FluentTwitter.CreateRequest()
.Authentication.GetRequestToken(OAUTH_CONSUMER_KEY, OAUTH_CONSUMER_SECRET);
var response = twitter.Request();
var token = response.AsToken();2. Authorizing a desktop // Defining this method will automatically open a browser to the
// authorization URL on Twitter for user input
var twitter = FluentTwitter.CreateRequest()
.Authentication.AuthorizeDesktop(OAUTH_CONSUMER_KEY,
OAUTH_CONSUMER_SECRET,
request.Token,
request.TokenSecret);
// Time passes...
// This call will attempt to exchange the request token for
// an access token that can be used in the AuthenticateWith() method
var response = twitter.Request();
var token = response.AsToken();3. Exchanging a request token for an access token var twitter = FluentTwitter.CreateRequest()
.Authentication.GetAccessToken(OAUTH_CONSUMER_KEY,
OAUTH_CONSUMER_SECRET,
request.Token,
request.TokenSecret);
var response = twitter.Request();
var token = response.AsToken();
|
Sign in to add a comment
Hello folks, before leaving a comment, please know that Google does not send a notification when you add a comment to this page, so you may not get a response. If you have a question about TweetSharp?, please visit http://groups.google.com/group/tweetsharp and post your question on our Google Groups page directly.
Thanks!