Question

I'm trying to update a user's Twitter status from my C# application.

I searched the web and found several possibilities, but I'm a bit confused by the recent (?) change in Twitter's authentication process. I also found what seems to be a relevant StackOverflow post, but it simply does not answer my question because it's ultra-specific regading a code snippet that does not work.

I'm attempting to reach the REST API and not the Search API, which means I should live up to the stricter OAuth authentication.

I looked at two solutions. The Twitterizer Framework worked fine, but it's an external DLL and I would rather use source code. Just as an example, the code using it is very clear and looks like so:

Twitter twitter = new Twitter("username", "password");
twitter.Status.Update("Hello World!");

I also examined Yedda's Twitter library, but this one failed on what I believe to be the authentication process, when trying basically the same code as above (Yedda expects the username and password in the status update itself but everything else is supposed to be the same).

Since I could not find a clear cut answer on the web, I'm bringing it to StackOverflow.

What's the simplest way to get a Twitter status update working in a C# application, without external DLL dependency?

Thanks

Was it helpful?

Solution

If you like the Twitterizer Framework but just don't like not having the source, why not download the source? (Or browse it if you just want to see what it's doing...)

OTHER TIPS

I'm not a fan of re-inventing the wheel, especially when it comes to products that already exist that provide 100% of the sought functionality. I actually have the source code for Twitterizer running side by side my ASP.NET MVC application just so that I could make any necessary changes...

If you really don't want the DLL reference to exist, here is an example on how to code the updates in C#. Check this out from dreamincode.

/*
 * A function to post an update to Twitter programmatically
 * Author: Danny Battison
 * Contact: gabehabe@hotmail.com
 */

/// <summary>
/// Post an update to a Twitter acount
/// </summary>
/// <param name="username">The username of the account</param>
/// <param name="password">The password of the account</param>
/// <param name="tweet">The status to post</param>
public static void PostTweet(string username, string password, string tweet)
{
    try {
        // encode the username/password
        string user = Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(username + ":" + password));
        // determine what we want to upload as a status
        byte[] bytes = System.Text.Encoding.ASCII.GetBytes("status=" + tweet);
        // connect with the update page
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://twitter.com/statuses/update.xml");
        // set the method to POST
        request.Method="POST";
        request.ServicePoint.Expect100Continue = false; // thanks to argodev for this recent change!
        // set the authorisation levels
        request.Headers.Add("Authorization", "Basic " + user);
        request.ContentType="application/x-www-form-urlencoded";
        // set the length of the content
        request.ContentLength = bytes.Length;

        // set up the stream
        Stream reqStream = request.GetRequestStream();
        // write to the stream
        reqStream.Write(bytes, 0, bytes.Length);
        // close the stream
        reqStream.Close();
    } catch (Exception ex) {/* DO NOTHING */}
}

Another Twitter library I have used sucessfully is TweetSharp, which provides a fluent API.

The source code is available at Google code. Why don't you want to use a dll? That is by far the easiest way to include a library in a project.

The simplest way to post stuff to twitter is to use basic authentication , which isn't very strong.

    static void PostTweet(string username, string password, string tweet)
    {
         // Create a webclient with the twitter account credentials, which will be used to set the HTTP header for basic authentication
         WebClient client = new WebClient { Credentials = new NetworkCredential { UserName = username, Password = password } };

         // Don't wait to receive a 100 Continue HTTP response from the server before sending out the message body
         ServicePointManager.Expect100Continue = false;

         // Construct the message body
         byte[] messageBody = Encoding.ASCII.GetBytes("status=" + tweet);

         // Send the HTTP headers and message body (a.k.a. Post the data)
         client.UploadData("http://twitter.com/statuses/update.xml", messageBody);
    }

Try LINQ To Twitter. Find LINQ To Twitter update status with media complete code example that works with Twitter REST API V1.1. Solution is also available for download.

LINQ To Twitter Code Sample

var twitterCtx = new TwitterContext(auth);
string status = "Testing TweetWithMedia #Linq2Twitter " +
DateTime.Now.ToString(CultureInfo.InvariantCulture);
const bool PossiblySensitive = false;
const decimal Latitude = StatusExtensions.NoCoordinate; 
const decimal Longitude = StatusExtensions.NoCoordinate; 
const bool DisplayCoordinates = false;

string ReplaceThisWithYourImageLocation = Server.MapPath("~/test.jpg");

var mediaItems =
       new List<media>
       {
           new Media
           {
               Data = Utilities.GetFileBytes(ReplaceThisWithYourImageLocation),
               FileName = "test.jpg",
               ContentType = MediaContentType.Jpeg
           }
       };

 Status tweet = twitterCtx.TweetWithMedia(
    status, PossiblySensitive, Latitude, Longitude,
    null, DisplayCoordinates, mediaItems, null);

Try TweetSharp . Find TweetSharp update status with media complete code example works with Twitter REST API V1.1. Solution is also available for download.

TweetSharp Code Sample

//if you want status update only uncomment the below line of code instead
        //var result = tService.SendTweet(new SendTweetOptions { Status = Guid.NewGuid().ToString() });
        Bitmap img = new Bitmap(Server.MapPath("~/test.jpg"));
        if (img != null)
        {
            MemoryStream ms = new MemoryStream();
            img.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
            ms.Seek(0, SeekOrigin.Begin);
            Dictionary<string, Stream> images = new Dictionary<string, Stream>{{"mypicture", ms}};
            //Twitter compares status contents and rejects dublicated status messages. 
            //Therefore in order to create a unique message dynamically, a generic guid has been used

            var result = tService.SendTweetWithMedia(new SendTweetWithMediaOptions { Status = Guid.NewGuid().ToString(), Images = images });
            if (result != null && result.Id > 0)
            {
                Response.Redirect("https://twitter.com");
            }
            else
            {
                Response.Write("fails to update status");
            }
        }

Here's another solution with minimal code using the excellent AsyncOAuth Nuget package and Microsoft's HttpClient. This solution also assumes you're posting on your own behalf so you have your access token key/secret already, however even if you don't the flow is pretty easy (see AsyncOauth docs).

using System.Threading.Tasks;
using AsyncOAuth;
using System.Net.Http;
using System.Security.Cryptography;

public class TwitterClient
{
    private readonly HttpClient _httpClient;

    public TwitterClient()
    {
        // See AsyncOAuth docs (differs for WinRT)
        OAuthUtility.ComputeHash = (key, buffer) =>
        {
            using (var hmac = new HMACSHA1(key))
            {
                return hmac.ComputeHash(buffer);
            }
        };

        // Best to store secrets outside app (Azure Portal/etc.)
        _httpClient = OAuthUtility.CreateOAuthClient(
            AppSettings.TwitterAppId, AppSettings.TwitterAppSecret,
            new AccessToken(AppSettings.TwitterAccessTokenKey, AppSettings.TwitterAccessTokenSecret));
    }

    public async Task UpdateStatus(string status)
    {
        try
        {
            var content = new FormUrlEncodedContent(new Dictionary<string, string>()
            {
                {"status", status}
            });

            var response = await _httpClient.PostAsync("https://api.twitter.com/1.1/statuses/update.json", content);

            if (response.IsSuccessStatusCode)
            {
                // OK
            }
            else
            {
                // Not OK
            }

        }
        catch (Exception ex)
        {
            // Log ex
        }
    }
}

This works on all platforms due to HttpClient's nature. I use this method myself on Windows Phone 7/8 for a completely different service.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top