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;
        }
Exemplo n.º 2
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();
            }
        }
 public void InvalidateStorage()
 {
     if (_storage != null)
     {
         _storage.Close();
         _storage = null;
     }
 }
Exemplo n.º 4
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);
        }
Exemplo n.º 5
0
 public void Close()
 {
     try
     {
         // close the connection
         m_dropBoxStorage.Close();
         m_initialize = false;
     }
     catch (Exception err)
     {
         m_initialize = false;
     }
 }
        public int UploadFiles(IEnumerable <string> files)
        {
            if (files == null)
            {
                return(0);
            }

            if (_accessToken == null)
            {
                throw new InvalidOperationException("Connection is not established.");
            }

            var uploadedCount = 0;

            _cloudStorage.Open(_configuration, _accessToken);

            var filesSize       = GetFilesSize(files as string[]);
            var availableMemory = GetAvailableMemory();

            if (filesSize > availableMemory)
            {
                _cloudStorage.Close();
                throw new OutOfMemoryException(string.Format("Available memory in the cloud storage: {0}",
                                                             availableMemory));
            }

            if (!DirectoryExists(ApplicationFolderPath))
            {
                _cloudStorage.CreateFolder(ApplicationFolderPath);
            }

            var appFolder = _cloudStorage.GetFolder(ApplicationFolderPath);


            foreach (var file in files)
            {
                if (File.Exists(file))
                {
                    OnUploadFileStarted(new UploadFileStartedEventArgs(file));
                    try
                    {
                        _cloudStorage.UploadFile(file, appFolder, UploadProgressChangedCallback);
                    }
                    catch (SharpBoxException)
                    {
                        OnUploadFileCanceled(new UploadFileCanceledEventArgs(file));

                        return(uploadedCount);
                    }
                    uploadedCount++;
                    OnUploadFileCompleted(new UploadFileCompletedEventArgs(file));
                }
            }

            _cloudStorage.Close();

            return(uploadedCount);
        }
Exemplo n.º 7
0
        internal static void CloseCouldStorage(Form1 form, CloudStorage cloudStorage)
        {
            ToolStripStatusLabel toolStripStatusLabel = form.toolStripStatusLabel;

            if (!IsCloudStorageOpen(cloudStorage))
            {
                return;
            }

            form.LastDropboxFolder = String.Empty;
            cloudStorage.Close();
            PasswordUtil.UpdateParameter("LastDropboxAccessToken", String.Empty); //ConfigUtil.UpdateParameter("LastDropboxAccessToken", String.Empty);

            toolStripStatusLabel.Text = LanguageUtil.GetCurrentLanguageString("DropboxLogOut", className);
        }
Exemplo n.º 8
0
        static void Main(string[] args)
        {
            // Creating the cloudstorage object
            var 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 (FileStream fs = File.Open(strAccessToken, FileMode.Open, FileAccess.Read, FileShare.None))
                accessToken = dropBoxStorage.DeserializeSecurityToken(fs);

            // open the connection
            var storageToken = dropBoxStorage.Open(dropBoxConfig, accessToken);


            //
            // do what ever you want to
            //

            // get a specific directory in the cloud storage, e.g. /Public
            var root = dropBoxStorage.GetRoot();

            /*
             * foreach (var fof in root)
             * {
             *  // check if we have a directory
             *  Boolean bIsDirectory = fof is ICloudDirectoryEntry;
             *  // output the info
             *  Console.WriteLine("{0}: {1}", bIsDirectory ? "DIR" : "FIL", fof.Name );
             * }
             */
            // Folder
            //var folderEntryQq = dropBoxStorage.GetFolder("/Qq");
            //var folderEntryQqChild = dropBoxStorage.CreateFolder("QqChild", folderEntryQq);
            //var fileEntry = dropBoxStorage.UploadFile(@"C:\msdia80.dll", folderEntryQqChild);

            // Root
            var entryRoot = dropBoxStorage.GetRoot();
            var fileEntry = dropBoxStorage.UploadFile(@"C:\mpfmservicelog.txt", entryRoot);

            // close the connection
            dropBoxStorage.Close();
        }
        private void HandleDropboxAuth(object sender, NavigationRoutedEventArgs e)
        {
            if (_GeneratedToken == null && e.Uri.ToString().StartsWith(_UsedConfig.AuthorizationCallBack.ToString()))
            {
                _GeneratedToken = DropBoxStorageProviderTools.ExchangeDropBoxRequestTokenIntoAccessToken(_UsedConfig, Networks.DropBoxAuth.Key, Networks.DropBoxAuth.Secret, _CurrentRequestToken);

                (sender as Window).Close();

                CloudStorage cs = new CloudStorage();
                cs.Open(_UsedConfig, _GeneratedToken);

                Complete(cs.IsOpened, "Dropbox");
                //cs.SerializeSecurityToken(_GeneratedToken);

                cs.Close();
            }
            //throw new NotImplementedException();
        }
Exemplo n.º 10
0
        /// <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));
        }
Exemplo n.º 11
0
        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();
                }
            }
        }
Exemplo n.º 12
0
        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);
        }
Exemplo n.º 13
0
        private void Save(string fileName, MemoryStream stream)
        {
            var storage = new CloudStorage();

            storage.Open(_storageConfiguration, _accessToken);

            var cloudFolder = storage.GetFolder(_config.Cloud.BackupFolder);

            if (cloudFolder == null)
            {
                throw new Exception("Cloud folder not found: " + _config.Cloud.BackupFolder);
            }

            var cloudFile = storage.CreateFile(cloudFolder, fileName);

            using (var cloudStream = cloudFile.GetDataTransferAccessor().GetUploadStream(stream.Position))
                cloudStream.Write(stream.GetBuffer(), 0, (int)stream.Position);

            if (storage.IsOpened)
            {
                storage.Close();
            }
        }
Exemplo n.º 14
0
        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();
                }
            }
        }
Exemplo n.º 15
0
 public override void CloseConnection()
 {
     _client.Close();
     //base.CloseConnection();
 }
        public bool UploadFile(FileDescription fileDescription)
        {
            var appRootFolderPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);

            var fileSetId = RandomIdGenerator.GetBase36(7).ToLower();

            var ftpDestinationName     = String.Empty;
            var ftpDestinationFilePath = Path.Combine(appRootFolderPath, FtpDestinationFileName);

            if (File.Exists(ftpDestinationFilePath))
            {
                ftpDestinationName = File.ReadAllText(ftpDestinationFilePath).Trim();
            }

            var fileSetName = String.Format("{0}{1}_{2}_cwl",
                                            !String.IsNullOrEmpty(ftpDestinationName) ? String.Format("{0}_", ftpDestinationName) : String.Empty,
                                            Path.GetFileNameWithoutExtension(fileDescription.FilePath),
                                            fileSetId);

            try
            {
                var dropBoxStorage = new CloudStorage();
                var dropBoxConfig  = (DropBoxConfiguration)CloudStorage.GetCloudConfigurationEasy(nSupportedCloudConfigurations.DropBox);


                ICloudStorageAccessToken accessToken;
                using (var fs = File.Open(
                           Path.Combine(appRootFolderPath, SecurityTokenFileName),
                           FileMode.Open,
                           FileAccess.Read,
                           FileShare.None))
                {
                    accessToken = dropBoxStorage.DeserializeSecurityToken(fs);
                }
                dropBoxStorage.Open(dropBoxConfig, accessToken);
                var dropBoxRootFolder = dropBoxStorage.GetRoot();



                var destinationFolder = dropBoxStorage.GetFolder(fileSetName, dropBoxRootFolder, false) ??
                                        dropBoxStorage.CreateFolder(fileSetName, dropBoxRootFolder);

                dropBoxStorage.UploadFile(fileDescription.FilePath, destinationFolder);
                dropBoxStorage.UploadFile(ftpDestinationFilePath, destinationFolder);
                dropBoxStorage.UploadFile(new MemoryStream(Encoding.Default.GetBytes(fileDescription.Advertiser)), AdvertiserFileName, destinationFolder);
                dropBoxStorage.UploadFile(new MemoryStream(Encoding.Default.GetBytes(fileDescription.UserEmail)), EmailFileName, destinationFolder);
                dropBoxStorage.UploadFile(new MemoryStream(Encoding.Default.GetBytes(fileSetId)), IdFileName, destinationFolder);

                dropBoxStorage.Close();
            }
            catch (Exception ex)
            {
                File.WriteAllText("error.txt", String.Format("{0}{1}{2}", ex.Message, ex.StackTrace, Environment.NewLine));
                return(false);
            }

            var notificationRecipients         = String.Empty;
            var notificationRecipientsFilePath = Path.Combine(appRootFolderPath, NotificationRecipientsFileName);

            if (File.Exists(notificationRecipientsFilePath))
            {
                notificationRecipients = String.Join("; ", File.ReadAllText(notificationRecipientsFilePath).Trim().Split(';').Select(item => item.Trim()).Where(item => !String.IsNullOrEmpty(item)));
            }
            if (!String.IsNullOrEmpty(notificationRecipients))
            {
                try
                {
                    using (var client = new SmtpClient())
                        using (var mail = new MailMessage(SMTPLogin, notificationRecipients))
                        {
                            client.Port           = 587;
                            client.Credentials    = new NetworkCredential(SMTPLogin, SMTPPassword);
                            client.Host           = SMTPAddress;
                            client.DeliveryMethod = SmtpDeliveryMethod.Network;
                            client.EnableSsl      = true;

                            mail.Subject = String.Format("Client Weblink Alert: {0}", fileSetName);
                            mail.Body    = String.Format("{0}{4}{1}{4}{2}{4}{3}",
                                                         fileSetName,
                                                         fileDescription.Advertiser,
                                                         ftpDestinationName,
                                                         fileDescription.UserEmail,
                                                         Environment.NewLine);

                            client.Send(mail);
                        }
                }
                catch (Exception ex)
                {
                    File.WriteAllText("error.txt", String.Format("{0}{1}{2}", ex.Message, ex.StackTrace, Environment.NewLine));
                }
            }
            return(true);
        }
