Using Twitter API via .NET

Objective :

In this post i will quickly explain how can we interact with Twitter API using .Net code.

Ingredients :

LinqToTwitter , Visual Studio 2010

Recipe :

You may find several popular Dlls on internet that communicate with Twitter. I have used LinqToTwitter & have found it easy to understand & implement.

You need to have “twitterConsumerKey” & “twitterConsumerSecret” that you will use from within your application. Get your applications twitter credentials from https://dev.twitter.com/apps

Our application URL will be like “http://localhost:PortNumber” but once you are on Twitter Applications settings Form : It does not validate¬†“http://localhost:PortNumber” , therefore an alternate is to use “http://127.0.0.1:PortNumber” as our website placeholder. it will serve our purpose. Twitter uses this fully qualified URL in the source attribution for tweets created by your application and it be shown in user-facing authorization screens.

.NET code

Create a simple Asp.net web application in visual studio 2010.

Web.Config Changes

Add following in your web.config appSettings

<add key="twitterConsumerKey" value="twitterConsumerKey"/><add key="twitterConsumerSecret" value="twitterConsumerSecret"/>

Namespace

Add following namespace in your code file.

using LinqToTwitter;

Code

I used following code to explore Search feature & User Context.

private WebAuthorizer auth; private TwitterContext twitterCtx;

protected void Page_Load(object sender, EventArgs e)

{

IOAuthCredentials credentials = new SessionStateCredentials();

if (credentials.ConsumerKey == null || credentials.ConsumerSecret == null)

{

credentials.ConsumerKey = ConfigurationManager.AppSettings["twitterConsumerKey"];

credentials.ConsumerSecret = ConfigurationManager.AppSettings["twitterConsumerSecret"];

}

auth = new WebAuthorizer

{

Credentials = credentials,

PerformRedirect = authUrl => Response.Redirect(authUrl)

};

if (!Page.IsPostBack && Request.QueryString["oauth_token"] != null)

{

auth.CompleteAuthorization(Request.Url);

}

if (string.IsNullOrWhiteSpace(credentials.ConsumerKey) ||

string.IsNullOrWhiteSpace(credentials.ConsumerSecret))

{

//Do nothing

}

else if (auth.IsAuthorized)

{

//Do nothing

}

else

{

auth.BeginAuthorization(Request.Url);

if (!auth.IsAuthorized)

{

Uri specialUri = new Uri(Request.Url.ToString());

auth.BeginAuthorization(specialUri);

}

}

if (auth.IsAuthorized)

{

twitterCtx = new TwitterContext(auth);

#region Search Text

var searchResult =

(from srch in twitterCtx.Search

where srch.Type == SearchType.Search &&

srch.Query == "Brian Adams"

select srch)

.SingleOrDefault();

gvTweetView.DataSource = searchResult.Statuses;

gvTweetView.DataBind();

#endregion

#region UserInfo

var users =

(from user in twitterCtx.User

where user.Type == UserType.Lookup &&

user.ScreenName == "prosarfraz"

select user);

string strHtml = string.Empty;

foreach (User objUser in users)

{

strHtml += "";

strHtml += " Screen Name ";

strHtml += "" + objUser.ScreenName + "";

strHtml += " Favorites Count ";

strHtml += "" + objUser.FavoritesCount + "";

strHtml += " Followers ";

strHtml += "" + objUser.FollowersCount + "";

strHtml += " Description ";

strHtml += "" + objUser.Description + "";

strHtml += "";

}

ulsrc.InnerHtml = "" + strHtml + "";
<p style="padding-left: 60px;">#endregion}}

Executing this code will redirect the web page user to twitter authentication page. One you authorize from your twitter account it will redirect you back to the application page to process #SearchResult & #UserInfo regions.

I hope this has provided you a quick insight on how to connect to Twitter Api using C# code.

About these ads

Tagged: , , , ,

7 thoughts on “Using Twitter API via .NET

  1. Kamran Shahid April 11, 2013 at 11:36 Reply

    Hi Sarfraz,
    For twitter consumer key I am trying to create a application there.
    But at the moment i doesn’t have the website url and whatever i placed in the website [as place holder] it is rejected.do you know what(pattern of data) to put in website as place holder?

    • Kamran Shahid April 11, 2013 at 12:17 Reply

      Put https://twitter.com/XXXXXXX and got some consumer key and Consumer secret
      In Aspx page put one gridview and div with the ids mentioned in the code and able to compile the application.
      but got error at the line auth.BeginAuthorization(Request.Url);
      The remote server returned an error: (401) Unauthorized.

      • Sarfraz Ahmed Khan April 11, 2013 at 20:14

        try “http://127.0.0.1:PortNumber”, by website placeholder You are telling your twitter application that Hey this URL will send u the request to authenticate.
        & Callback URL value is the url where Twitter Page should land back after authorization. You can can use “http://127.0.0.1:applicationPortnumber/yourPageName”.

    • Sarfraz Ahmed Khan April 11, 2013 at 20:10 Reply

      Our application URL will be like “http://localhost:PortNumber” but once you are on Twitter Applications settings Form : It does not validate “http://localhost:8085″ , therefore an alternate is to use “http://127.0.0.1:PortNumber” as our website placeholder. it will serve our purpose.

      • Kamran Shahid April 11, 2013 at 21:33

        Thanks Sarfraz.Will try it

  2. Miguel August 2, 2013 at 03:13 Reply

    Hi Sarfraz
    My website gerates an error with ulrc: The name ‘ulsrc’ does not exist in the current context
    Do you like to help me? what is ‘ulsrc’?

    • Sarfraz Ahmed Khan August 6, 2013 at 08:57 Reply

      ulSrc
      A unsigned long value to be copied into the new _variant_t object.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: