Umer Pasha Blogs

www.umerpasha.com

C# dot net code to get latest tweets using twitter API 1.1

Twitter just recently retired their old API 1.0. The new API requires oAuth. Following code will help you jumpstart to write code in C# to get your tweets.

This is using dot net framework 4.0
I am also using NewtonSoft’s excellent JSON library. You can get it here. Use the dot net 4.0 library and add as a reference to your C# Web project.

You first have to create a twitter app here. Use the oAuth Tool tab to get the 4 tokens/codes that you will be replacing in the code below.


Default.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div id="myDiv" runat="server">
    
    </div>s
    </form>
</body>
</html>


Default.aspx.cs


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text;
using System.Security.Cryptography;
using System.Net;
using System.IO;
using Newtonsoft.Json.Linq;


public partial class _Default : System.Web.UI.Page
{


    public string query = "umerpasha";
//    public string url = "https://api.twitter.com/1.1/users/search.json" ;
    public string url = "https://api.twitter.com/1.1/statuses/user_timeline.json" ;


    protected void Page_Load(object sender, EventArgs e)
    {
        findUserTwitter(url, query);
    }

    public void findUserTwitter(string resource_url, string q)
    {

        // oauth application keys
        var oauth_token = "xxx"; //"insert here...";
        var oauth_token_secret = "xxx"; //"insert here...";
        var oauth_consumer_key = "xxx";// = "insert here...";
        var oauth_consumer_secret = "xxx";// = "insert here...";

        // oauth implementation details
        var oauth_version = "1.0";
        var oauth_signature_method = "HMAC-SHA1";

        // unique request details
        var oauth_nonce = Convert.ToBase64String(new ASCIIEncoding().GetBytes(DateTime.Now.Ticks.ToString()));
        var timeSpan = DateTime.UtcNow
            - new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
        var oauth_timestamp = Convert.ToInt64(timeSpan.TotalSeconds).ToString();


        // create oauth signature
        var baseFormat = "oauth_consumer_key={0}&oauth_nonce={1}&oauth_signature_method={2}" +
                        "&oauth_timestamp={3}&oauth_token={4}&oauth_version={5}&q={6}";

        var baseString = string.Format(baseFormat,
                                    oauth_consumer_key,
                                    oauth_nonce,
                                    oauth_signature_method,
                                    oauth_timestamp,
                                    oauth_token,
                                    oauth_version,
                                    Uri.EscapeDataString(q)
                                    );

        baseString = string.Concat("GET&", Uri.EscapeDataString(resource_url), "&", Uri.EscapeDataString(baseString));

        var compositeKey = string.Concat(Uri.EscapeDataString(oauth_consumer_secret),
                                "&", Uri.EscapeDataString(oauth_token_secret));

        string oauth_signature;
        using (HMACSHA1 hasher = new HMACSHA1(ASCIIEncoding.ASCII.GetBytes(compositeKey)))
        {
            oauth_signature = Convert.ToBase64String(
                hasher.ComputeHash(ASCIIEncoding.ASCII.GetBytes(baseString)));
        }

        // create the request header
        var headerFormat = "OAuth oauth_nonce=\"{0}\", oauth_signature_method=\"{1}\", " +
                           "oauth_timestamp=\"{2}\", oauth_consumer_key=\"{3}\", " +
                           "oauth_token=\"{4}\", oauth_signature=\"{5}\", " +
                           "oauth_version=\"{6}\"";

        var authHeader = string.Format(headerFormat,
                                Uri.EscapeDataString(oauth_nonce),
                                Uri.EscapeDataString(oauth_signature_method),
                                Uri.EscapeDataString(oauth_timestamp),
                                Uri.EscapeDataString(oauth_consumer_key),
                                Uri.EscapeDataString(oauth_token),
                                Uri.EscapeDataString(oauth_signature),
                                Uri.EscapeDataString(oauth_version)
                        );



        ServicePointManager.Expect100Continue = false;

        // make the request
        var postBody = "q=" + Uri.EscapeDataString(q);//
        resource_url += "?" + postBody ;
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(resource_url);
        request.Headers.Add("Authorization", authHeader);
        request.Method = "GET";
        request.ContentType = "application/x-www-form-urlencoded";
        var response = (HttpWebResponse)request.GetResponse();
        var reader = new StreamReader(response.GetResponseStream());
        var objText = reader.ReadToEnd();
        myDiv.InnerHtml = objText;/**/
        string html = "";
        try
        {
            JArray jsonDat = JArray.Parse(objText);
            for (int x = 0; x < jsonDat.Count(); x++)
            {
                //html += jsonDat[x]["id"].ToString() + "<br/>";
                html += jsonDat[x]["text"].ToString() + "<br/>";
               // html += jsonDat[x]["name"].ToString() + "<br/>";
                html += jsonDat[x]["created_at"].ToString() + "<br/>";

            }
            myDiv.InnerHtml = html;
        }
        catch (Exception twit_error)
        {
            myDiv.InnerHtml = html + twit_error.ToString();
        }
    }
}
96 Comments »

Using Adobe Omniture WebServices API in C# and showing data in Telerik grid and charts (Source Code included)

Here is the Source Code right up front: The C# Project File for Visual Studio 2008

If you have used Adobe Omniture Site Catalyst Web Services API, you will know what a hassle it is and how bad the documentation and technical support is. It took me a couple of weeks to reach this point. But that also included mastering a 3rd party grid and charting control from Telerik.

You will need to get a trial version of RadGrid from Telerik here which works for 90 days. You can also modify the attached code to just get the data and delete anything related to Telerik.

You will need to download MS Web Service Enhancement 3. You can get it here.

Make sure you get Web Service Access to the Enterprise API. Instructions are here.

You need to get your specific Site Catalyst WSDL. Here are the instructions. You will use this to add a web reference to your dot net project.

In the web.config, setup the SQL Server Connection String before running. I am storing the data I get from Omniture in SQL Server. I have not provided the SP code here. Mail me if you need help with that. You can remove all the SQL bits from code to not use that.

The project uses API 1.3 which is the latest as of now.

The project also shows getting custom conversion variables “eVar21”. if you are not using them, you can remove the code.


Some important links:

Getting started with Omniture API: https://developer.omniture.com/en_US

Reporting API Tutorial: https://developer.omniture.com/en_US/content_page/enterprise-api/c-reporting-api-tutorial

Leave a comment »