Esempio n. 1
0
        public async Task <string> UploadBlob(string containerName, string path, IProgress <UploadProgressUpdate> progress)
        {
            await Initialization;
            CloudBlobContainer container = blobClient.GetContainerReference(containerName);
            await container.CreateIfNotExistsAsync();

            var blob = container.GetBlockBlobReference(System.IO.Path.GetFileName(path));

            var tcs = new TaskCompletionSource <string>();

            BlobTransfer transferUpload = new BlobTransfer();

            transferUpload.TransferProgressChanged += (object sender, BlobTransfer.BlobTransferProgressChangedEventArgs e) =>
            {
                progress.Report(new UploadProgressUpdate()
                {
                    Percentage  = e.ProgressPercentage,
                    Description = (e.Speed / 1024).ToString("N2") + "KB/s"
                });
            };
            transferUpload.TransferCompleted += (object sender, System.ComponentModel.AsyncCompletedEventArgs e) =>
            {
                tcs.TrySetResult("");
            };
            transferUpload.UploadBlobAsync(blob, path);

            await tcs.Task;

            blob.Properties.ContentType = System.Web.MimeMapping.GetMimeMapping(System.IO.Path.GetFileName(path));
            await blob.SetPropertiesAsync();

            return(blob.Uri.ToString());
        }
        internal void CancelTransfer(BlobTransfer transferItem)
        {
            var payload = new BlobTransferCancelRequestedEvent();

            payload.Transfer = transferItem;

            Messenger.Default.Send <BlobTransferCancelRequestedEvent>(payload);

            this.Transfers.Remove(transferItem);
        }
Esempio n. 3
0
        private void OnBlobDownloadRequested(BlobDownloadRequestedEvent payload)
        {
            var destinationFile = payload.Target;
            var source          = payload.Source.Uri;

            BackgroundDownloader downloader = new BackgroundDownloader();
            DownloadOperation    download   = downloader.CreateDownload(source, destinationFile);

            var transfer = new BlobTransfer();

            transfer.Identifier      = download.Guid;
            transfer.PercentComplete = 0;
            transfer.FileName        = payload.FileName;
            transfer.FullPath        = payload.FullPath;

            this.TransferHistory.Add(transfer);

            HandleDownloadAsync(download, true);
        }
        protected override string ProcessRemoteCommand(string name, string[] args)
        {
            if (name != "upload")
                throw new ArgumentException("Invalid command.");

            var entryResults = Util.Files.GetDirectoryEntry(
                new GetDirectoryEntryCommand
                {
                    Path = this.Context.SourceDirectory,
                    IncludeRootPath = true,
                    Recurse = this.Recursive
                }
            );

            var matches = Util.Files.Comparison.GetMatches(
                this.Context.SourceDirectory,
                entryResults.Entry,
                this.FileMasks
            ).OfType<FileEntryInfo>().ToList();

            if (matches.Count == 0)
            {
                this.LogWarning("No files matched with the specified mask.");
                return null;
            }

            this.LogDebug("Mask matched {0} file(s).", matches.Count);

            this.LogInformation("Contacting Windows Azure Storage Service...");
            var account = new CloudStorageAccount(new StorageCredentials(this.AccountName, this.AccessKey), true);
            var blobClient = account.CreateCloudBlobClient();

            this.LogDebug("Getting container {0}...", this.Container);
            var container = blobClient.GetContainerReference(this.Container);
            if (container.CreateIfNotExists())
                this.LogDebug("Container created.");
            else
                this.LogDebug("Container found.");

            var targetFolder = (this.TargetFolder ?? "").Trim('/');
            if (targetFolder != string.Empty)
                targetFolder += "/";

            this.LogDebug("Uploading to {0}...", targetFolder);
            foreach (var fileInfo in matches)
            {
                var fileName = targetFolder + fileInfo.Path.Substring(this.Context.SourceDirectory.Length).Replace(Path.DirectorySeparatorChar, '/').Trim('/');
                this.LogInformation("Transferring {0} to {1}...", fileInfo.Path, fileName);
                try
                {
                    var blob = container.GetBlockBlobReference(fileName);

                    var transfer = new BlobTransfer(blob);
                    transfer.TransferProgressChanged += (s, e) =>
                    {
                        this.LogDebug("Upload Progress: {0}/{1} ({2}%) - Est. Time Remaining: {3}", e.BytesSent, e.TotalBytesToSend, e.ProgressPercentage, e.TimeRemaining);
                    };
                    transfer.TransferCompleted += (s, e) =>
                    {
                        this.LogDebug("File {0} uploaded successfully.", fileName);
                    };

                    var result = transfer.UploadBlobAsync(fileInfo.Path);

                    int handled = WaitHandle.WaitAny(new[] { result.AsyncWaitHandle, this.Context.CancellationToken.WaitHandle });
                    if (handled == 1)
                    {
                        result.Cancel();
                        this.ThrowIfCanceledOrTimeoutExpired();
                    }
                }
                catch (Exception ex)
                {
                    if (this.ResumeNextOnError)
                        this.LogError("Upload failed: {0}", ex.Message);
                    else
                        throw;
                }
            }

            return null;
        }
