Beispiel #1
0
        public async Task <bool> ExecuteAsync(CancellationToken ct)
        {
            if (Items.Length == 0)
            {
                Log.LogError("No items were provided for upload.");
                return(false);
            }

            Log.LogMessage("Begin uploading blobs to Azure account {0} in container {1}.",
                           AccountName,
                           ContainerName);

            try
            {
                AzureStorageUtils blobUtils = new AzureStorageUtils(AccountName, AccountKey, ContainerName);

                List <Task> uploadTasks = new List <Task>();

                foreach (var item in Items)
                {
                    uploadTasks.Add(Task.Run(async() =>
                    {
                        string relativeBlobPath = item.GetMetadata("RelativeBlobPath");

                        if (string.IsNullOrEmpty(relativeBlobPath))
                        {
                            throw new Exception(string.Format("Metadata 'RelativeBlobPath' is missing for item '{0}'.", item.ItemSpec));
                        }

                        if (!File.Exists(item.ItemSpec))
                        {
                            throw new Exception(string.Format("The file '{0}' does not exist.", item.ItemSpec));
                        }

                        BlobClient blobReference = blobUtils.GetBlob(relativeBlobPath);

                        if (!Overwrite && await blobReference.ExistsAsync())
                        {
                            if (PassIfExistingItemIdentical)
                            {
                                if (await blobReference.IsFileIdenticalToBlobAsync(item.ItemSpec))
                                {
                                    return;
                                }
                            }

                            throw new Exception(string.Format("The blob '{0}' already exists.", relativeBlobPath));
                        }

                        CancellationTokenSource timeoutTokenSource = new CancellationTokenSource(TimeSpan.FromMinutes(UploadTimeoutInMinutes));

                        using (Stream localFileStream = File.OpenRead(item.ItemSpec))
                        {
                            await blobReference.UploadAsync(localFileStream, timeoutTokenSource.Token);
                        }
                    }));
                }

                await Task.WhenAll(uploadTasks);

                Log.LogMessage("Upload to Azure is complete, a total of {0} items were uploaded.", Items.Length);
            }
            catch (Exception e)
            {
                Log.LogErrorFromException(e, true);
            }

            return(!Log.HasLoggedErrors);
        }