• Skip to main content
  • Skip to primary sidebar
  • Skip to secondary sidebar
  • Skip to footer

Coding Still

  • Home
  • About

Use Dropbox with your ASP.NET application

November 7, 2013 By _tasos 21 Comments

In this article we will see how we can use Dropbox in a ASP.NET application. We will implement the basic functions of a file manager. Since there is no official SDK for .NET, we will use the HigLabo library for our interaction with the Dropbox API.

1. Setup

First, we need to create an application in our dropbox account. Go to the App Console in the Dropbox website and there you can create an application. This will be the application your users authorize their Dropbox account to.

There you have two options, and for our scenario we choose Dropbox API app, then choose Files and DataStores. There you choose whether your Dropbox application needs to have a specific folder or have access to all files. Finally give a name to your application.

2. Authorization

Creating the application in the App Console generates an App key and an App secret. We can use those to create an Authorize Url so that when our users click it they will be redirected to the Dropbox website and authorize their account with out app.

using HigLabo.Net;
using HigLabo.Net.Dropbox;
 
private const string App_key = "dropbox_app_key";
private const string App_secret = "dropbox_app_secret";
 
OAuthClient ocl = null;
HigLabo.Net.AuthorizeInfo ai = null;
 
ocl = DropboxClient.CreateOAuthClient(App_key, App_secret);
ai = ocl.GetAuthorizeInfo();
 
string RequestToken= ai.RequestToken;
string RequestTokenSecret= ai.RequestTokenSecret;
string redirect_url = ai.AuthorizeUrl;

When generating the url, also two request tokens are created (RequestToken and RequestTokenSecret) that you get them before the user does anything. When the user finally authorizes your application, those 2 request tokens are activated and can be used to get the actual 2 token that you can use them to initialize the DropBoxClient class.

// After the user has authorized our app to his account
AccessTokenInfo t = ocl.GetAccessToken(RequestToken, RequestTokenSecret);
 
string Token= t.Token;
string TokenSecret= ai.TokenSecret;

You need to keep those two values in your database and use them for this specific user.

3. Browsing and managing files

Browsing the files is very simple, you need to set two basic parameters. One is the path of the folder you are trying to browse. The second property depends whether your Dropbox application has full access to the Dropbox or it has its own private folder.

public List Contents(string path) 
{
    DropboxClient cl = new DropboxClient(App_key, App_secret, Token, TokenSecret);
 
    HigLabo.Net.Dropbox.GetMetadataCommand gmc = new HigLabo.Net.Dropbox.GetMetadataCommand();
    gmc.Root = RootFolder.Dropbox; //Our Dropbox app has access to the root of the user's Dropbox 
    gmc.Path = path;
 
    Metadata md = cl.GetMetadata(gmc);
    return md.Contents;
}
 
public void DeleteFile(string file)
{
    DropboxClient cl = new DropboxClient(App_key, App_secret, Token, TokenSecret);
 
    HigLabo.Net.Dropbox.DeleteCommand delcom = new HigLabo.Net.Dropbox.DeleteCommand();
    delcom.Root = RootFolder.Dropbox;
    delcom.Path = file;
 
    Metadata md = cl.Delete(delcom);
}
 
public void RenameFile(string from_path, string to_path)
{
    DropboxClient cl = new DropboxClient(App_key, App_secret, Token, TokenSecret);
 
    HigLabo.Net.Dropbox.MoveFileCommand mvcom = new HigLabo.Net.Dropbox.MoveFileCommand();
    mvcom.Root = RootFolder.Dropbox;
    mvcom.FromPath = from_path;
    mvcom.ToPath = to_path;
 
    Metadata md = cl.MoveFile(mvcom);
}

Deleting and moving a file has some other parameters, which are really simple to get. Those 2 actions, work also with folders.

4. Downloading and uploading files

