/// <summary>
        /// finishes the token exchange process
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void webBrowser_DocumentTitleChanged(object sender, EventArgs e)
        {
            if (_GeneratedToken == null && wcAuthenticate.Source.ToString().StartsWith(_UsedConfig.AuthorizationCallBack.ToString()))
            {
                // 5. try to get the real token
                _GeneratedToken = DropBoxStorageProviderTools.ExchangeDropBoxRequestTokenIntoAccessToken(_UsedConfig, appKey, appSecret, _CurrentRequestToken);

                // 6. store the real token to file
                var cs = new CloudStorage();
                if(!Directory.Exists("auth"))
                {
                    Directory.CreateDirectory("auth");
                }
                cs.SerializeSecurityTokenEx(_GeneratedToken, _UsedConfig.GetType(), null, "auth/token.xml");

                // 7. show message box
                Console.WriteLine(@"ConnectWindow>>> Authentication token stored.");

                //Show main window
                var mainWindow = new MainWindowSimple();
                mainWindow.Show();

                Close();
                //System.Windows.Forms.MessageBox.Show(@"Stored token into " + @"auth/token.xml");
            }
        }
示例#2
0
        public static BrainstormingEventLogger GetInstance(CloudStorage storage)
        {
            if (loggerInstance == null)
            {
                lock (syncRoot)
                {
                    if (loggerInstance == null)
                    {
                        loggerInstance = new BrainstormingEventLogger(storage);

                        ICloudDirectoryEntry targetFolder;
                        try
                        {
                            targetFolder = storage.GetFolder("/UserStudy_Log");
                        }
                        catch (Exception ex)
                        {
                            targetFolder = storage.CreateFolder("/UserStudy_Log");
                        }

                    }
                }
            }
            return loggerInstance;
        }
		protected void ExecuteUpload(IExecuteBoxNetUploaderWorkflowMessage message, GenericNetworkCredentials authenticationToken, FileInfo inputFilePath)
		{
			var cancellationTokenSource = new CancellationTokenSource();
			var cancellationToken = cancellationTokenSource.Token;

			var task = Task.Factory.StartNew(() => { });
			task.ContinueWith((t) =>
			{
				BoxNetUploaderService.Uploaders.Add(message, new CancellableTask
				{
					Task = task,
					CancellationTokenSource = cancellationTokenSource
				});

				var configuration = GetBoxNetConfiguration();
				var storage = new CloudStorage();
				var accessToken = storage.Open(configuration, authenticationToken);

				var folder = string.IsNullOrEmpty(message.Settings.Folder) ? storage.GetRoot() : storage.GetFolder(message.Settings.Folder);
				if (folder == null)
				{
					throw new Exception(string.Format("Folder does not exist - {0}", message.Settings.Folder));
				}
				else
				{
					var file = storage.CreateFile(folder, inputFilePath.Name);
					var uploader = file.GetDataTransferAccessor();
					using (var inputFileStream = inputFilePath.OpenRead())
					{
						uploader.Transfer(inputFileStream, nTransferDirection.nUpload, FileOperationProgressChanged, task);
					}
				}

				if (storage.IsOpened)
				{
					storage.Close();
				}
			}
			, cancellationToken)
			.ContinueWith((t) =>
			{
				var executedBoxNetUploaderWorkflowMessage = new ExecutedBoxNetUploaderWorkflowMessage()
				{
					CorrelationId = message.CorrelationId,
					Cancelled = t.IsCanceled,
					Error = t.Exception
				};

				var bus = BusDriver.Instance.GetBus(BoxNetUploaderService.BusName);
				bus.Publish(executedBoxNetUploaderWorkflowMessage);

				BoxNetUploaderService.Uploaders.Remove(message);
			});
		}
 public DropboxNoteUploader()
 {
     storage = new CloudStorage();
     var dropboxConfig = CloudStorage.GetCloudConfigurationEasy(nSupportedCloudConfigurations.DropBox);
     ICloudStorageAccessToken accessToken;
     using (var fs = File.Open("DropBoxStorage.Token", FileMode.Open, FileAccess.Read, FileShare.None))
     {
         accessToken = storage.DeserializeSecurityToken(fs);
     }
     storageToken = storage.Open(dropboxConfig, accessToken);
     InitNoteFolderIfNecessary();
 }