Esempio n. 5
0
        protected override string ProcessRemoteCommand(string name, string[] args)
        {
            if (name != "upload")
            {
                throw new ArgumentException("Invalid command.");
            }

            var entryResults = Util.Files.GetDirectoryEntry(
                new GetDirectoryEntryCommand
            {
                Path            = this.Context.SourceDirectory,
                IncludeRootPath = true,
                Recurse         = this.Recursive
            }
                );

            var matches = Util.Files.Comparison.GetMatches(
                this.Context.SourceDirectory,
                entryResults.Entry,
                this.FileMasks
                ).OfType <FileEntryInfo>().ToList();

            if (matches.Count == 0)
            {
                this.LogWarning("No files matched with the specified mask.");
                return(null);
            }

            this.LogDebug("Mask matched {0} file(s).", matches.Count);

            this.LogInformation("Contacting Windows Azure Storage Service...");
            var account    = new CloudStorageAccount(new StorageCredentials(this.AccountName, this.AccessKey), true);
            var blobClient = account.CreateCloudBlobClient();

            this.LogDebug("Getting container {0}...", this.Container);
            var container = blobClient.GetContainerReference(this.Container);

            if (container.CreateIfNotExists())
            {
                this.LogDebug("Container created.");
            }
            else
            {
                this.LogDebug("Container found.");
            }

            var targetFolder = (this.TargetFolder ?? "").Trim('/');

            if (targetFolder != string.Empty)
            {
                targetFolder += "/";
            }

            this.LogDebug("Uploading to {0}...", targetFolder);
            foreach (var fileInfo in matches)
            {
                var fileName = targetFolder + fileInfo.Path.Substring(this.Context.SourceDirectory.Length).Replace(Path.DirectorySeparatorChar, '/').Trim('/');
                this.LogInformation("Transferring {0} to {1}...", fileInfo.Path, fileName);
                try
                {
                    var blob = container.GetBlockBlobReference(fileName);

                    var transfer = new BlobTransfer(blob);
                    transfer.TransferProgressChanged += (s, e) =>
                    {
                        this.LogDebug("Upload Progress: {0}/{1} ({2}%) - Est. Time Remaining: {3}", e.BytesSent, e.TotalBytesToSend, e.ProgressPercentage, e.TimeRemaining);
                    };
                    transfer.TransferCompleted += (s, e) =>
                    {
                        this.LogDebug("File {0} uploaded successfully.", fileName);
                    };

                    var result = transfer.UploadBlobAsync(fileInfo.Path);

                    int handled = WaitHandle.WaitAny(new[] { result.AsyncWaitHandle, this.Context.CancellationToken.WaitHandle });
                    if (handled == 1)
                    {
                        result.Cancel();
                        this.ThrowIfCanceledOrTimeoutExpired();
                    }
                }
                catch (Exception ex)
                {
                    if (this.ResumeNextOnError)
                    {
                        this.LogError("Upload failed: {0}", ex.Message);
                    }
                    else
                    {
                        throw;
                    }
                }
            }

            return(null);
        }