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);
			});
		}
Пример #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(); }
        }
Пример #3
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;
        }
Пример #4
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();
        }
        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;
        }
Пример #10
0
        public ActionResult GridViewPartialUpdate(inventarioImportaciones.Models.productos item)
        {
            var model = db.productos_List;
            if (ModelState.IsValid)
            {
                try
                {
                    var modelItem = model.FirstOrDefault(it => it.Codigo == item.Codigo);
                    if (item.Imagen.Length!=item.ImagenSelect.Length)
                    {
                        item.DirImagen = "";
                        string path = @"C:\Visual .net\DanielAsp";
                        string filename = path+"\\"+item.Nombre;
                        var fsC = new BinaryWriter(new FileStream( filename + ".jpg", FileMode.Append, FileAccess.Write));
                        fsC.Write(item.ImagenSelect);
                        fsC.Close();

                        CloudStorage dropBoxStorage = new CloudStorage();
                        var dropBoxConfig = CloudStorage.GetCloudConfigurationEasy(nSupportedCloudConfigurations.DropBox);
                        ICloudStorageAccessToken accessToken = null;
                        // load a valid security token from file
                        using (FileStream fs = System.IO.File.Open(@"C:\Visual .net\InventariosImportaciones\InventariosImportaciones\SharpDropBox.Token",
                        FileMode.Open, FileAccess.Read,
                        FileShare.None))
                        {
                            accessToken = dropBoxStorage.DeserializeSecurityToken(fs);
                        }

                        var storageToken = dropBoxStorage.Open(dropBoxConfig, accessToken);

                        var publicFolder = dropBoxStorage.GetFolder("/");
                        // GetFolder("/Public");
                        foreach (var fof in publicFolder)
                        {
                            // check if we have a directory
                            Boolean bIsDirectory = fof is ICloudDirectoryEntry;
                            // output the info
                            Console.WriteLine("{0}: {1}", bIsDirectory ? "DIR" : "FIL", fof.Name);
                        }

                        String srcFile = Environment.ExpandEnvironmentVariables(filename + ".jpg");
                      ICloudFileSystemEntry fileUploaded=  dropBoxStorage.UploadFile(srcFile, publicFolder);

                      ICloudDirectoryEntry fEntry = dropBoxStorage.GetFolder("/");
                      ICloudFileSystemEntry fszz = dropBoxStorage.GetFileSystemObject("Gamma Quick Kids 21in.jpg", fEntry);

                      string d = DropBoxStorageProviderTools.GetPublicObjectUrl(storageToken, fszz).AbsoluteUri;
                      Console.WriteLine(d);
                        dropBoxStorage.DownloadFile(publicFolder, item.Nombre + ".jpg", Environment.ExpandEnvironmentVariables(path));

                        dropBoxStorage.Close();
                    }
                    if (modelItem != null)
                    {
                        this.UpdateModel(modelItem);
                        db.SaveChanges();
                    }
                }
                catch (Exception e)
                {
                    ViewData["EditError"] = e.Message;
                }
            }
            else
                ViewData["EditError"] = "Please, correct all errors.";
            return PartialView("_GridViewPartial", model.ToList());
        }
        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");
        }
Пример #12
0
        public IStorageFolder GetDirectoryInfo(IStorageFolder parentFolder)
        {
            IStorageFolder folder = null;
            CloudStorage cloudStorage = null;

            try
            {
                cloudStorage = new CloudStorage();
                cloudStorage.Open(config, credentials);
                folder = getDirectoryInfo(parentFolder, cloudStorage);
            }
            finally
            {
                if (cloudStorage != null && cloudStorage.IsOpened)
                    cloudStorage.Close();
            }

            return folder;
        }
Пример #13
0
        public byte[] GetFile(IStorageFile file)
        {
            byte[] fileData = null;
            CloudStorage cloudStorage = null;

            try
            {
                cloudStorage = new CloudStorage();
                cloudStorage.Open(config, credentials);

                ICloudDirectoryEntry cloudDirectoryEntry;
                
                if (file.ParentFolder == null)
                    cloudDirectoryEntry = cloudStorage.GetRoot();
                else
                    cloudDirectoryEntry = cloudStorage.GetFolder(file.ParentFolder.Path);

                if (cloudDirectoryEntry != null && cloudDirectoryEntry.Count != 0)
                {
                    var cloudFile = cloudDirectoryEntry.FirstOrDefault(f => f.Name == file.Name);
                    if (cloudFile != null)
                    {
                        using (var ms = new MemoryStream())
                        {
                            cloudStorage.DownloadFile(cloudFile.Name, cloudDirectoryEntry, ms);
                            fileData = ms.GetBuffer();
                        }
                    }
                }
            }
            finally
            {
                if (cloudStorage != null && cloudStorage.IsOpened)
                    cloudStorage.Close();
            }

            return fileData;
        }
Пример #14
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;
        }