示例#5
0
 public static BoardScreenUpdater GetInstance(CloudStorage storage)
 {
     if (instance == null)
         {
             lock (syncRoot)
             {
                 if (instance == null)
                     instance = new BoardScreenUpdater(storage);
             }
         }
     return instance;
 }
        public static void UploadFile(string filename, string path)
        {
            if (_credentials == null)
                return;
            else if (string.IsNullOrEmpty(_remoteDirectory))
                return;

            Console.WriteLine("Uploading file to dropbox");

            // instanciate a cloud storage configuration, e.g. for dropbox
            DropBoxConfiguration configuration = DropBoxConfiguration.GetStandardConfiguration();

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

            // open the connection to the storage
            if (!storage.Open(configuration, _credentials))
            {
                Console.WriteLine("Connection failed");
                return;
            }

            ICloudDirectoryEntry folder = _remoteDirectory.Equals("root", StringComparison.CurrentCultureIgnoreCase)
                                                           ? storage.GetRoot()
                                                           : GetDirectoryPath(storage);

            // create the file
            ICloudFileSystemEntry file = storage.CreateFile(folder, filename);

            // upload the data
            Stream data = file.GetContentStream(FileAccess.Write);

            // build a stream read
            var writer = new BinaryWriter(data);

            var filedata = File.ReadAllBytes(path);
            writer.Write(filedata);

            // close the streamreader
            writer.Close();

            // close the stream
            data.Close();

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

            Console.WriteLine("Upload Complete");
        }
        public void Open(string authToken)
        {
            if (IsOpened)
                return;

            if (_provider == null)
                _provider = new GoogleDocsStorageProvider();

            var token = new CloudStorage().DeserializeSecurityTokenFromBase64(authToken);
            _provider.Open(new GoogleDocsConfiguration(), token);

            IsOpened = true;
        }
示例#8
0
        private IStorageFolder getDirectoryInfo(IStorageFolder parentFolder, CloudStorage cloudStorage)
        {
            if (parentFolder == null)
                parentFolder = new YandexStorageFolder
                {
                    Files = new List<IStorageFile>(),
                    Name = string.Empty,
                    ParentFolder = null,
                    Path = "/",
                    SubFolders = new List<IStorageFolder>()
                };

            var cloudDirectoryEntry = cloudStorage.GetFolder(parentFolder.Path);

            if (cloudDirectoryEntry == null || cloudDirectoryEntry.Count == 0)
                return parentFolder;
            else
            {
                foreach (var dirItem in cloudDirectoryEntry)
                {
                    if (dirItem.Length == 0)
                    {
                        var subfolder = new YandexStorageFolder
                        {
                            Files = new List<IStorageFile>(),
                            Name = dirItem.Name,
                            ParentFolder = parentFolder,
                            Path = string.Concat(parentFolder.Path, dirItem.Name, "/"),
                            SubFolders = new List<IStorageFolder>(),
                            DateTime = dirItem.Modified
                        };

                        parentFolder.SubFolders.Add(GetDirectoryInfo(subfolder));
                    }
                    else
                        parentFolder.Files.Add(new YandexStorageFile
                        {
                            DateTime = dirItem.Modified,
                            Extension = Path.GetExtension(dirItem.Name).ToLower(),
                            Name = dirItem.Name,
                            Size = dirItem.Length,
                            ParentFolder = parentFolder
                        });
                }
            }

            return parentFolder;
        }
示例#9
0
 public BrainstormingEventLogger(CloudStorage storage)
 {
     this.Storage = storage;
     logFileName_Cloud = "Whiteboard_" + DateTime.Now.ToString("dd-MM-yy HH-mm-ss") + ".csv";
     string logFileFolder = Environment.CurrentDirectory + "/BrainstormLog";
     if (!Directory.Exists(logFileFolder))
     {
         Directory.CreateDirectory(logFileFolder);
     }
     localFilePath = logFileFolder + "/" + logFileName_Cloud;
     if (!File.Exists(localFilePath))
     {
         File.Create(localFilePath).Close();
     }
     logWriter = File.AppendText(localFilePath);
 }
示例#10
0
        private void Save(string filename, MemoryStream memoryStream)
        {
            var storage = new CloudStorage();
            storage.Open(_cloudStorageConfiguration, _cloudeStorageCredentials);

            var backupFolder = storage.GetFolder(ArchiveFolderPath);
            if (backupFolder == null) { throw new Exception("Cloud folder not found: " + ArchiveFolderPath); }

            var cloudFile = storage.CreateFile(backupFolder, filename);
            using (var cloudStream = cloudFile.GetContentStream(FileAccess.Write))
            {
                cloudStream.Write(memoryStream.GetBuffer(), 0, (int)memoryStream.Position);
            }

            if (storage.IsOpened) { storage.Close(); }
        }
示例#11
0
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Session.IsReadOnly)
            {
                SubmitError("No session is availible.", Source);
                return;
            }

            var config = CloudStorage.GetCloudConfigurationEasy(nSupportedCloudConfigurations.DropBox) as DropBoxConfiguration;
            var callbackUri = new UriBuilder(Request.GetUrlRewriter());
            if (!string.IsNullOrEmpty(Request.QueryString[AuthorizationUrlKey]) && Session[RequestTokenSessionKey] != null)
            {
                //Authorization callback
                try
                {
                    var accessToken = DropBoxStorageProviderTools.ExchangeDropBoxRequestTokenIntoAccessToken(config,
                                                                                                             ImportConfiguration.DropboxAppKey,
                                                                                                             ImportConfiguration.DropboxAppSecret,
                                                                                                             Session[RequestTokenSessionKey] as DropBoxRequestToken);

                    Session[RequestTokenSessionKey] = null; //Exchanged
                    var storage = new CloudStorage();
                    var base64token = storage.SerializeSecurityTokenToBase64Ex(accessToken, config.GetType(), new Dictionary<string, string>());
                    storage.Open(config, accessToken); //Try open storage!
                    var root = storage.GetRoot();
                    if (root == null) throw new Exception();

                    SubmitToken(base64token, Source);
                }
                catch
                {
                    SubmitError("Failed to open storage with token", Source);
                }
            }
            else
            {
                callbackUri.Query += string.Format("&{0}=1", AuthorizationUrlKey);
                config.AuthorizationCallBack = callbackUri.Uri;
                // create a request token
                var requestToken = DropBoxStorageProviderTools.GetDropBoxRequestToken(config, ImportConfiguration.DropboxAppKey,
                                                                                      ImportConfiguration.DropboxAppSecret);
                var authorizationUrl = DropBoxStorageProviderTools.GetDropBoxAuthorizationUrl(config, requestToken);
                Session[RequestTokenSessionKey] = requestToken; //Store token into session!!!
                Response.Redirect(authorizationUrl);
            }
        }
 private void CreateStorage()
 {
     _storage = new CloudStorage();
     var config = CloudStorage.GetCloudConfigurationEasy(_providerKey);
     if (!string.IsNullOrEmpty(_authData.Token))
     {
         if (_providerKey != nSupportedCloudConfigurations.BoxNet)
         {
             var token = _storage.DeserializeSecurityTokenFromBase64(_authData.Token);
             _storage.Open(config, token);
         }
     }
     else
     {
         _storage.Open(config, new GenericNetworkCredentials {Password = _authData.Password, UserName = _authData.Login});
     }
 }
示例#13
0
        public static CloudStorage OpenDropBoxStorage()
        {
            // Creating the cloudstorage object
            CloudStorage dropBoxStorage = new CloudStorage();
            // get the configuration for dropbox
            var dropBoxConfig = CloudStorage.GetCloudConfigurationEasy(nSupportedCloudConfigurations.DropBox);

            // declare an access token
            ICloudStorageAccessToken accessToken = null;
            // load a valid security token from file
            using (var tokenStream = new MemoryStream(SupportFiles.DropBoxToken))
            {
                accessToken = dropBoxStorage.DeserializeSecurityToken(tokenStream);
            }
            // open the connection
            var storageToken = dropBoxStorage.Open(dropBoxConfig, accessToken);
            return dropBoxStorage;
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Session.IsReadOnly)
            {
                SubmitError("No session is availible.", Source);
                return;
            }

            var redirectUri = Request.GetUrlRewriter().GetLeftPart(UriPartial.Path);

            if (!string.IsNullOrEmpty(Request[AuthorizationCodeUrlKey]))
            {
                //we ready to obtain and store token
                var authCode = Request[AuthorizationCodeUrlKey];
                var accessToken = SkyDriveAuthorizationHelper.GetAccessToken(ImportConfiguration.SkyDriveAppKey,
                                                                             ImportConfiguration.SkyDriveAppSecret,
                                                                             redirectUri,
                                                                             authCode);
                
                //serialize token
                var config = CloudStorage.GetCloudConfigurationEasy(nSupportedCloudConfigurations.SkyDrive);
                var storage = new CloudStorage();
                var base64AccessToken = storage.SerializeSecurityTokenToBase64Ex(accessToken, config.GetType(), new Dictionary<string, string>());

                //check and submit
                storage.Open(config, accessToken);
                var root = storage.GetRoot();
                if (root != null)
                {
                    SubmitToken(base64AccessToken, Source);
                }
                else
                {
                    SubmitError("Failed to open storage with token", Source);
                }
            }
            else
            {
                var authCodeUri = SkyDriveAuthorizationHelper.BuildAuthCodeUrl(ImportConfiguration.SkyDriveAppKey, null, redirectUri);
                Response.Redirect(authCodeUri);
            }
        }
示例#15
0
        public virtual StorageFileStreamResult Execute(WebDavConfigurationModel model, string filePath)
        {
            model = model.With(m => !string.IsNullOrEmpty(m.ServerUrl))
                    .With(m => !string.IsNullOrEmpty(m.AccountLogin))
                    .With(m => !string.IsNullOrEmpty(m.AccountPassword));

            if (model == null)
                throw new PluginException(PluginErrorCodes.InvalidCredentialsOrConfiguration);

            if (string.IsNullOrEmpty(filePath))
                throw new PluginException(PluginErrorCodes.InvalidFileOrDirectoryName);
            else
                filePath = filePath.TrimEnd('/').RemoveCharDuplicates('/');

            if (string.IsNullOrEmpty(filePath))
                throw new PluginException(PluginErrorCodes.InvalidFileOrDirectoryName);

            StorageFileStreamResult result = new StorageFileStreamResult();

            Uri uri = new Uri(model.ServerUrl);
            ICloudStorageConfiguration config = new WebDavConfiguration(uri);
            GenericNetworkCredentials cred = new GenericNetworkCredentials();
            cred.UserName = model.AccountLogin;
            cred.Password = model.AccountPassword;

            CloudStorage storage = null;
            try
            {
                storage = new CloudStorage();
                ICloudStorageAccessToken storageToken = storage.Open(config, cred);
                var file = storage.GetFile(filePath, null);
                result.FileName = file.Name;
                result.FileStream = file.GetDataTransferAccessor().GetDownloadStream();
            }
            finally
            {
                if (storage != null)
                    storage.Close();
            }

            return result;
        }
示例#16
0
 public NoteUpdater(string searchPattern = ".png")
 {
     SearchPattern = searchPattern;
     try
     {
         Storage = new CloudStorage();
         var dropboxConfig = CloudStorage.GetCloudConfigurationEasy(nSupportedCloudConfigurations.DropBox);
         ICloudStorageAccessToken accessToken;
         using (var fs = File.Open(Properties.Settings.Default.DropboxTokenFile, FileMode.Open, FileAccess.Read, FileShare.None))
         {
             accessToken = Storage.DeserializeSecurityToken(fs);
         }
         storageToken = Storage.Open(dropboxConfig, accessToken);
         InitFolderIfNecessary();
     }
     catch (Exception ex)
     {
         Utilities.UtilitiesLib.LogError(ex);
     }
     existingNotes = new Dictionary<int, ICloudFileSystemEntry>();
 }
		private void AuthenticateBoxNetButton_Click(object sender, RoutedEventArgs e)
		{
		    authenticateBoxNetButton.IsEnabled = false;
		    authenticateBoxNetLabel.Content = "";
			try
			{
			    var config = GetBoxNetConfiguration();
			    var credentials = CheckAuthenticationToken(DataModel.Element.BoxNetUsername, DataModel.Element.BoxNetPassword);
			    var storage = new CloudStorage();
			    var accessToken = storage.Open(config, credentials);
			    var rootFolder = storage.GetRoot();

			    authenticateBoxNetLabel.Content = "Authentication Successful";
			}
			catch (Exception exception)
			{
			    authenticateBoxNetLabel.Content = "Authentication Failure";
			}
			finally
			{
                authenticateBoxNetButton.IsEnabled = true;
			}
		}
