سؤال

أحاول تحديث مستخدم تويتر حالة من C# التطبيق.

بحثت في الإنترنت ووجدت عدة احتمالات ، ولكن أنا مشوشة قليلا قبل الأخيرة (?) تغيير في تويتر عملية المصادقة.كما أنني وجدت ما يبدو ، ذات الصلة ستاكوفيرفلوو بعد, لكنه ببساطة لا يجيب على سؤالي لأنه فائقة محددة regading التعليمات البرمجية المتكررة التي لا تعمل.

أنا يحاولون الوصول إلى بقية API وليس البحث API ، وهو ما يعني أنني يجب أن ترقى إلى مستوى أكثر صرامة أوث المصادقة.

نظرت اثنين من الحلول.على Twitterizer إطار عملت بشكل جيد, لكنه خارجي DLL وأنا أفضل استخدام التعليمات البرمجية المصدر.فقط كمثال ، رمز باستخدام فمن الواضح جدا تبدو مثل ذلك:

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

أنا أيضا درست ييدا تويتر المكتبة, لكن هذا فشل على ما أعتقد أن تكون عملية التوثيق ، عندما تحاول أساسا نفس القانون أعلاه (ييدا تتوقع اسم المستخدم وكلمة المرور في حالة تحديث نفسها ولكن كل شيء آخر هو من المفترض أن يكون نفس).

منذ أنا لا يمكن أن تجد واضحة المعالم الإجابة على شبكة الإنترنت ، أنا ليصل إلى ستاكوفيرفلوو.

ما هو أبسط طريقة للحصول على تويتر تحديث حالة العمل في C# التطبيق ، دون DLL الخارجية التبعية?

شكرا

هل كانت مفيدة؟

المحلول

إذا أحببت هذا الإطار Twitterizer ولكن لا أحب عدم وجود مصدر، لماذا لا <لأ href = "http://code.google.com/p/twitterizer/source/checkout" يختلط = "نوفولو noreferrer "> تحميل المصدر ؟ (أو تصفح أنه إذا كنت ترغب فقط لرؤية ما تقوم به .. .)

نصائح أخرى

وأنا لست من محبي اختراع إعادة عجلة القيادة، وخصوصا عندما يتعلق الأمر المنتجات الموجودة بالفعل أن نقدم 100٪ من وظائف المطلوبة. أنا فعلا شفرة المصدر ل Twitterizer تشغيل جنبا إلى جنب طلبي ASP.NET MVC فقط كي أتمكن من إجراء أية تغييرات ضرورية ...

إذا كنت حقا لا أريد الإشارة DLL في الوجود، وهنا مثال على كيفية رمز التحديثات في C #. التحقق من ذلك من 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 */}
}

ومكتبة أخرى تويتر ولقد استخدمت بنجاح ل TweetSharp ، الذي يوفر API بطلاقة.

وشفرة المصدر متاح في جوجل كود . لماذا لا تريد استخدام دلل؟ هذا هو إلى حد بعيد أسهل طريقة لتشمل مكتبة في المشروع.

وأبسط طريقة لإضافة الاشياء لتويتر لاستخدام الأساسية المصادقة ، الذي يسن ' ر قوية جدا.

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

محاولة LINQ إلى تويتر.البحث LINQ إلى تويتر حالة التحديث مع وسائل الإعلام كاملة المثال التعليمات البرمجية التي تعمل مع تويتر API REST V1.1.الحل هو متاح أيضا للتحميل.

LINQ إلى تويتر نموذج التعليمات البرمجية

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

محاولة TweetSharp .البحث TweetSharp حالة التحديث مع وسائل الإعلام كاملة التعليمات البرمجية المثال تعمل مع تويتر API REST 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");
            }
        }

وهنا حل آخر مع الحد الأدنى من التعليمات البرمجية باستخدام AsyncOAuth Nuget حزمة وHttpClient مايكروسوفت. هذا الحل يفترض أيضا كنت نشرها على مصلحتك الخاصة جدا أن يكون لديك وصول رمزي مفتاح / سر بالفعل، ولكن حتى لو كنت لا تدفق من السهل جدا (انظر مستندات 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
        }
    }
}

وهذا يعمل على جميع المنابر بسبب HttpClient وإصلاحه في الطبيعة. I استخدام هذا الأسلوب نفسي على هاتف ويندوز 7/8 لخدمة مختلفة تماما.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top