To download the file, first your web application downloads the file and then sends it to the user. To upload a file, you first need to upload the file to your web server, and then you send the file to Dropbox.
Both actions can be a bit tricky with big files, since a timeout could occur.

public void DownloadFile(string path)
{
    DropboxClient cl = new DropboxClient(App_key, App_secret, Token, TokenSecret);
 
    HigLabo.Net.Dropbox.GetFileCommand dl = new HigLabo.Net.Dropbox.GetFileCommand();
    dl.Root = RootFolder.Dropbox;
    dl.Path = path;
 
    Byte[] bytes = cl.GetFile(dl);
 
    System.Web.HttpResponse response = HttpContext.Current.Response;
 
    response.Clear();
    response.AddHeader("Content-Disposition", "attachment; filename=" + path.Substring(path.LastIndexOf("/") + 1););
    response.AddHeader("Content-Length", bytes.Length.ToString());
    response.ContentType = "application/octet-stream";
    response.BinaryWrite(bytes);
    response.End();
    response.Close();
}
 
public void UploadFile(byte[] content, string filename, string target)
{
    DropboxClient cl = new DropboxClient(App_key, App_secret, Token, TokenSecret);
 
    HigLabo.Net.Dropbox.UploadFileCommand ul = new HigLabo.Net.Dropbox.UploadFileCommand();
    ul.Root = RootFolder.Sandbox;
    ul.FolderPath = target;
    ul.FileName = filename;
    ul.LoadFileData(content);
 
    Metadata md = cl.UploadFile(ul);
}

Finally, if you have an ASP.NET MVC application, you can check this page to see how to make a very nice upload process for your users. If you have a Web Forms application you can also find useful the JavaScript part.

Note 1: This article was written with the 1.3.2 version of the Higlabo library. The 1.3.2 version uses the v1 API of Dropbox which is currently retired.

Note 2: The current version of Higlabo does not have support for Dropbox.

Filed Under: .NET Development, ASP.NET Tagged With: ASP.NET MVC, ASP.NET Web Forms, HigLabo

Reader Interactions