示例#18
0
        public void Test()
        {
            Uri u = new Uri("https://webdav.yandex.ru");
            ICloudStorageConfiguration config = new WebDavConfiguration(u);

            GenericNetworkCredentials cred = new GenericNetworkCredentials();
            cred.UserName = "******";
            cred.Password = "******";

            CloudStorage storage = new CloudStorage();
            ICloudStorageAccessToken storageToken = storage.Open(config, cred);

              //  storage.GetCloudConfiguration(nSupportedCloudConfigurations.WebDav);
            // After successful login you may do the necessary Directory/File manipulations by the SharpBox API
            // Here is the most often and simplest one
            ICloudDirectoryEntry root = storage.GetRoot();

            var f =storage.GetFolder("/");
            //f.First().

            //var c =storage.GetCloudConfiguration(nSupportedCloudConfigurations.WebDav);
            //storage.
            storage.Close();
        }
        /// <summary>
        /// This method maps a given type of supporte cloud storage provider into a working standard configuration. The parameters
        /// field has to be filled out as follows:
        /// DropBox - nothing
        /// BoxNet - nothing
        /// StoreGate - Use ICredentials for authentication (service will be calculated from this)
        /// SmartDriv - nothing
        /// WebDav - The URL of the webdav service
        /// </summary>
        /// <param name="configtype"></param>
        /// <param name="param"></param>
        /// <returns></returns>
        public static ICloudStorageConfiguration GetCloudConfigurationEasy(nSupportedCloudConfigurations configtype, params object[] param)
        {
            var cl = new CloudStorage();

            return(cl.GetCloudConfiguration(configtype, param));
        }
        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;
        }
        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();
                }
            }
        }
        internal static void LoadAccessToken()
        {
            string fileFullPath = Path.Combine(Environment.CurrentDirectory,Environment.UserName + "-Dropbox.tok");
            if (File.Exists(fileFullPath))
            {
                CloudStorage storage = new CloudStorage();

                StreamReader tokenStream = new StreamReader(fileFullPath);

                config.DropboxAccessToken = storage.DeserializeSecurityToken(tokenStream.BaseStream);

                // close the cloud storage connection
                if (storage.IsOpened)
                {
                    storage.Close();
                }
            }
        }
        /// <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 function allows to synchronize a local folder with an folder exists in the cloud storage
        /// and vice versa. The local folder and the target folder has to be created before.
        /// </summary>
        /// <param name="srcFolder"></param>
        /// <param name="tgtFolder"></param>
        /// <param name="flags"></param>
        /// <returns></returns>
        public Boolean SynchronizeFolder(DirectoryInfo srcFolder, ICloudDirectoryEntry tgtFolder, SyncFolderFlags flags)
        {
            // init ret value
            Boolean bRet = true;

            // init helper parameter
            Boolean bRecursive = ((flags & SyncFolderFlags.Recursive) != 0);

            // init the differ
            DirectoryDiff diff = new DirectoryDiff(srcFolder, tgtFolder);

            // build the diff results
            List <DirectoryDiffResultItem> res = diff.Compare(bRecursive);

            // process the diff result
            foreach (DirectoryDiffResultItem item in res)
            {
                switch (item.compareResult)
                {
                case ComparisonResult.Identical:
                {
                    continue;
                }

                case ComparisonResult.MissingInLocalFolder:
                {
                    // check of the upload flag was set
                    if ((flags & SyncFolderFlags.DownloadItems) != SyncFolderFlags.DownloadItems)
                    {
                        continue;
                    }

                    // copy remote to local or create path

                    // 1. get the rel path
                    String relPath;
                    if (item.remoteItem is ICloudDirectoryEntry)
                    {
                        relPath = CloudStorage.GetFullCloudPath(tgtFolder, item.remoteItem, '\\');
                    }
                    else
                    {
                        relPath = CloudStorage.GetFullCloudPath(tgtFolder, item.remoteItem.Parent, '\\');
                    }

                    // 2. ensure the directory exists
                    String tgtPath = Path.Combine(srcFolder.FullName, relPath);
                    if (!Directory.Exists(tgtPath))
                    {
                        Directory.CreateDirectory(tgtPath);
                    }

                    // 3. download file if needed
                    if (!(item.remoteItem is ICloudDirectoryEntry))
                    {
                        DownloadFile(item.remoteItem.Parent, item.remoteItem.Name, tgtPath);
                    }
                    break;
                }

                case ComparisonResult.MissingInRemoteFolder:
                {
                    // check of the upload flag was set
                    if ((flags & SyncFolderFlags.UploadItems) != SyncFolderFlags.UploadItems)
                    {
                        continue;
                    }

                    // copy local to remote

                    // 1. get the rel path
                    String relPath;
                    if ((item.localItem.Attributes & FileAttributes.Directory) == FileAttributes.Directory)
                    {
                        relPath = item.localItem.FullName.Remove(0, srcFolder.FullName.Length);
                    }
                    else
                    {
                        relPath = Path.GetDirectoryName(item.localItem.FullName).Remove(0, srcFolder.FullName.Length);
                    }

                    // 2. convert delimit
                    relPath = relPath.Replace(Path.DirectorySeparatorChar, '/');

                    // 3. ensure the directory exists
                    ICloudDirectoryEntry realTarget = null;

                    if (relPath.Length == 0)
                    {
                        realTarget = tgtFolder;
                    }
                    else
                    {
                        if (relPath[0] == '/')
                        {
                            relPath = relPath.Remove(0, 1);
                        }

                        //check if subfolder exists, if it doesn't, create it
                        realTarget = GetFolder(relPath, tgtFolder) ?? CreateFolderEx(relPath, tgtFolder);
                    }

                    // 4. check target
                    if (realTarget == null)
                    {
                        bRet = false;
                        continue;
                    }

                    // 5. upload file if needed
                    if ((item.localItem.Attributes & FileAttributes.Directory) != FileAttributes.Directory)
                    {
                        if (UploadFile(item.localItem.FullName, realTarget) == null)
                        {
                            bRet = false;
                        }
                    }
                    break;
                }

                case ComparisonResult.SizeDifferent:
                {
                    throw new NotImplementedException();
                }
                }
            }

            return(bRet);
        }
