Click here to Skip to main content
15,881,967 members
Articles / Programming Languages / C#
Article

Simple One Page RestSharp Based Console Application for the Box.com Cloud Service

Rate me:
Please Sign up or sign in to vote.
0.00/5 (No votes)
8 Apr 2013LGPL33 min read 29.4K   480   6   2
This article describes how to use the RestSharp SDK to build an application for the Box.com Cloud service.

Introduction

The present article would be useful for developers who are going to the Box.com Cloud service for desktop applications and hesitating facing the number of available opportunities and already made contributions to 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! :)

This article continues the short how to series started with the DropBox explanation.

Background

Nowadays the Cloud service is something everyone wants to use. It looks simple and fast to join to the popular Cloud Group. Particular Cloud service providers 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 in which 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 Box.com and creating a Box.com application (i.e. obtaining the App key/App secret pair). You can read the instructions explaining these simple steps at the Box.com development resource here.

Using the Code

This article provides you with the complete Microsoft Visual Studio 2010 Express application that is able to get OAuth v2 Access Code, the user approval, the Access Token, and retrieve the user's account information as a regular sample of the Box.com 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 your 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 Access Code and Getting an Approval from a User for the Access

This step corresponds to the Authorize operation:

C#
//
// Get Authorization Code and an Approval from the User
//

var baseUrl = "https://www.box.com";

var client = new RestClient(baseUrl);

// Create a Callback URL
string sAuthorizationCallBackURL = string.Format(
    sLoopbackCallback,
    auth_GetRandomUnusedPort(), Assembly.GetEntryAssembly().GetName().Name
    );
    
var request = new RestRequest(
    string.Format(
    "/api/oauth2/authorize?response_type=code&client_id={0}&state=authenticated&redirect_uri={1}",
    mc_apiKey, sAuthorizationCallBackURL
    ), Method.POST);
    
bool bHasUserGrantedAccess = false;

var url = client.BuildUri(request).ToString();

// Set up a local HTTP server to accept authentication callback

string auth_code = null;
var resetEvent = new ManualResetEvent(false);
using (var svr = SimpleServer.Create(sAuthorizationCallBackURL, context =>
{
    var qs = HttpUtility.ParseQueryString(context.Request.RawUrl);
    auth_code = qs["code"];
    
    if (!string.IsNullOrEmpty(auth_code))
    {
        // The user has granted access
        bHasUserGrantedAccess = true;
    }
    
    // Resume execution...
    resetEvent.Set();
    
}))
{
    // Launch a default browser to get the user's approval
    System.Diagnostics.Process.Start(url);
    
    // Wait until the user decides whether to grant access
    resetEvent.WaitOne();    
}

if (false == bHasUserGrantedAccess)
{
    // The user has not granded access
    break;
}

string authorizationCode = auth_code;

Obtaining the Access Token:

This step corresponds to the Token operation:

C#
//
// Get Access Token
//

request = new RestRequest("/api/oauth2/token", Method.POST);

request.AddParameter("grant_type", "authorization_code");
request.AddParameter("code", authorizationCode);
request.AddParameter("client_id", mc_apiKey);
request.AddParameter("client_secret", mc_appsecret);

var response = client.Execute<AccessToken>(request);

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

// Extract the Access Token

// output parameter:
accessToken = response.Data;

if (string.IsNullOrEmpty(accessToken.access_token) ||
    string.IsNullOrEmpty(accessToken.refresh_token) ||
    (0 == accessToken.expires_in))
{
    break;
}

Getting the Access Token Refreshed (currently this procedure shall be repeated every hour despite the fact of actual service usage duration)

This step corresponds to the Token operation:

C#
	//
	// Refresh the access token (should be done if the 1 hour passed 
	// since the last access token has been obtained)
	//
	// Please not, the step refresh would fail in case the 1 hour has not passed
	// That is why the code has been cut using the preprocessor
	//

#if USE_REFRESH_TOKEN
	request = new RestRequest("/api/oauth2/token", Method.POST);

	request.AddParameter("grant_type", "refresh_token");
	request.AddParameter("code", accessToken.access_token);
	request.AddParameter("client_id", mc_apiKey);
	request.AddParameter("client_secret", mc_appsecret);
	request.AddParameter("refresh_token", accessToken.refresh_token);

	response = client.Execute<AccessToken>(request);
	
	if (response.StatusCode != System.Net.HttpStatusCode.OK)
	{
		break;
	}

	// Extract the Access Token

	// output parameter:
	accessToken = response.Data;

	if (string.IsNullOrEmpty(accessToken.access_token) ||
		string.IsNullOrEmpty(accessToken.refresh_token) ||
		(0 == accessToken.expires_in))
	{
		break;
	}

#endif // USE_REFRESH_TOKEN

Obtaining the User Account Information

This step corresponds to the Get the Current User’s Information operation:

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

baseUrl = "https://api.box.com";

client = new RestClient(baseUrl);

request = new RestRequest(string.Format("/{0}/users/me", mc_version), Method.GET);

request.AddParameter(
    "Authorization",
    string.Format("Bearer {0}", accessToken.access_token), ParameterType.HttpHeader);
    
var responseAccountInfo = client.Execute<AccountInfo>(request);

if (responseAccountInfo.StatusCode != System.Net.HttpStatusCode.OK)
{
    break;
}

AccountInfo accountInfo = responseAccountInfo.Data;

Console.WriteLine("Got access to the \"{0}\" account with ID=\"{1}\" and \"{2}\" e-mail. ",
    accountInfo.name,
    accountInfo.id,
    accountInfo.login);

Points of Interest

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

I hope my small and modest contribution will help other developers who are looking for such help.

Thanks

I would like to acknowledge contributions that stand as a background for this article:

History

  • 2013-04-05 Initial revision

License

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


Written By
Systems Engineer N/A
Ukraine Ukraine
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
QuestionNot working Pin
karan_one20-Sep-14 1:50
karan_one20-Sep-14 1:50 
AnswerRe: Not working Pin
boris_oleinic22-Sep-14 23:59
boris_oleinic22-Sep-14 23:59 

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.