Comments

  1. Mifl says

    May 4, 2014 at 15:12

    Hi,

    When I try to use the library the following error is thrown when ocl.GetAuthorizeInfo() is called. Please help me resolve this issue.

    var ocl = DropboxClient.CreateOAuthClient(App_key, App_secret);
    __ var ai = ocl.GetAuthorizeInfo();__

    [ArgumentNullException: Value cannot be null.
    Parameter name: value]
    System.Net.HttpWebRequest.set_ClientCertificates(X509CertificateCollection value) +2234270
    HigLabo.Net.HttpClient.CreateRequest(HttpRequestCommand command) +228
    HigLabo.Net.HttpClient.GetHttpWebResponse(HttpRequestCommand command) +38
    HigLabo.Net.HttpClient.GetResponse(HttpRequestCommand command) +36
    HigLabo.Net.OAuthClient.GetAuthorizeInfo() +176
    CapaDrop._Default.Button1_Click(Object sender, EventArgs e) in C:\Freelance\capa\Project\trunk\CapaDropbox\CapaDrop\CapaDrop\Default.aspx.cs:33
    System.Web.UI.WebControls.Button.OnClick(EventArgs e) +9752490
    System.Web.UI.WebControls.Button.RaisePostBackEvent(String eventArgument) +196
    System.Web.UI.WebControls.Button.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument) +10
    System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument) +13
    System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData) +35
    System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +1724

    Reply
  2. _tasos says

    May 5, 2014 at 20:49

    Hello Mifl
    The error message indicates that either the App_Key and or the App_secret variables have a null value. Make sure you have set these values correctly.

    Reply
  3. Raghu says

    May 15, 2014 at 10:27

    Hi,
    I am also facing same error even after passing the app key and App_secret.Here is my code
    var ocl = DropboxClient.CreateOAuthClient(“xxxxxxxxxxxx”, “xxxxxxxxxxxx”);
    var ai = ocl.GetAuthorizeInfo();
    //Access ai.AuthorizeUrl by Browser and signin your account
    //After signin you can get AccessToken
    var t = ocl.GetAccessToken(ai.RequestToken, ai.RequestTokenSecret);
    var cl = new DropboxClient(“consumerKey”, “consumerSecret”, t.Token, t.TokenSecret);

    And Below is the stack trace:

    [ArgumentNullException: Value cannot be null.
    Parameter name: value]
    System.Net.HttpWebRequest.set_ClientCertificates(X509CertificateCollection value) +2234270
    HigLabo.Net.HttpClient.CreateRequest(HttpRequestCommand command) +690
    HigLabo.Net.HttpClient.GetHttpWebResponse(HttpRequestCommand command) +87
    HigLabo.Net.HttpClient.GetResponse(HttpRequestCommand command) +80
    HigLabo.Net.HttpClient.GetBodyText(HttpRequestCommand command) +50
    HigLabo.Net.OAuthClient.GetAuthorizeInfo() +355
    _Default.UploadFile() in d:\RND\DropBox\Default.aspx.cs:19
    _Default.Page_Load(Object sender, EventArgs e) in d:\RND\DropBox\Default.aspx.cs:14
    System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e) +51
    System.Web.UI.Control.OnLoad(EventArgs e) +92
    System.Web.UI.Control.LoadRecursive() +54
    System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +772

    Please advice what should I do?

    Thanks
    Raghu

    Reply
  4. _tasos says

    May 15, 2014 at 17:40

    The code you are trying out is from the “2. Authorization” part of the article when calling the ocl.GetAuthorizeInfo(); function. Make sure the App_Key and App_Secret you are using are correct.

    If you need more help on your code, consider posting a question in stackoverflow.com and post here the link for me to see it.

    Reply
  5. Luiz says

    May 20, 2014 at 02:11

    Hi,

    I’m having the same problem of Raghu. I copied the code of the page, to test the functionality, and gives the same error:

    An unhandled exception of type ‘System.ArgumentNullException’ occurred in System.dll Additional information: Value can not be null.

    Detail: AppSecret AppKey and filled correctly.

    Do you have any idea what it could be?

    Thanks!
    Luiz

    Reply
    • _tasos says

      May 20, 2014 at 18:01

      Hello Luiz,

      Since you have the same issue have you tried checking the values you gave in the App_key and App_secret variables?

      Reply
  6. _tasos says

    May 26, 2014 at 14:00

    Hello guys, I just bumped into this error you are all mentioning. It seems that it is an issue occurring in the latest version of the library.

    When I wrote this article when the 1.3.2 version was released and in that version there were no issues at all. I just rolled back to that version and everything seems to be working.

    Edit: It seems that there is an update for this, check out this link.

    Reply
  7. Ayesha says

    July 12, 2014 at 01:40

    could you please provide code for uploading files to dropbox through asp.net MVC application.. !! please help

    Reply
  8. Abhijit says

    November 19, 2014 at 08:47

    Hi,
    am facing such type problem

    ocl = DropboxClient.CreateOAuthClient(App_key, App_secret);

    does not contain definition of CreateOAuthClient ();
    plz help me…

    Reply
  9. _tasos says

    November 20, 2014 at 15:52

    Hello Abhijit,

    This could occur if you haven’t referenced all required dll files. Make sure that you have both HigLabo.Net.dll and HigLabo.Net.Dropbox.dll.

    If the above does not fix your issue, check if you have a DropboxClient namespace in your code. If yes, change it to something else.

    Reply
  10. mforman says

    November 28, 2014 at 11:44

    Hi,

    This is my authorization code(vb.net):

    Const App_key As String = “XXXXXXXXXXX”
    Const App_secret As String = “XXXXXXXXXX”

    Dim ocl As OAuthClient = Nothing
    Dim ai As HigLabo.Net.AuthorizeInfo = Nothing

    ocl = DropboxClient.CreateOAuthClient(App_key, App_secret)
    ai = ocl.GetAuthorizeInfo()

    Dim RequestToken As String = ai.RequestToken
    Dim RequestTokenSecret As String = ai.RequestTokenSecret
    Dim redirect_url As String = ai.AuthorizeUrl

    ‘ After the user has authorized our app to his account
    Dim t As AccessTokenInfo = ocl.GetAccessToken(RequestToken,
    RequestTokenSecret)

    Dim Token As String = t.Token
    Dim TokenSecret As String = ai.TokenSecret

    but for this line: Dim TokenSecret As String = ai.TokenSecret
    I’m getting the foloing error:
    Error 1 ‘TokenSecret’ is not a member of ‘HigLabo.Net.AuthorizeInfo’.

    Any help will be very much appreciated.
    Thanks in advance!

    Reply
    • _tasos says

      November 28, 2014 at 12:51

      Hello,

      Check my previous comment, maybe it will help you.

      Reply
  11. Neel says

    November 28, 2014 at 21:49

    I am not finding method CreateOAuthClient . DropboxClient has no such methods.
    Please help me, is there something i am missing.

    Reply
  12. Abhishek Singh says

    August 22, 2015 at 09:17

    I am trying this code after completing console part, but the code should shows error in many lines, there is any .dll file need for importing?

    Reply
    • _tasos says

      August 22, 2015 at 13:25

      Hello there, you will need to add as reference the HigLabo.Net.dll as well as the HigLabo.Net.Dropbox.dll

      Reply
  13. JD says

    September 3, 2015 at 05:08

    Hi, i already added Higlabo.net.dll and Higlabo.net.dropbox.dll into the name space and still i cannot add ocl = DropboxClient.CreateOAuthClient(app_key, app_secret) the OnCreateOAuthClient is not a member of DropBoxClient. can you help me with this one

    Reply
  14. psayadav says

    November 24, 2015 at 11:22

    Byte[] bytes = cl.GetFile(dl);

    i am getting error at above line while downloading file. Please help.
    Error: The remote server returned an error: (401) Unauthorized.

    Reply
  15. vishnu says

    January 9, 2016 at 19:34

    Hi, i added Higlabo.net.dll and Higlabo.net.dropbox.dll into the name space and still i cannot add ocl = DropboxClient.CreateOAuthClient(app_key, app_secret) the OnCreateOAuthClient is not a member of DropBoxClient. can you help me with this one

    Reply
  16. sonika says

    June 22, 2016 at 10:15

    Hello,

    I am trying to integrate this code but its did’nt work .i am getting the errors you can see in screenshot given below

    https://gyazo.com/0dee9dae460aa0cb8576245324c4c871

    could you please help me to sort out this issue

    Reply
    • _tasos says

      June 27, 2016 at 12:49

      Hello,

      Make sure you have the correct version added as a reference.

      Reply
  17. Ender Ariç says

    July 18, 2016 at 11:45

    Hi i’m trying to upload a file into my apps folder. it gives an error value can not be null on

    ai = ocl.GetAuthorizeInfo();

    How can i explain this. This is emergency. Here is my code.

    private const string App_key = “my_app_key”;
    private const string App_secret = “my_app_secret”;
    OAuthClient ocl = null;
    HigLabo.Net.AuthorizeInfo ai = null;

    public void UploadFile(byte[] content, string filename, string target)
    {

    ocl = DropboxClient.CreateOAuthClient(App_key, App_secret);
    ai = ocl.GetAuthorizeInfo();
    string RequestToken = ai.RequestToken;
    string RequestTokenSecret = ai.RequestTokenSecret;
    string redirect_url = ai.AuthorizeUrl;
    AccessTokenInfo t = ocl.GetAccessToken(RequestToken, RequestTokenSecret);
    string Token = t.Token;
    string TokenSecret = t.TokenSecret;

    DropboxClient cl = new DropboxClient(App_key, App_secret, Token, TokenSecret);

    HigLabo.Net.Dropbox.UploadFileCommand ul = new HigLabo.Net.Dropbox.UploadFileCommand();
    ul.Root = RootFolder.Sandbox;
    ul.FolderPath = target;
    ul.FileName = filename;
    ul.LoadFileData(content);

    Metadata md = cl.UploadFile(ul);
    }

    protected void Button1_Click(object sender, EventArgs e)
    {
    //string filename = Path.GetFullPath(FileUpload1.FileBytes);
    //byte[] bytes = System.IO.File.ReadAllBytes(filename);
    UploadFile(FileUpload1.FileBytes, “sundas.jpg”, “/Apps/synch/”);
    }

    Reply

