2009-07-30 12 views
5

Estoy tratando de actualizar el estado de Twitter de un usuario desde mi aplicación C#.Actualizar estado de Twitter en 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 un relevant StackOverflow post, pero simplemente no responde mi pregunta porque es ultraespecífico que vuelve a generar un fragmento de código que no funciona.

Estoy intentando 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 Twitterizer Framework funcionó bien, pero es un DLL externo y prefiero usar el código fuente. A modo de ejemplo, el código de uso es muy clara y se ve así:

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

también examiné Yedda's Twitter library, pero éste fracasó en lo que yo creo que es el proceso de autenticación, cuando se trata básicamente el mismo código que arriba (Yedda espera el nombre de usuario y la contraseña en la actualización de estado, pero se supone que todo lo demás es igual).

Como no pude encontrar una respuesta clara en la web, la llevaré 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

Respuesta

10

Si te gusta el Marco Twitterizer pero simplemente no les gusta no tener la fuente, por qué no download the source? (O browse it si solo quiere ver lo que está haciendo ...)

+0

Bueno, supongo que una pregunta tonta merece una respuesta simple ... De alguna manera me perdí el hecho de que sus fuentes estaban disponibles. Gracias :) –

7

No soy un fanático 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 una 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 */} 
} 
+1

¡Es sorprendente que haya marcos de desarrollo para Twitter cuando solo 10 líneas de C# son suficientes para hacer esto! +1 – nbevans

+5

@NathanE: Hay muchas cosas que son solo unas 10 líneas de código, pero que es bueno tener en una biblioteca. Le impide cometer errores tontos, como olvidar las declaraciones de 'uso' de las transmisiones y evitar excepciones, por ejemplo ... –

+3

@NathanE: todavia me mantengo fiel a mi recomendación que Jon también hizo eco de que use la Biblioteca siempre que sea posible y cree la biblioteca si necesita una ... – RSolberg

3

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

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

1

La forma más sencilla de publicar cosas en twitter es usar basic authentication, que no es muy fuerte.

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

Probar TweetSharp. Buscar TweetSharp update status with media complete code example funciona con Twitter REST API V1.1. La solución también está disponible para descargar.

Código TweetSharp Muestra

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

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

LINQ A Twitter Código de ejemplo

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

Aquí hay otra solución con código mínimo utilizando la excelente AsyncOAuth paquete Nuget y Microsoft de HttpClient. 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.

Cuestiones relacionadas