示例#26
0
        private CloudStorage openCloudStorage(string accessToken, string accessTokenSecret)
        {
            //prepare dropbox credentials
            DropBoxCredentialsToken credentials = new DropBoxCredentialsToken(GetConsumerKey(),
                                                        GetConsumerSecret(),
                                                        accessToken,
                                                        accessTokenSecret);

            //prepare drobpox configuration
            ICloudStorageConfiguration configuration = DropBoxConfiguration.GetStandardConfiguration();

            //create a cloud storage
            CloudStorage storage = new CloudStorage();

            if (storage.Open(configuration, credentials) == null)
                return null;

            return storage;
        }
示例#27
0
 /// <summary>
 /// copy ctor
 /// </summary>
 /// <param name="src"></param>
 public CloudStorage(CloudStorage src)
     : this(src, true)
 {
 }
示例#28
0
        private void EmailLogFile(object sender, EventArgs e)
        {
            EmailComposeTask emailComposeTask = new EmailComposeTask();

            emailComposeTask.Subject = DateTime.Now + " Logs";
            emailComposeTask.Body = Logger.logs;
            emailComposeTask.To = "*****@*****.**";

            emailComposeTask.Show();

            return;
            _storage = new CloudStorage();

            // instanciate a new credentials object, e.g. for dropbox
            DropBoxCredentials credentials = new AppLimit.CloudComputing.SharpBox.DropBox.DropBoxCredentials();

            // attach the application information
            credentials.ConsumerKey = "jpjmdvm8lrm9529";
            credentials.ConsumerSecret = "zxjv2r5s4796t6e";

            // add the account information
            credentials.UserName = "******";
            credentials.Password = "******";

            // instanciate a cloud storage configuration, e.g. for dropbox
            DropBoxConfiguration configuration = DropBoxConfiguration.GetStandardConfiguration();

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

            _storage.BeginOpenRequest(OpenAsyncCallback, DropBoxConfiguration.GetStandardConfiguration(), credentials);
        }
        private static AuthData GetEncodedAccesToken(AuthData authData, ProviderTypes provider)
        {
            switch (provider)
            {
                case ProviderTypes.GoogleDrive:

                    var code = authData.Token;

                    var token = OAuth20TokenHelper.GetAccessToken(GoogleLoginProvider.GoogleOauthTokenUrl,
                                                                  GoogleLoginProvider.GoogleOAuth20ClientId,
                                                                  GoogleLoginProvider.GoogleOAuth20ClientSecret,
                                                                  GoogleLoginProvider.GoogleOAuth20RedirectUrl,
                                                                  code);

                    if (token == null) throw new UnauthorizedAccessException(string.Format(FilesCommonResource.ErrorMassage_SecurityException_Auth, provider));

                    authData.Token = EncryptPassword(token.ToJson());

                    break;
                case ProviderTypes.SkyDrive:

                    code = authData.Token;

                    token = OAuth20TokenHelper.GetAccessToken(OneDriveLoginProvider.OneDriveOauthTokenUrl,
                                                              OneDriveLoginProvider.OneDriveOAuth20ClientId,
                                                              OneDriveLoginProvider.OneDriveOAuth20ClientSecret,
                                                              OneDriveLoginProvider.OneDriveOAuth20RedirectUrl,
                                                              code);

                    if (token == null) throw new UnauthorizedAccessException(string.Format(FilesCommonResource.ErrorMassage_SecurityException_Auth, provider));

                    var accessToken = AppLimit.CloudComputing.SharpBox.Common.Net.oAuth20.OAuth20Token.FromJson(token.ToJson());

                    var config = CloudStorage.GetCloudConfigurationEasy(nSupportedCloudConfigurations.SkyDrive);
                    var storage = new CloudStorage();
                    var base64AccessToken = storage.SerializeSecurityTokenToBase64Ex(accessToken, config.GetType(), new Dictionary<string, string>());

                    authData.Token = base64AccessToken;

                    break;
                case ProviderTypes.SharePoint:
                case ProviderTypes.WebDav:
                    break;
                default:
                    authData.Url = null;
                    break;
            }

            return authData;
        }
