2009-07-30 19 views
5

Sto tentando di aggiornare lo stato di Twitter di un utente dalla mia applicazione C#.Aggiornamento dello stato di Twitter in C#

Ho cercato sul Web e trovato diverse possibilità, ma sono un po 'confuso dal recente (?) Cambiamento nel processo di autenticazione di Twitter. Ho anche trovato quello che sembra essere un relevant StackOverflow post, ma semplicemente non risponde alla mia domanda perché è ultra-specifico che regadora uno snippet di codice che non funziona.

Sto tentando di raggiungere l'API REST e non l'API di ricerca, il che significa che dovrei rispettare l'autenticazione OAuth più rigida.

Ho esaminato due soluzioni. Il Twitterizer Framework ha funzionato bene, ma è una DLL esterna e preferisco usare il codice sorgente. A titolo di esempio, il codice utilizzando è molto chiaro e si presenta in questo modo:

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

ho anche esaminato Yedda's Twitter library, ma questo non è riuscito su quello che ritengo essere il processo di autenticazione, quando si cerca in sostanza lo stesso codice sopra (Yedda si aspetta il nome utente e la password nell'aggiornamento di stato stesso, ma tutto il resto dovrebbe essere lo stesso).

Dal momento che non sono riuscito a trovare una risposta chiara sul web, lo porto a StackOverflow.

Qual è il modo più semplice per ottenere un aggiornamento dello stato di Twitter che funzioni in un'applicazione C#, senza dipendenza DLL esterna?

Grazie

risposta

10

Se ti piace il quadro Twitterizer, ma proprio non mi piace non avere la fonte, perché non download the source? (O browse it se vuoi vedere cosa sta facendo ...)

+0

Beh, immagino che una domanda stupida meriti una risposta semplice ... In qualche modo ho perso il fatto che le loro fonti erano disponibili. Grazie :) –

7

Non sono un fan di re-inventare la ruota, specialmente quando si tratta di prodotti che già esistono che forniscono il 100% della funzionalità ricercata . In realtà ho il codice sorgente per Twitterizer che esegue parallelamente l'applicazione ASP.NET MVC solo per poter apportare le modifiche necessarie ...

Se davvero non si desidera che il riferimento DLL esista, ecco un esempio su come codificare gli aggiornamenti in C#. Dai un'occhiata a 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

È incredibile che ci siano framework di sviluppo per Twitter là fuori quando bastano solo 10 righe di C# per farlo! +1 – nbevans

+5

@NathanE: ci sono molte cose che sono solo circa 10 righe di codice, ma che sono buone da avere in una libreria. Ti impedisce di commettere errori stupidi come dimenticare le istruzioni '' using' 'per flussi e ingoiare le eccezioni, ad esempio ... –

+3

@NathanE: resto fedele alla mia raccomandazione che Jon ha echeggiato e che usa la Libreria dove possibile e crea il libreria se ne hai bisogno ... – RSolberg

3

Un'altra libreria Twitter che ho usato con successo è TweetSharp, che fornisce un'API fluente.

Il codice sorgente è disponibile allo Google code. Perché non vuoi usare una dll? Questo è di gran lunga il modo più semplice per includere una libreria in un progetto.

1

Il modo più semplice per pubblicare contenuti su Twitter è utilizzare basic authentication, che non è molto potente.

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

Prova TweetSharp. Trova TweetSharp update status with media complete code example funziona con Twitter REST API V1.1. La soluzione è anche disponibile per il download.

codice di esempio 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"); 
      } 
     } 
1

Prova LINQ To Twitter.Trova lo stato di aggiornamento LINQ To Twitter con l'esempio di codice completo del supporto compatibile con API REST di Twitter V1.1. La soluzione è anche disponibile per il download.

LINQ Per Twitter codice di esempio

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

Ecco un'altra soluzione con codice minimo utilizzando l'eccellente pacchetto di AsyncOAuth Nuget e Microsoft di HttpClient. Questa soluzione presuppone anche che si stia pubblicando per proprio conto in modo da avere già accesso alla chiave/segreto del token, anche se il flusso non è abbastanza semplice (consultare Documenti AsyncOauth).

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

Questo funziona su tutte le piattaforme a causa della natura di HttpClient. Uso questo metodo personalmente su Windows Phone 7/8 per un servizio completamente diverso.

Problemi correlati