Update Twitter Status in C #

I am trying to update twitter user status from my C # application.

I searched the Internet and found several possibilities, but I am a little confused by the recent (?) Change of the Twitter authentication process. I also found what it seems to be https://stackoverflow.com/a/1361212/..but it just doesn't answer my question because it ultra-specifically restores a piece of code that doesn't work.

I am trying to achieve a REST API, not a search API, which means that I have to perform stronger OAuth authentication.

I reviewed two solutions. The Twitterizer Framework worked fine, but it is an external DLL, and I would rather use the source code. As an example, the code using it is very clear and looks like this:

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

I also reviewed the Yedda Twitter library , but this error failed due to what I consider to be an authentication process, while trying to basically use the same code as above (Yedda expects a username and password in the status update itself, but everything else should be the same).

Since I could not find a clear answer on the Internet, I bring it to StackOverflow.

What is the easiest way to get Twitter status updates running in a C # application without an external DLL dependency?

thanks

+5
source share
7 answers

Twitterizer, , , ? ( , , ...)

+10

, , 100% . Twitterizer, ASP.NET MVC, ...

, DLL , , #. 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 */}
}
+7

Twitter, , - TweetSharp, API.

Google. dll? .

+3

- , .

    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);
    }
+1

LINQ To Twitter. LINQ To Twitter , Twitter REST API V1.1. .

LINQ To Twitter

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);
+1

TweetSharp. TweetSharp Twitter REST API V1.1. .

TweetSharp

//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");
            }
        }
0

Here's another solution with minimal code, using the excellent AsyncOAuth package from Nuget and Microsoft HttpClient. This solution also assumes that you publish on your behalf, so that you already have a key / secret access token, however, even if the stream is not very simple (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 the nature of HttpClient. I use this method myself on Windows Phone 7/8 for a completely different service.

0
source

All Articles