Samples in C# .NET


#1

Hi all,

I’m newbie using Twitter. I use .NET C#. Visual Studio 2013.

Any full source code samples applications in C# using REST API Twitter?

IMHO, better samples for minimize learning curve are real applications with full source code and good patterns

Any good getting started with it ? Quick Start- Getting Started step by step in 10 minutes?

Thx.


#2
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;
using System.Security.Cryptography;

namespace Twitter
{
    class Program
    {
        static void Main(string[] args)
        {
            string consumerKey = ...;
            string consumerSecret = ...;
            string accessToken = ...;
            string accessTokenSecret = ...;

            string URL = "https://api.twitter.com/1.1/search/tweets.json";
            Dictionary<string, string> parameters = new Dictionary<string, string>() { { "q", "zzz" } };

            WebRequest request = CreateRequest(
                consumerKey, consumerSecret, accessToken, accessTokenSecret,
                "GET", URL, parameters);

            using (WebResponse response = request.GetResponse())
            {
                using (Stream stream = response.GetResponseStream())
                {
                    using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
                    {
                        Console.Write(reader.ReadToEnd());
                    }
                }
            }
        }

        static public WebRequest CreateRequest(
            string consumerKey, string consumerSecret, string accessToken, string accessKey, 
            string method, string url, Dictionary<string, string> parameters)
        {
            string encodedParams = EncodeParameters(parameters);

            WebRequest request;
            if (method == "GET")
                request = WebRequest.Create(string.Format("{0}?{1}", url, encodedParams));
            else
                request = WebRequest.Create(url);

            request.Method = method;
            request.ContentType = "application/x-www-form-urlencoded";
            request.Headers.Add(
                "Authorization", 
                MakeOAuthHeader(consumerKey, consumerSecret, accessToken, accessKey, method, url, parameters));

            if (method == "POST")
            {
                byte[] postBody = new ASCIIEncoding().GetBytes(encodedParams);
                using (Stream stream = request.GetRequestStream())
                {
                    stream.Write(postBody, 0, postBody.Length);
                }
            }

            return request;
        }

        static string EncodeParameters(Dictionary<string, string> parameters)
        {
            if (parameters.Count == 0)
                return string.Empty;
            Dictionary<string, string>.KeyCollection.Enumerator keys = parameters.Keys.GetEnumerator();
            keys.MoveNext();
            StringBuilder sb = new StringBuilder(
                string.Format("{0}={1}", keys.Current, Uri.EscapeDataString(parameters[keys.Current])));
            while (keys.MoveNext())
                sb.AppendFormat("&{0}={1}", keys.Current, Uri.EscapeDataString(parameters[keys.Current]));
            return sb.ToString();
        }

        static string MakeOAuthHeader(string consumerKey, string consumerSecret, string accessToken, string accessKey, 
            string method, string url, Dictionary<string, string> parameters)
        {
            TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);

            string oauth_consumer_key = consumerKey;
            string oauth_nonce = Convert.ToBase64String(new ASCIIEncoding().GetBytes(DateTime.Now.Ticks.ToString()));
            string oauth_signature_method = "HMAC-SHA1";
            string oauth_token = accessToken;
            string oauth_timestamp = Convert.ToInt64(ts.TotalSeconds).ToString();
            string oauth_version = "1.0";

            SortedDictionary<string, string> sd = new SortedDictionary<string, string>();
            if (parameters != null)
                foreach (string key in parameters.Keys)
                    sd.Add(key, Uri.EscapeDataString(parameters[key]));
            sd.Add("oauth_version", oauth_version);
            sd.Add("oauth_consumer_key", oauth_consumer_key);
            sd.Add("oauth_nonce", oauth_nonce);
            sd.Add("oauth_signature_method", oauth_signature_method);
            sd.Add("oauth_timestamp", oauth_timestamp);
            sd.Add("oauth_token", oauth_token);

