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.
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:
var baseUrl = "https://www.box.com";
var client = new RestClient(baseUrl);
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();
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))
{
bHasUserGrantedAccess = true;
}
resetEvent.Set();
}))
{
System.Diagnostics.Process.Start(url);
resetEvent.WaitOne();
}
if (false == bHasUserGrantedAccess)
{
break;
}
string authorizationCode = auth_code;
Obtaining the Access Token:
This step corresponds to the Token operation:
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;
}
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:
#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;
}
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:
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