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

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

0.00/5 (No votes)
8 Apr 2013LGPL33 min read 28.7K   595  
The article describes how to use the RestSharp SDK to build an application for the Box.com Cloud service

This series of articles would be useful for developers who are going to use the Box.com Cloud service for their desktop applications, but are hesitating because they are faced with a number of available opportunities and have already made contributions to the His Majesty WWW. If you, this article reader, are the one then the simple and easy "copy and paste" code is waiting for you! :)

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

Background

These days the Cloud service is something everyone wants to use. It seems like it's 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 to use the RestSharp SDK in a 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 instruction explaining these simple steps at the Box.com 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 v2 Access Code, the user approval, the Access Token, and retrieve the user's account information as an 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 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 Access Code and Getting an Approval from an 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 authetization 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;
}</accesstoken>

Getting the 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</accesstoken>

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);</accountinfo>

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 :)

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-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)