            StringBuilder sb = new StringBuilder();
            sb.AppendFormat("{0}&{1}&", method, Uri.EscapeDataString(url));
            foreach (KeyValuePair<string, string> entry in sd)
                sb.Append(Uri.EscapeDataString(string.Format("{0}={1}&", entry.Key, entry.Value)));
            string baseString = sb.ToString().Substring(0, sb.Length - 3);

            string oauth_token_secret = accessKey;
            string signingKey = string.Format(
                "{0}&{1}", Uri.EscapeDataString(consumerSecret), Uri.EscapeDataString(oauth_token_secret));
            HMACSHA1 hasher = new HMACSHA1(new ASCIIEncoding().GetBytes(signingKey));
            string oauth_signature = Convert.ToBase64String(hasher.ComputeHash(new ASCIIEncoding().GetBytes(baseString)));

            sb = new StringBuilder("OAuth ");
            sb.AppendFormat("oauth_consumer_key=\"{0}\",", Uri.EscapeDataString(oauth_consumer_key));
            sb.AppendFormat("oauth_nonce=\"{0}\",", Uri.EscapeDataString(oauth_nonce));
            sb.AppendFormat("oauth_signature=\"{0}\",", Uri.EscapeDataString(oauth_signature));
            sb.AppendFormat("oauth_signature_method=\"{0}\",", Uri.EscapeDataString(oauth_signature_method));
            sb.AppendFormat("oauth_timestamp=\"{0}\",", Uri.EscapeDataString(oauth_timestamp));
            sb.AppendFormat("oauth_token=\"{0}\",", Uri.EscapeDataString(oauth_token));
            sb.AppendFormat("oauth_version=\"{0}\"", Uri.EscapeDataString(oauth_version));

            return sb.ToString();
        }
    }
}

#3

Great

Suggestion from newbie: Wiki with more useful samples using C# and Twitter.

Suggestion 2 from newbie: How-to for get values for ConsumerKey and AccessToken.

I have create a TestMethod. Only I need generate consumer and accesstoken values. I will find help in forums, SO, and other.

     [TestMethod]
             public void Get_tweets_is_ok()
            {
                 string consumerKey = "...";
                string consumerSecret = "...";
                string accessToken = "...";
                string accessTokenSecret = "...";
    
                string URL = "https://api.twitter.com/1.1/search/tweets.json";
                Dictionary<string, string> parameters = new Dictionary<string, string>() { { "q", "zzz" } };
    
                WebRequest request = TwitterHelper.CreateRequest(
                    consumerKey, consumerSecret, accessToken, accessTokenSecret,
                    "GET", URL, parameters);
    
                using (WebResponse response = request.GetResponse())
                {
                    using (Stream stream = response.GetResponseStream())
                    {
                        using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
                        {
                            Console.Write(reader.ReadToEnd());
                        }
                    }
                }
    
            }

#4

Thanks for the suggestion! Actually we share code samples on the TwitterDev organisation on Github, but I’ve not checked to see whether we have anything in C# yet!


#5

It would be great full source code samples in C#.


#6

Several of the libraries for .NET listed on our Libraries page contain code samples.


#7

For .NET, I have not seen many samples official Twitter:

2 API: TweetSharp vs Tweetmoasharp
https://github.com/danielcrenna/tweetsharp

Mindly notes:

Any good getting started with it? step by step in 10 minutes?

IMHO, better samples for minimize learning curve are real applications with full source code and good patterns and practices

Full source code sample REAL application? not Demo, only real applications?
Like for small to medium applications development, but open source, if you can sharing or maybe another real project or production-ready application using.

main influences, are full of innovative ideas that can free our minds to explore new techniques, patterns and paradigms.

You want to use technologies that allow for rapid development, constant iteration, maximal efficiency, speed, robustness and more. You want to be lean and you want to be agile. You want to use technologies that will help you succeed in the short and long term. And those technologies are not always easy to pick out.


#8

i am using Uri.EscapeDataString to encode :frowning: but it fails to encode , it only encodes : character. any one can help how to get :frowning: or :slight_smile: sentiments using search api with c#.net