Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / HTTPS

Simple one page RestSharp based console application for the DropBox Cloud service

4.60/5 (3 votes)
28 Mar 2013LGPL32 min read 42.5K   890  
The article describes how to use the RestSharp SDK to build an application for the DropBox Cloud service.

Introduction

The present articles would be useful for developers who is going to the DropBox Cloud service for the desktop application and hesitating facing with number of available opportunities and already made contributions to the His Majesty WWW. If you, this article reader, are the one then the simple and easy to "copy and paste" code is waiting for you! Smile | :)

Background

Now days the Cloud service is something everyone wants to use. It looks simple and fast to join to the popular Cloud Group. Particular Cloud service provider's Documentation pages usually contain plenty of information and due to the distributed nature of the Clouds often specify a custom REST style API. Such specification is well enough to understand number of features that the service provider offers but does not make us closer to the real implementation using any regular development tools and modern programming languages.

The RestSharp SDK offers plenty of already implemented features like OAuth v1 and OAuth v2 protocols, REST protocol, and many more and even provides us with a skeleton of the way how to use the RestSharp SDK in native style.

Before the application studying and usage please make sure that you have already passed the following steps: registering to the DropBox and creating a DropBox application (i.e. obtaining the App key/App secret pair). You can read instruction explaining these simple steps at the DropBox development resource here.

Using the code

The article provides you with the complete MS Visual Studio 2010 Express application that is able to get OAuth v1 Request token, the user approval, the Access token, and retrieve the user's account information as an regular sample of the DropBox service usage.

Let us go step by step through the most interesting parts of the application.

Configuring the application

Put the App key/App secret pair you have obtained to the constant string below. This is an important step and it is the only fragment of code that needs you contribution to make it actual and valid

C#
private const string mc_apiKey = "YOUR_API_KEY";
private const string mc_appsecret = "YOUR_APP_SECRET";

Obtaining the Request Token

This step corresponds to the /oauth/request_token operation:

C#
//
// Get request token
//

var baseUrl = "https://api.dropbox.com";

var client = new RestClient(baseUrl);
client.Authenticator = OAuth1Authenticator.ForRequestToken(mc_apiKey, mc_appsecret);
var request = new RestRequest(string.Format("/{0}/oauth/request_token", mc_version), Method.POST);

var response = client.Execute(request);

if (response.StatusCode != HttpStatusCode.OK)
{
    break;
}

OAuthToken requestToken = new OAuthToken();
{
    var qs = HttpUtility.ParseQueryString(response.Content);
    var oauth_token = qs["oauth_token"];
    var oauth_token_secret = qs["oauth_token_secret"];

    requestToken.Token = oauth_token;
    requestToken.Secret = oauth_token_secret;
}

Getting an approval from an user for the access

This step corresponds to the /oauth/authorize operation:

C#
//
// Get approval from user for the access
//

// Create a HttpListener for the specified url.
string AuthorizationCallBackURL = string.Format(LoopbackCallback, 
  auth_GetRandomUnusedPort(), Assembly.GetEntryAssembly().GetName().Name);


request = new RestRequest(string.Format("/{0}/oauth/authorize", mc_version));
request.AddParameter("oauth_token", requestToken.Token);
request.AddParameter("oauth_callback", AuthorizationCallBackURL);
var url = client.BuildUri(request).ToString();

bool bUserAcceptedRequest = false;

var resetEvent = new ManualResetEvent(false);
using (var svr = SimpleServer.Create(AuthorizationCallBackURL, context =>
{
    string uid = context.Request.QueryString["uid"];
    string code = context.Request.QueryString["oauth_token"];

    if (!string.IsNullOrEmpty(uid) && !string.IsNullOrEmpty(code))
    {
        bUserAcceptedRequest = true;
    }
    resetEvent.Set();

}))
{
    System.Diagnostics.Process.Start(url);

    resetEvent.WaitOne();

}

if (false == bUserAcceptedRequest)
{
    break;
}

Obtaining the Access Token

This step corresponds to the /oauth/access_token operation:

C#
//
// Get access token
//

var verifier = "123456";
request = new RestRequest(string.Format("/{0}/oauth/access_token", mc_version), Method.POST);
client.Authenticator = OAuth1Authenticator.ForAccessToken(
mc_apiKey, mc_appsecret, requestToken.Token, requestToken.Secret, verifier
);
response = client.Execute(request);

if (response.StatusCode != HttpStatusCode.OK)
{
    break;
}

accessToken = new OAuthToken();
{
    var qs = HttpUtility.ParseQueryString(response.Content);
    var oauth_token = qs["oauth_token"];
    var oauth_token_secret = qs["oauth_token_secret"];

    accessToken.Token = oauth_token;
    accessToken.Secret = oauth_token_secret;
}

Obtaining the user Account Information

This step corresponds to the /account/info operation:

C#
//
// Below is a sample how to access any DropBox service regular using the valid access token
//

request = new RestRequest(string.Format("/{0}/account/info", mc_version));
client.Authenticator = OAuth1Authenticator.ForProtectedResource(
mc_apiKey, mc_appsecret, accessToken.Token, accessToken.Secret
);

var responseAccount = client.Execute<AccountInfo>(request);

if (responseAccount.StatusCode != HttpStatusCode.OK)
{
    break;
}

AccountInfo acntInfo = responseAccount.Data;
if (null == acntInfo)
{
    break;
}

Console.WriteLine("First step tokens: token:{0} secret:{1}", requestToken.Token, requestToken.Secret);
Console.WriteLine("Second step tokens: token:{0} secret:{1}", accessToken.Token, accessToken.Secret);
Console.WriteLine("Account Info: {0}", responseAccount.Content);

Points of Interest

The main goal of the article is to equip a C# developer with complete reference application to speed up process of finding out with how it works, what to start with, and how to get it working Smile | :)

Let my small and modest contribution to help other developers who is looking for such aid.

Thanks

I would like to tell good words regarding contributions that stand as a background for this article:

History

  • 2013-03-28: Initial revision.

License

This article, along with any associated source code and files, is licensed under The GNU Lesser General Public License (LGPLv3)