Exemplo n.º 17
0
        public StorageFolderResult Execute(WebDavConfigurationModel model, string path, int accountId)
        {
            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);
            }

            StorageFolderResult result = new StorageFolderResult();

            Uri uri = new Uri(model.ServerUrl);
            ICloudStorageConfiguration config = new WebDavConfiguration(uri);
            GenericNetworkCredentials  cred   = new GenericNetworkCredentials();

            cred.UserName = model.AccountLogin;
            cred.Password = model.AccountPassword;

            if (string.IsNullOrEmpty(path))
            {
                path = "/";
            }
            else
            {
                path = path.RemoveCharDuplicates('/');
            }
            if (!path.Equals("/", StringComparison.OrdinalIgnoreCase))
            {
                path = path.TrimEnd('/');
            }

            CloudStorage storage = null;

            try
            {
                storage = new CloudStorage();
                ICloudStorageAccessToken storageToken = storage.Open(config, cred);
                ICloudDirectoryEntry     directory    = storage.GetFolder(path, true);

                result.CurrentFolderName = directory.Name;
                result.CurrentFolderUrl  = path;
                path = path.TrimEnd('/');
                foreach (var entry in directory)
                {
                    var    dirEntry  = entry as ICloudDirectoryEntry;
                    string entryPath = string.Format(CultureInfo.InvariantCulture, "{0}{1}{2}", path, "/", entry.Name);
                    if (dirEntry != null)
                    {
                        result.AddItem(new StorageFolder
                        {
                            Name             = dirEntry.Name,
                            Path             = entryPath,
                            StorageAccountId = accountId
                        });
                    }
                    else
                    {
                        result.AddItem(new StorageFile
                        {
                            Name             = entry.Name,
                            Path             = entryPath,
                            StorageAccountId = accountId
                        });
                    }
                }

                StoragePathItem rootPath = new StoragePathItem
                {
                    Name = "/",
                    Url  = "/"
                };
                string relativePath = path.Trim('/').RemoveCharDuplicates('/');
                if (relativePath.Length > 0)
                {
                    string[]      pathItems       = relativePath.Split('/');
                    StringBuilder pathUrlsBuilder = new StringBuilder("/");
                    foreach (var pathItem in pathItems)
                    {
                        pathUrlsBuilder.Append(pathItem);
                        rootPath.AppendItem(new StoragePathItem
                        {
                            Name = pathItem,
                            Url  = pathUrlsBuilder.ToString()
                        });
                        pathUrlsBuilder.Append("/");
                    }
                }

                result.CurrentPath = rootPath;
            }
            finally
            {
                if (storage != null)
                {
                    storage.Close();
                }
            }

            return(result);
        }
Exemplo n.º 18
0
 public void CloseCloud()
 {
     m_dropBox.Close();
 }