Friday, March 17, 2017

Twitter from C# .NET MVC..

 I wrote the Stock tracker application as mostly just a learning drill for Angular 1 and 2.
But I have found, it could be actually useful, with a touch of Twitter.

I find myself searching Twitter for charting,analysis, links, and just plain prognosticating by people, by searching the stock symbol preceded by "$".

So I set out to add some Twitter links to my site today.
There was a ton of helpful documentation by others already on the internet. Problem was the format and varying usage needs. I really needed to get the grunt work done in C# .NET. Some of the Gurus are using Node.js and other things, and some others were just making it harder than it needed for me to be.

What I wanted to end up with, and now have looks like this :




So the user can click the bird and see what has been tweeted about a company stock.

I would offer up that the heavy lifting is done by getting an OAuth token from Twitter first, and post that code for reference sake :

public string GetAuthToken()
        {

            string encodedKeyAndSecret = Convert.ToBase64String(
                new System.Text.UTF8Encoding().GetBytes(
                  ConsumerKey + ":" + ConsumerSecret));

            string urlToken = "https://api.twitter.com/oauth2/token";

            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(new Uri(urlToken));

            req.Headers.Add("Authorization","Basic " + encodedKeyAndSecret);
              
            req.ContentType = "application/x-www-form-urlencoded;charset=UTF-8";
            req.Method = "POST";

            string requestBody = "grant_type=client_credentials";

            Stream dataStream = req.GetRequestStream();

            byte[] byteArray = new System.Text.UTF8Encoding().GetBytes(requestBody);
            dataStream.Write(byteArray, 0, byteArray.Length);
            dataStream.Close();

            WebResponse response = req.GetResponse();

            string jsonResponse = "";

            using (var reader = new StreamReader(response.GetResponseStream()))
            {
               jsonResponse = reader.ReadToEnd();
            }

            TokenResponse t = 
                Newtonsoft.Json.JsonConvert.DeserializeObject(jsonResponse);
      
            return t.access_token;

        }

The rest of the act of querying Twitter is super easy to code, but can take some to get working, deserializing to something useable in your app, and then modeled by your classes and client-side objects.


No comments: