Post "Hello World" to twitter from .NET application
Yes, you can do it without any third-party library. See my IronPython sample posted on the IronPython Cookbook site that shows you exactly how. Even if you don't program in IronPython, the main part of the code that should get you started is repeated below and easy to port to C#:
ServicePointManager.Expect100Continue = False
wc = WebClient(Credentials = NetworkCredential(username, password))
wc.Headers.Add('X-Twitter-Client', 'Pweeter')
form = NameValueCollection()
form.Add('status', status)
wc.UploadValues('http://twitter.com/statuses/update.xml', form)
Basically, this does an HTTP POST to http://twitter.com/statuses/update.xml with a single HTML FORM field called status
and which contains the status update text for the account identified by username
(and password
).
I created a video tutorial showing exactly how to setup the application inside twitter, install an API Library using nuget, accept an access token from a user and post on that user's behalf:
Video: http://www.youtube.com/watch?v=TGEA1sgMMqU
Tutorial: http://www.markhagan.me/Samples/Grant-Access-And-Tweet-As-Twitter-User-ASPNet
In case you don't want to leave this page:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Twitterizer;
namespace PostFansTwitter
{
public partial class twconnect : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
var oauth_consumer_key = "gjxG99ZA5jmJoB3FeXWJZA";
var oauth_consumer_secret = "rsAAtEhVRrXUTNcwEecXqPyDHaOR4KjOuMkpb8g";
if (Request["oauth_token"] == null)
{
OAuthTokenResponse reqToken = OAuthUtility.GetRequestToken(
oauth_consumer_key,
oauth_consumer_secret,
Request.Url.AbsoluteUri);
Response.Redirect(string.Format("http://twitter.com/oauth/authorize?oauth_token={0}",
reqToken.Token));
}
else
{
string requestToken = Request["oauth_token"].ToString();
string pin = Request["oauth_verifier"].ToString();
var tokens = OAuthUtility.GetAccessToken(
oauth_consumer_key,
oauth_consumer_secret,
requestToken,
pin);
OAuthTokens accesstoken = new OAuthTokens()
{
AccessToken = tokens.Token,
AccessTokenSecret = tokens.TokenSecret,
ConsumerKey = oauth_consumer_key,
ConsumerSecret = oauth_consumer_secret
};
TwitterResponse<TwitterStatus> response = TwitterStatus.Update(
accesstoken,
"Testing!! It works (hopefully).");
if (response.Result == RequestResult.Success)
{
Response.Write("we did it!");
}
else
{
Response.Write("it's all bad.");
}
}
}
}
}
Just use this implemented wrapper for the Twitter API:
https://github.com/danielcrenna/tweetsharp
var twitter = FluentTwitter.CreateRequest()
.AuthenticateAs("USERNAME", "PASSWORD")
.Statuses().Update("Hello World!")
.AsJson();
var response = twitter.Request();
From: http://code-inside.de/blog-in/2009/04/23/howto-tweet-with-c/
There is even a DotNetRocks interview with the developers.