Leave a Reply to mforman Cancel reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Primary Sidebar

Categories

  • .NET Development
  • ASP.NET
  • Databases
  • Fun
  • IIS
  • JavaScript
  • Web Development

Tags

.NET Core Android ANTLR ASP.NET Ajax ASP.NET Core ASP.NET MVC ASP.NET Web Forms AWS Bouncy Castle Chartjs cli Client info detection Comic Continuous integration CSS Data backup Date handling Firebase Firefox addons Github HigLabo HTML5 Image manipulation jQuery JWT MySQL Nodejs Nuget OAuth Objectionjs OOP openssl Oracle ORM PHP Regular expressions SEO Social media SQL SQL Server UI/UX Url rewriting Videos Visual Studio Web design

Meta

  • Log in
  • Entries feed
  • Comments feed
  • WordPress.org

Secondary Sidebar

Archives

  • July 2020
  • March 2020
  • August 2019
  • December 2018
  • November 2018
  • February 2018
  • August 2016
  • June 2016
  • May 2016
  • February 2016
  • January 2016
  • August 2015
  • July 2015
  • October 2014
  • July 2014
  • November 2013
  • April 2013
  • February 2013
  • January 2013
  • December 2012
  • November 2012
  • August 2012
  • May 2012
  • February 2012
  • December 2011
  • October 2011
  • September 2011
  • August 2011
  • July 2011
  • May 2011
  • April 2011
  • March 2011
  • February 2011
  • January 2011
  • December 2010
  • November 2010
  • October 2010
  • September 2010
  • August 2010
  • July 2010

