Project: Dropbox.Usage.With.Dropnet


Authorize your Dropbox application:
Authorize your Dropbox application

This snippet allow you to use DropNet (a Dropbox API helper library on Nuget) to:
  1. authorize your Dropbox application for the first time usage
  2. get and store the access token for the next usages
  3. query Dropbox to get the list of folder and files
private const string DropBoxMetaKey = "Dropbox.Meta";

void Main()
{
	DropNetClient client;
	
	if (!IsDropboxMetaStoredInPasswordManager())
	{
		Console.WriteLine("Dropbox API keys, get them at https://www.dropbox.com/developers");
		Console.Write("Provide API key: ");
		var apiKey = Console.ReadLine();
		Console.WriteLine(apiKey);
		Console.Write("Provide API secret: ");
		var apiSecret = Console.ReadLine();
		Console.WriteLine(apiSecret);
		
		client = new DropNetClient(apiKey, apiSecret);
		AuthorizeApplicationForTheFirstTime(client);
		AuthenticateToDropBox(client, apiKey, apiSecret);
	}
	else
	{
		var keys = Util.GetPassword(DropBoxMetaKey).Split(';');		
		client = new DropNetClient(keys[0], keys[1], keys[2], keys[3]);
	}

	Console.WriteLine("Quering Dropbox...");
	ShowMetadata(client);
}

private void ShowMetadata(DropNetClient client)
{
	var data = client.GetMetaData();
	
	Console.WriteLine("Path = {0}", data.Path);
	data
		.Contents
		.OrderByDescending(c => c.Is_Dir)
		.ToList()
		.ForEach(x => Console.WriteLine("- {0} = {1}", x.Is_Dir ? "Folder" : "File", x.Name));
}

private void AuthorizeApplicationForTheFirstTime(DropNetClient client)
{
	var token = client.GetToken();

	Console.WriteLine();
	Console.WriteLine("Authorize the app using the browser:");
	Console.WriteLine("1. wait that Dropbox page");
	Console.WriteLine("2. press the \"Allow\" button");
	Console.WriteLine("\r\npress enter to launch the browser...");

	Console.ReadLine();

	var dropboxAuthorizeUrl = client.BuildAuthorizeUrl();
	Process.Start(dropboxAuthorizeUrl);

	Thread.Sleep(2000);
	Console.WriteLine("\r\nAuthentication done... press enter to proceed...");
	
	Console.ReadLine();
	Console.WriteLine();
}
	
private void AuthenticateToDropBox(DropNetClient client, string apiKey, string apiSecret)
{	
	var accessToken = client.GetAccessToken();
	
	client = new DropNetClient(apiKey, apiSecret, accessToken.Token, accessToken.Secret);
	
	Util.SetPassword("Dropbox.Meta", string.Format("{0};{1};{2};{3}", apiKey, apiSecret, accessToken.Token, accessToken.Secret));
}

public bool IsDropboxMetaStoredInPasswordManager()
{
	return LINQPadUtil.GetPassword(DropBoxMetaKey) != null;
}

public static class LINQPadUtil
{
	public static string GetPassword(string name)
	{
		return
			(string)
			typeof(LINQPad.Util).Assembly.GetType("LINQPad.PasswordManager")
			.GetMethod("GetPassword").Invoke(null, new object[] { name });
	}
}

Last edited Mar 2, 2013 at 3:05 PM by teoarch, version 3

Comments

No comments yet.