Example #1
0
        private void buttonAuthenticate_Click(object sender, EventArgs e)
        {
            if (config == null)
            {
                // get the config of dropbox
                config =
                    CloudStorage.GetCloudConfigurationEasy(nSupportedCloudConfigurations.DropBox) as
                    Dropbox.DropBoxConfiguration;

                // set your own callback which will be called from Dropbox after successful
                // authorization
                config.AuthorizationCallBack = new Uri("http://getgreenshot.org/");

                // create a request token
                requestToken =
                    Dropbox.DropBoxStorageProviderTools.GetDropBoxRequestToken(config,
                                                                               DropboxUtils.DROPBOX_APP_KEY,
                                                                               DropboxUtils.DROPBOX_APP_SECRET);

                // call the authorization url via WebBrowser Plugin
                String AuthorizationUrl =
                    Dropbox.DropBoxStorageProviderTools.GetDropBoxAuthorizationUrl(config, requestToken);

                System.Diagnostics.Process.Start(AuthorizationUrl);
            }
            else
            {
                // create the access token
                AuthToken = Dropbox.DropBoxStorageProviderTools.ExchangeDropBoxRequestTokenIntoAccessToken(config,
                                                                                                           DropboxUtils.DROPBOX_APP_KEY, DropboxUtils.DROPBOX_APP_SECRET, requestToken);
                requestToken = null;
            }
        }
 /// <summary>
 /// This method builds derived from the request token a valid authorization url which can be used
 /// for web applications
 /// </summary>
 /// <param name="configuration"></param>
 /// <param name="DropBoxRequestToken"></param>
 /// <returns></returns>
 static public String GetDropBoxAuthorizationUrl(DropBoxConfiguration configuration, DropBoxRequestToken DropBoxRequestToken)
 {
     // build the auth url
     return(OAuthUrlGenerator.GenerateAuthorizationUrl(configuration.AuthorizationTokenUrl.ToString(),
                                                       configuration.AuthorizationCallBack.ToString(),
                                                       DropBoxRequestToken.RealToken));
 }
 /// <summary>
 /// This method builds derived from the request token a valid authorization url which can be used
 /// for web applications
 /// </summary>
 /// <param name="configuration"></param>
 /// <param name="DropBoxRequestToken"></param>
 /// <returns></returns>
 public static String GetDropBoxAuthorizationUrl(DropBoxConfiguration configuration, DropBoxRequestToken DropBoxRequestToken)
 {
     // build the auth url
     return OAuthUrlGenerator.GenerateAuthorizationUrl(configuration.AuthorizationTokenUrl.ToString(),
                                                       configuration.AuthorizationCallBack.ToString(),
                                                       DropBoxRequestToken.RealToken);
 }
        public static void DeleteDropboxImage(DropboxInfo dropBoxInfo)
        {
            // Make sure we remove it from the history, if no error occured
            config.runtimeDropboxHistory.Remove(dropBoxInfo.ID);
            config.DropboxUploadHistory.Remove(dropBoxInfo.ID);

            // get the config of dropbox
            Dropbox.DropBoxConfiguration dropBoxConfig =
                CloudStorage.GetCloudConfigurationEasy(nSupportedCloudConfigurations.DropBox) as
                Dropbox.DropBoxConfiguration;

            // instanciate the cloudstorage manager
            CloudStorage storage = new CloudStorage();

            // open the connection to the storage
            storage.Open(dropBoxConfig, config.DropboxAccessToken);

            // get the root entry of the cloud storage
            ICloudDirectoryEntry root = storage.GetRoot();

            // delete a file
            ICloudFileSystemEntry fileSystemEntry = storage.GetFileSystemObject(dropBoxInfo.ID, root);

            if (fileSystemEntry != null)
            {
                storage.DeleteFileSystemEntry(fileSystemEntry);
            }
            // close the cloud storage connection
            if (storage.IsOpened)
            {
                storage.Close();
            }

            dropBoxInfo.Image = null;
        }
        public ConnectWindow()
        {
            InitializeComponent();

            // get a standard config
            _UsedConfig = DropBoxConfiguration.GetStandardConfiguration();

            wcAuthenticate.Navigated += new NavigatedEventHandler(webBrowser_DocumentTitleChanged);

            //Start authentication
            Authenticate();
        }
        /// <summary>
        /// This method retrieves a new request token from the dropbox server
        /// </summary>
        /// <param name="configuration"></param>
        /// <param name="ConsumerKey"></param>
        /// <param name="ConsumerSecret"></param>
        /// <returns></returns>
        static public DropBoxRequestToken GetDropBoxRequestToken(DropBoxConfiguration configuration, String ConsumerKey, String ConsumerSecret)
        {
            // build the consumer context
            var consumerContext = new OAuthConsumerContext(ConsumerKey, ConsumerSecret);

            // build up the oauth session
            var serviceContext = new OAuthServiceContext(configuration.RequestTokenUrl.ToString(),
                                                         configuration.AuthorizationTokenUrl.ToString(), configuration.AuthorizationCallBack.ToString(),
                                                         configuration.AccessTokenUrl.ToString());

            // get a request token from the provider
            OAuthService svc = new OAuthService();

            return(new DropBoxRequestToken(svc.GetRequestToken(serviceContext, consumerContext)));
        }
        /// <summary>
        /// This method retrieves a new request token from the dropbox server
        /// </summary>
        /// <param name="configuration"></param>
        /// <param name="ConsumerKey"></param>
        /// <param name="ConsumerSecret"></param>
        /// <returns></returns>
        public static DropBoxRequestToken GetDropBoxRequestToken(DropBoxConfiguration configuration, String ConsumerKey, String ConsumerSecret)
        {
            // build the consumer context
            var consumerContext = new OAuthConsumerContext(ConsumerKey, ConsumerSecret);

            // build up the oauth session
            var serviceContext = new OAuthServiceContext(configuration.RequestTokenUrl.ToString(),
                                                         configuration.AuthorizationTokenUrl.ToString(), configuration.AuthorizationCallBack.ToString(),
                                                         configuration.AccessTokenUrl.ToString());

            // get a request token from the provider      
            var svc = new OAuthService();
            var oauthToken = svc.GetRequestToken(serviceContext, consumerContext);
            return oauthToken != null ? new DropBoxRequestToken(oauthToken) : null;
        }
        /// <summary>
        /// Do the actual upload to Dropbox
        /// For more details on the available parameters, see: http://sharpbox.codeplex.com/
        /// </summary>
        /// <param name="imageData">byte[] with image data</param>
        /// <returns>DropboxResponse</returns>
        public static DropboxInfo UploadToDropbox(byte[] imageData, string title, string filename)
        {
            // get the config of dropbox
            Dropbox.DropBoxConfiguration dropBoxConfig =
                CloudStorage.GetCloudConfigurationEasy(nSupportedCloudConfigurations.DropBox) as
                Dropbox.DropBoxConfiguration;

            // instanciate the cloudstorage manager
            CloudStorage storage = new CloudStorage();

            // open the connection to the storage
            storage.Open(dropBoxConfig, config.DropboxAccessToken);

            // get the root entry of the cloud storage
            ICloudDirectoryEntry root = storage.GetRoot();

            if (root == null)
            {
                Console.WriteLine("No root object found");
            }
            else
            {
                // create the file
                ICloudFileSystemEntry file = storage.CreateFile(root, filename);

                // build the data stream
                Stream data = new MemoryStream(imageData);

                // reset stream
                data.Position = 0;

                // upload data
                file.GetDataTransferAccessor().Transfer(data, nTransferDirection.nUpload, null, null);
            }

            // close the cloud storage connection
            if (storage.IsOpened)
            {
                storage.Close();
            }


            return(RetrieveDropboxInfo(filename));
        }
        public static DropboxInfo RetrieveDropboxInfo(string filename)
        {
            LOG.InfoFormat("Retrieving Dropbox info for {0}", filename);

            DropboxInfo dropBoxInfo = new DropboxInfo();

            dropBoxInfo.ID        = filename;
            dropBoxInfo.Title     = filename;
            dropBoxInfo.Timestamp = DateTime.Now;
            dropBoxInfo.WebUrl    = string.Empty;

            // get the config of dropbox
            Dropbox.DropBoxConfiguration dropBoxConfig =
                CloudStorage.GetCloudConfigurationEasy(nSupportedCloudConfigurations.DropBox) as
                Dropbox.DropBoxConfiguration;

            // instanciate the cloudstorage manager
            CloudStorage storage = new CloudStorage();

            // get the root entry of the cloud storage
            ICloudDirectoryEntry root = storage.GetRoot();

            // open the connection to the storage
            storage.Open(dropBoxConfig, config.DropboxAccessToken);
            dropBoxInfo.WebUrl = storage.GetFileSystemObjectUrl(dropBoxInfo.ID, root).ToString();

            ICloudFileSystemEntry fileSystemEntry = storage.GetFileSystemObject(dropBoxInfo.ID, root);

            if (fileSystemEntry != null)
            {
                dropBoxInfo.Title     = fileSystemEntry.Name;
                dropBoxInfo.Timestamp = fileSystemEntry.Modified;
            }

            // close the cloud storage connection
            if (storage.IsOpened)
            {
                storage.Close();
            }

            return(dropBoxInfo);
        }
        /// <summary>
        /// This method returns the account information of a dropbox account
        /// </summary>
        /// <param name="token"></param>
        /// <returns></returns>
        static public DropBoxAccountInfo GetAccountInformation(ICloudStorageAccessToken token)
        {
            // generate the dropbox service
            DropBoxStorageProviderService service = new DropBoxStorageProviderService();

            // generate a session
            IStorageProviderSession session = service.CreateSession(token, DropBoxConfiguration.GetStandardConfiguration());

            if (session == null)
            {
                return(null);
            }

            // receive acc info
            DropBoxAccountInfo accInfo = service.GetAccountInfo(session);

            // close the session
            service.CloseSession(session);

            // go ahead
            return(accInfo);
        }
        internal static void SaveAccessToken()
        {
            if (config.DropboxAccessToken != null)
            {
                // get the config of dropbox
                Dropbox.DropBoxConfiguration dropBoxConfig =
                    CloudStorage.GetCloudConfigurationEasy(nSupportedCloudConfigurations.DropBox) as
                    Dropbox.DropBoxConfiguration;

                CloudStorage storage = new CloudStorage();

                // open the connection to the storage
                storage.Open(dropBoxConfig, config.DropboxAccessToken);

                Stream tokenStream = storage.SerializeSecurityToken(config.DropboxAccessToken);

                string fileFullPath = Path.Combine(Environment.CurrentDirectory, Environment.UserName + "-Dropbox.tok");

                // Create a FileStream object to write a stream to a file
                using (FileStream fileStream = System.IO.File.Create(fileFullPath, (int)tokenStream.Length))
                {
                    // Fill the bytes[] array with the stream data
                    byte[] bytesInStream = new byte[tokenStream.Length];
                    tokenStream.Read(bytesInStream, 0, (int)bytesInStream.Length);

                    // Use FileStream object to write to the specified file
                    fileStream.Write(bytesInStream, 0, bytesInStream.Length);
                }

                // close the cloud storage connection
                if (storage.IsOpened)
                {
                    storage.Close();
                }
            }
        }
        /// <summary>
        /// This method is able to exchange the request token into an access token which can be used in 
        /// sharpbox. It is necessary that the user validated the request via authorization url otherwise 
        /// this call wil results in an unauthorized exception!
        /// </summary>
        /// <param name="configuration"></param>
        /// <param name="ConsumerKey"></param>
        /// <param name="ConsumerSecret"></param>
        /// <param name="DropBoxRequestToken"></param>
        /// <returns></returns>
        public static ICloudStorageAccessToken ExchangeDropBoxRequestTokenIntoAccessToken(DropBoxConfiguration configuration, String ConsumerKey, String ConsumerSecret, DropBoxRequestToken DropBoxRequestToken)
        {
            // build the consumer context
            var consumerContext = new OAuthConsumerContext(ConsumerKey, ConsumerSecret);

            // build up the oauth session
            var serviceContext = new OAuthServiceContext(configuration.RequestTokenUrl.ToString(),
                                                         configuration.AuthorizationTokenUrl.ToString(), configuration.AuthorizationCallBack.ToString(),
                                                         configuration.AccessTokenUrl.ToString());

            // build the access token
            var svc = new OAuthService();
            var accessToken = svc.GetAccessToken(serviceContext, consumerContext, DropBoxRequestToken.RealToken);
            if (accessToken == null)
                throw new UnauthorizedAccessException();

            // create the access token 
            return new DropBoxToken(accessToken,
                                    new DropBoxBaseTokenInformation
                                        {
                                            ConsumerKey = ConsumerKey,
                                            ConsumerSecret = ConsumerSecret
                                        });
        }
        /// <summary>
        /// This method is able to exchange the request token into an access token which can be used in
        /// sharpbox. It is necessary that the user validated the request via authorization url otherwise
        /// this call wil results in an unauthorized exception!
        /// </summary>
        /// <param name="configuration"></param>
        /// <param name="ConsumerKey"></param>
        /// <param name="ConsumerSecret"></param>
        /// <param name="DropBoxRequestToken"></param>
        /// <returns></returns>
        static public ICloudStorageAccessToken ExchangeDropBoxRequestTokenIntoAccessToken(DropBoxConfiguration configuration, String ConsumerKey, String ConsumerSecret, DropBoxRequestToken DropBoxRequestToken)
        {
            // build the consumer context
            var consumerContext = new OAuthConsumerContext(ConsumerKey, ConsumerSecret);

            // build up the oauth session
            var serviceContext = new OAuthServiceContext(configuration.RequestTokenUrl.ToString(),
                                                         configuration.AuthorizationTokenUrl.ToString(), configuration.AuthorizationCallBack.ToString(),
                                                         configuration.AccessTokenUrl.ToString());

            // build the access token
            OAuthService svc         = new OAuthService();
            OAuthToken   accessToken = svc.GetAccessToken(serviceContext, consumerContext, DropBoxRequestToken.RealToken);

            if (accessToken == null)
            {
                throw new UnauthorizedAccessException();
            }

            // create the access token
            return(new DropBoxToken(accessToken,
                                    new DropBoxBaseTokenInformation()
            {
                ConsumerKey = ConsumerKey,
                ConsumerSecret = ConsumerSecret
            }));
        }
        /// <summary>
        /// This method offers the mobile login api of dropbox for users who are migrating from version 0 of the
        /// dropbox API because version 1 supports token based logins only
        /// </summary>
        /// <param name="username"></param>
        /// <param name="password"></param>
        /// <param name="appkey"></param>
        /// <param name="appsecret"></param>
        /// <returns></returns>
        static public ICloudStorageAccessToken LoginWithMobileAPI(String username, String password, String appkey, String appsecret)
        {
            // get the configuration
            DropBoxConfiguration configuration = DropBoxConfiguration.GetStandardConfiguration();

            // build the consumer context
            var consumerContext = new OAuthConsumerContext(appkey, appsecret);

            // build up the oauth session
            var serviceContext = new OAuthServiceContext(configuration.RequestTokenUrl.ToString(),
                                                         configuration.AuthorizationTokenUrl.ToString(), configuration.AuthorizationCallBack.ToString(),
                                                         configuration.AccessTokenUrl.ToString());

            // get a request token from the provider
            OAuthService svc = new OAuthService();
            var          oAuthRequestToken = svc.GetRequestToken(serviceContext, consumerContext);

            if (oAuthRequestToken == null)
            {
                throw new SharpBoxException(SharpBoxErrorCodes.ErrorInvalidConsumerKeySecret);
            }
            DropBoxToken DropBoxRequestToken = new DropBoxToken(oAuthRequestToken, new DropBoxBaseTokenInformation()
            {
                ConsumerKey = appkey, ConsumerSecret = appsecret
            });

            // generate the dropbox service
            DropBoxStorageProviderService service = new DropBoxStorageProviderService();

            // build up a request Token Session
            var requestSession = new DropBoxStorageProviderSession(DropBoxRequestToken, configuration, consumerContext, service);

            // build up the parameters
            var param = new Dictionary <String, String>
            {
                { "email", username },
                { "password", password }
            };

            // call the mobile login api
            String result = "";

            try
            {
                int code;
                result = DropBoxRequestParser.RequestResourceByUrl(DropBoxMobileLogin, param, service, requestSession, out code);
                if (result.Length == 0)
                {
                    throw new UnauthorizedAccessException();
                }
            }

#if MONOTOUCH || WINDOWS_PHONE || MONODROID
            catch (Exception ex)
            {
                if (ex is UnauthorizedAccessException)
                {
                    throw ex;
                }
                else
                {
                    throw new SharpBoxException(SharpBoxErrorCodes.ErrorCouldNotContactStorageService, ex);
                }
            }
#else
            catch (System.Web.HttpException netex)
            {
                throw new SharpBoxException(SharpBoxErrorCodes.ErrorCouldNotContactStorageService, netex);
            }
#endif

            // exchange a request token for an access token
            var accessToken = new DropBoxToken(result);

            // adjust the token
            if (accessToken.BaseTokenInformation == null)
            {
                accessToken.BaseTokenInformation                = new DropBoxBaseTokenInformation();
                accessToken.BaseTokenInformation.ConsumerKey    = appkey;
                accessToken.BaseTokenInformation.ConsumerSecret = appsecret;
            }


            // go ahead
            return(accessToken);
        }
        private void buttonAuthenticate_Click(object sender, EventArgs e)
        {
            if (config == null)
            {
                // get the config of dropbox
                config =
                CloudStorage.GetCloudConfigurationEasy(nSupportedCloudConfigurations.DropBox) as
                Dropbox.DropBoxConfiguration;

                // set your own callback which will be called from Dropbox after successful
                // authorization
                config.AuthorizationCallBack = new Uri("http://getgreenshot.org/");

                // create a request token
                requestToken =
                Dropbox.DropBoxStorageProviderTools.GetDropBoxRequestToken(config,
                DropboxUtils.DROPBOX_APP_KEY,
                DropboxUtils.DROPBOX_APP_SECRET);

                // call the authorization url via WebBrowser Plugin
                String AuthorizationUrl =
                Dropbox.DropBoxStorageProviderTools.GetDropBoxAuthorizationUrl(config, requestToken);

                System.Diagnostics.Process.Start(AuthorizationUrl);
            }
            else
            {
                 // create the access token
                AuthToken = Dropbox.DropBoxStorageProviderTools.ExchangeDropBoxRequestTokenIntoAccessToken(config,
            DropboxUtils.DROPBOX_APP_KEY, DropboxUtils.DROPBOX_APP_SECRET, requestToken);
                requestToken = null;
            }
        }
	    private ICloudStorageAccessToken GetAccessToken(DropBoxConfiguration config, IAuthenticationSettings authenticationSettings)
        {
            var accessToken  = DropBoxExtensions.GetDropBoxAccessToken(authenticationSettings.DropBoxAuthenticationKey, authenticationSettings.DropBoxAuthenticationSecret, authenticationSettings.DropBoxApiKey, authenticationSettings.DropBoxApiSecret);
            return accessToken;
        }