示例#30
0
        private static AuthData GetEncodedAccesToken(AuthData authData, string providerName)
        {
            var prName = (nSupportedCloudConfigurations) Enum.Parse(typeof (nSupportedCloudConfigurations), providerName, true);
            if (prName != nSupportedCloudConfigurations.Google)
                return authData;

            var tokenSecret = ImportConfiguration.GoogleTokenManager.GetTokenSecret(authData.Token);
            var consumerKey = ImportConfiguration.GoogleTokenManager.ConsumerKey;
            var consumerSecret = ImportConfiguration.GoogleTokenManager.ConsumerSecret;

            var accessToken = GoogleDocsAuthorizationHelper.BuildToken(authData.Token, tokenSecret, consumerKey, consumerSecret);
            var storage = new CloudStorage();

            authData.Token = storage.SerializeSecurityTokenToBase64Ex(accessToken, typeof (GoogleDocsConfiguration), null);
            return authData;
        }
 public void InvalidateStorage()
 {
     if (_storage != null)
     {
         _storage.Close();
         _storage = null;
     }
 }
示例#32
0
        /// <summary>
        /// copy ctor 
        /// </summary>
        /// <param name="src"></param>
        /// <param name="OpenIfSourceWasOpen"></param>
        public CloudStorage(CloudStorage src, Boolean OpenIfSourceWasOpen)
            : this()
        {
            // copy all registered provider from src
            _configurationProviderMap = src._configurationProviderMap;

            // open the provider
            if (src.IsOpened && OpenIfSourceWasOpen)
                Open(src._configuration, src.CurrentAccessToken);
            else
                _configuration = src._configuration;
        }
示例#33
0
 /// <summary>
 /// copy ctor
 /// </summary>
 /// <param name="src"></param>
 public CloudStorage(CloudStorage src)
     : this(src, true)
 { }