Footer

Recent Posts

  • Anatomy of an Objection.js model
  • Check your RSA private and public keys
  • Round functions on the Nth digit
  • Send FCM Notifications in C#
  • Jwt Manager
  • Things around the web #5
  • Query JSON data as relational in MySQL
  • Create and sign JWT token with RS256 using the private key
  • Drop all database objects in Oracle
  • Create and deploy a Nuget package

Latest tweets

  • Geekiness Intensifies.. NASA used Three.js to render a real-time simulation of this week's NASA rover landing on M… https://t.co/orgkXnYj9O February 19, 2021 18:12
  • Things I Wished More Developers Knew About Databases https://t.co/h4gfq6NJgo #softwaredevelopment #databases May 3, 2020 12:52
  • How a Few Lines of Code Broke Lots of Packages https://t.co/p7ZSiLY5ca #javascript May 3, 2020 12:48
  • Can someone steal my IP address and use it as their own? https://t.co/HoQ7Z3BG69 January 24, 2020 13:27
  • Organizational complexity is the best predictor of bugs in a software module https://t.co/aUYn9hD4oa #softwaredevelopment January 13, 2020 08:24
  • http://twitter.com/codingstill

Misc Links

  • George Liatsos Blog
  • Plethora Themes
  • C# / VB Converter
  • Higlabo: .NET library for mail, DropBox, Twitter & more

Connect with me

  • GitHub
  • LinkedIn
  • RSS
  • Twitter
  • Stack Overflow

Copyright © 2021 · eleven40 Pro on Genesis Framework · WordPress · Log in