Click here to Skip to main content
14,029,033 members
Click here to Skip to main content
Add your own
alternative version


6 bookmarked
Posted 8 Apr 2013
Licenced LGPL3

Simple One Page RestSharp Based Console Application for the Cloud Service

, 8 Apr 2013
Rate this:
Please Sign up or sign in to vote.
The article describes how to use the RestSharp SDK to build an application for the Cloud service

This series of articles would be useful for developers who are going to use the 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.


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 and creating a application (i.e. obtaining the App key/App secret pair). You can read instruction explaining these simple steps at the 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 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

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:

// Get Authorization Code and an Approval from the User

var baseUrl = "";

var client = new RestClient(baseUrl);

// Create a Callback URL
string sAuthorizationCallBackURL = string.Format(
    auth_GetRandomUnusedPort(), Assembly.GetEntryAssembly().GetName().Name

var request = new RestRequest(
    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...

    // Launch a default browser to get the user's approval

    // Wait until the user decides whether to grant access


if (false == bHasUserGrantedAccess)
    // The user has not granded access

string authorizationCode = auth_code;

Obtaining the Access Token

This step corresponds to the Token operation:

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

// Extract the Access Token

// output parameter:
accessToken = response.Data;

if (string.IsNullOrEmpty(accessToken.access_token) ||
    string.IsNullOrEmpty(accessToken.refresh_token) ||
    (0 == accessToken.expires_in))

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:

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

                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)

                // Extract the Access Token

                // output parameter:
                accessToken = response.Data;

                if (string.IsNullOrEmpty(accessToken.access_token) ||
                    string.IsNullOrEmpty(accessToken.refresh_token) ||
                    (0 == accessToken.expires_in))

#endif // USE_REFRESH_TOKEN</accesstoken>

Obtaining the user Account Information

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

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

baseUrl = "";

client = new RestClient(baseUrl);

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

    string.Format("Bearer {0}", accessToken.access_token), ParameterType.HttpHeader);

var responseAccountInfo = client.Execute<accountinfo>(request);

if (responseAccountInfo.StatusCode != System.Net.HttpStatusCode.OK)

AccountInfo accountInfo = responseAccountInfo.Data;

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

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.


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


2013-04-05 Initial revision


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


About the Author

United States United States
No Biography provided

You may also be interested in...


Comments and Discussions

Questionredirect_uri Pin
Member 433659414-Jun-15 1:38
memberMember 433659414-Jun-15 1:38 
AnswerRe: redirect_uri Pin
boris_oleinic2-Mar-18 21:02
memberboris_oleinic2-Mar-18 21:02 
GeneralVery Good & Usefull article Pin
ayyappanit17-Feb-14 3:02
memberayyappanit17-Feb-14 3:02 
AnswerRe: Very Good & Usefull article Pin
boris_oleinic17-Feb-14 3:14
memberboris_oleinic17-Feb-14 3:14 

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.

Permalink | Advertise | Privacy | Cookies | Terms of Use | Mobile
Web06 | 2.8.190419.4 | Last Updated 8 Apr 2013
Article Copyright 2013 by boris_oleinic
Everything else Copyright © CodeProject, 1999-2019
Layout: fixed | fluid