Click here to Skip to main content
15,888,286 members
Articles / Programming Languages / C#
Tip/Trick

Integrate Tumblr into C#.NET Website

Rate me:
Please Sign up or sign in to vote.
4.75/5 (4 votes)
16 Apr 2013CPOL4 min read 24.1K   582   5   2
A complete solution that seamlessly integrates Tumblr into your C# .NET website

Introduction

This application very easily integrates Tumblr with your application without wanting you to go deep into the OAuth complexities. OAuth is used to manage authorization & authentication. Thus, there's no need for the application to save or even know the user's Tumblr login credentials. Hence it is safe from user's perspective as well.

Background

Targeted for beginners who have no idea about how OAuth works, or C# syntax of making requests to Tumblr API. I started the same way and even after digging hard on the internet, could not find a working solution in C# that integrates Tumblr using OAuth.

Using the Code

This project does the following:

  1. Authenticates user on Tumblr
  2. Authorizes from user
  3. Creates a new post on the blog (After reading this tip, you would be able to do a lot more than just this.)

Follow instructions on Tumblr API documentation and register your application. The registration process is very easy. Let your application URL be where your website runs. Let us keep the localhost URL (Run your website to find this in your browser address bar. Example.: http://localhost:51432/SiteName/) for now. Enter something in redirect URL. I'll let you know what to enter there later. After saving the settings, you should see your app on

Download the code attached with this tip and add Helper.cs class file into your website. This class holds all the methods that we require. You need not go into much detail.

Next, add page Tumblr.aspx into your website from the code source.

Add to page a button (ID=btnAuthorize, Text="Authenticate & Authorize"), a timer, a scriptManager for the timer and a hidden field. Put in the following code:

C#
Helper requestHelper = new Helper(); 
protected void Page_Load(object sender, EventArgs e) 
{ 
Helper.TumblrConsumerKey = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"; //Your consumer 
	//key/client key provided by Tumblr after you register your application 
Helper.TumblrConsumerSecret = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"; //Your client 
	//secret provided by Tumblr after you register your application 
requestHelper.CallBackUrl = "http://localhost:51288/Pages/IntermediatePage.aspx"; //Your 
	//callback URL here. You should provide this in your application settings redirect URL 
if (!IsPostBack) 
{ 
hdnField.Value = requestHelper.GetAuthorizationLink(); 
} 
} 

Add the following script to Tumblr.aspx to open the Tumblr login page as a popup.

JavaScript
<script type="text/javascript"> 
function OpenTumblrWindow() { 
var txt = document.getElementById('hdnField'); 
var urlstring = txt.value; 
window.open(urlstring, '_blank', 'height=500,width=800,status=yes,
toolbar=no,menubar=no,location=no,scrollbars=yes,resizable=no,titlebar=no'); 
} 
</script> 

Call this on button click.

ASP.NET
<asp:Button runat="server" 
Text="Authorize" ID="btnAuthorize" 
OnClientClick="OpenTumblrWindow();" 
OnClick="btnAuthorize_Click" /> 
protected void btnAuthorize_Click(object sender, EventArgs e) 
{ 
timer.Enabled = true; //Start the timer 
} 

Now add to code Intermediate.cs public static class:

C#
public static class Intermediate 
{ 
public static string TumblrVerifier = string.Empty; //used to catch 
	//verifier code returned from API 
public static bool IsResponseReceived = false; 
} 

Now add IntermediatePage.aspx into your website and add the following script:

JavaScript
<script type="text/javascript"> 
function CloseSelf() { 
self.close(); 
} 
</script> 

In its code behind:

C#
protected void Page_Load(object sender, EventArgs e) 
{ 
Intermediate.TumblrVerifier = Request.QueryString["oauth_verifier"]; 
Intermediate.IsResponseReceived = true; 
ScriptManager.RegisterClientScriptBlock(this, typeof(string), 
"CloseSelf", "CloseSelf();", true); 
} 

Now, on your Tumblr website, login, go to URL http://www.tumblr.com/oauth/apps and into the redirect URL, type in the address for this page. Example: http://localhost:51432/SiteName/IntermediatePage.aspx .

Set requestHelper.CallBackUrl in your page load event for Tumblr.aspx to this value as well.

Now, run your website, the following sequence of actions occur.

  1. Tumblr.aspx page load sets appropriate value for hidden field. Here, behind the scenes, using your client secret & client token, we make a request to receive request tokens and authorize the application using user intervention.
  2. Click on 'Authenticate & Authorize' to open popup window. If you are not signed in, Login to Tumblr using your credentials. The application asks you to grant access. click on 'Allow'. Tumblr now redirects you to your redirect URL, in our case http://localhost:51432/SiteName/IntermediatePage.aspx
  3. TumblrVerifier in Intermediate gets set. We have the verifier code with us now. JavaScript closes the popup window.

Now, we need to make Tumblr.aspx know that we are having the code with us now. Add button (ID="btnPost", Text="Post Blog" and a label (ID="lblSuccess")). Please write the below code for its timer tick event.

Clicking on btnAuthorize enables the timer & it keeps checking if the code is received in Intermediate.TumblrVerifier. In case of any error, verifier won't be received. So we set IsResponseReceived to deal with this case which indicates that some response has been received; disable the timer.

C#
//Add tick event for timer on Tumblr.aspx 
protected void timer_Tick1(object sender, EventArgs e) 
{ 
if (!String.IsNullOrEmpty(Intermediate.TumblrVerifier)) 
{ 
btnPost.Visible = true; 
lblSuccess.Visible = true; 
timer.Enabled = false; 
lblSuccess.Text = "Authentication Successful.."; 
} 
else if (Intermediate.IsResponseReceived) 
{ 
lblSuccess.Text = "User denied access"; 
lblSuccess.Visible = true; 
timer.Enabled = false; 
Intermediate.IsResponseReceived = false; 
} 
} 

Now, for posting blog, add 2 textboxes, one for blog title and the other for blog content. in the btnPost click event:

C#
protected void btnPost_Click(object sender, EventArgs e) 
{ 
try 
{ 
string AccessTokenResponse = requestHelper.GetAccessToken
	(Helper.TumblrToken, Intermediate.TumblrVerifier); 
string[] tokens = AccessTokenResponse.Split('&'); //extract access 
		//token & secret from response 
string accessToken = tokens[0].Split('=')[1]; 
string accessTokenSecret = tokens[1].Split('=')[1]; 
KeyValuePair<string, string> LoginDetails = new KeyValuePair
<string, string>(accessToken, accessTokenSecret); 
var url2 = "http://api.tumblr.com/v2/user/dashboard"; 
//extract default blog URL for posting 
string BLOGURL = Helper.OAuthData(url2, "GET", 
LoginDetails.Key, LoginDetails.Value, null); 
BLOGURL = BLOGURL.Substring(BLOGURL.IndexOf("post_url") + 10, 
BLOGURL.IndexOf("slug") - BLOGURL.IndexOf("post_url") - 10); 
BLOGURL = BLOGURL.Replace("http:", "").
Replace("\"", "").Replace("/", "").
Replace("\\", "").Trim(); 
BLOGURL = BLOGURL.Substring(0, BLOGURL.IndexOf(".com") + 4); 
//Pass required parameters 
var prms = new Dictionary<string, object>(); 
prms.Add("type", "text"); 
prms.Add("title", txtBlogTitle.Text); 
prms.Add("body", txtBlogContent.Text); 
var postUrl2 = "http://api.tumblr.com/v2/blog/" + 
BLOGURL + "/post"; 
string result = Helper.OAuthData(postUrl2, "POST", 
LoginDetails.Key, LoginDetails.Value, prms); 
lblSuccess.Text = result; //this returns status 200 and 'Created' if success 
} 
catch (WebException ex) 
{ 
if (ex.Response is HttpWebResponse && ex.Response != null) 
{ 
StreamReader exReader = new StreamReader(ex.Response.GetResponseStream()); 
lblSuccess.Text = exReader.ReadToEnd(); 
} 
} 
} 

This is it! After making your website live, you can change the application URL and callback URL into Tumblr app settings accordingly.

For using other functionality that suits your need, you just have to use relevant URLs of tumblr API.

Points of Interest

It was quite annoying as I was not able to make OAuth work even after days of work put in. It was a pure trial and error process which I got stuck in getting access token and thereafter in making suitable requests to the API. The mistake I was making was in passing appropriate authentication header with the request. Got it working finally.

References

History

  • 16th April, 2013: Initial version

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer TatvaSoft
India India
http://www.tatvasoft.com

Comments and Discussions

 
GeneralMy vote of 5 Pin
Jawand Singh Virk25-Apr-17 0:01
Jawand Singh Virk25-Apr-17 0:01 
SuggestionProblem with getting blogurl using http://api.tumblr.com/v2/user/dashboard Pin
Shane Goodson21-May-14 1:15
Shane Goodson21-May-14 1:15 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.