tweetinvi developer c# twitter

c# - developer - twitter java



Actualiza el estado de Twitter en C# (7)

No soy partidario de reinventar la rueda, especialmente cuando se trata de productos que ya existen que proporcionan el 100% de la funcionalidad buscada. De hecho, tengo el código fuente de Twitterizer corriendo al lado de mi aplicación ASP.NET MVC solo para poder hacer los cambios necesarios ...

Si realmente no desea que exista la referencia de DLL, aquí hay un ejemplo sobre cómo codificar las actualizaciones en C #. Mira esto desde dreamincode .

/* * A function to post an update to Twitter programmatically * Author: Danny Battison * Contact: [email protected] */ /// <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 */} }

Estoy tratando de actualizar el estado de Twitter de un usuario desde mi aplicación C #.

Busqué en la web y encontré varias posibilidades, pero estoy un poco confundido por el reciente (?) Cambio en el proceso de autenticación de Twitter. También encontré lo que parece ser una publicación relevante de StackOverflow , pero simplemente no responde a mi pregunta porque es muy específico, ya que un fragmento de código no funciona.

Estoy tratando de llegar a la API REST y no a la API de búsqueda, lo que significa que debo cumplir con la autenticación OAuth más estricta.

Miré dos soluciones. El Framework de Twitterizer funcionó bien, pero es un DLL externo y prefiero usar el código fuente. Solo como ejemplo, el código que lo usa es muy claro y se ve así:

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

También examiné la biblioteca de Twitter de Yedda , pero esta falló en lo que creo que es el proceso de autenticación, cuando intento básicamente el mismo código que el anterior (Yedda espera el nombre de usuario y la contraseña en la actualización de estado pero todo lo demás se supone que es el mismo )

Como no pude encontrar una respuesta clara en la web, la llevo a StackOverflow.

¿Cuál es la forma más sencilla de obtener una actualización de estado de Twitter que funcione en una aplicación C #, sin dependencia DLL externa?

Gracias


Otra biblioteca de Twitter que he utilizado con éxito es TweetSharp , que proporciona una API fluida.

El código fuente está disponible en el código de Google . ¿Por qué no quieres usar un dll? Esa es la forma más fácil de incluir una biblioteca en un proyecto.


Si le gusta el marco de Twitterizer pero simplemente no le gusta no tener la fuente, ¿por qué no descargar la fuente ? (O navega si solo quieres ver lo que está haciendo ...)


La forma más sencilla de publicar cosas en Twitter es usar autenticación básica , que no es muy sólida.

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


Prueba TweetSharp . Buscar el estado de actualización de TweetSharp con el ejemplo de código completo de medios funciona con la API REST de Twitter V1.1. La solución también está disponible para descargar.

Ejemplo de código de 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"); } }


Prueba LINQ To Twitter . Encuentre el estado de actualización de LINQ To Twitter con el ejemplo de código completo de medios que funciona con Twitter REST API V1.1. La solución también está disponible para descargar.

LINQ a la muestra de código de 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);


Aquí hay otra solución con un código mínimo que usa el excelente paquete AsyncOAuth Nuget y el HttpClient de Microsoft. Esta solución también asume que está publicando en su propio nombre, por lo que ya tiene su clave / secreto de token de acceso, sin embargo, incluso si no lo hace, el flujo es bastante fácil (vea 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 } } }

Esto funciona en todas las plataformas debido a la naturaleza de HttpClient. Uso este método yo mismo en Windows Phone 7/8 para un servicio completamente diferente.