Ejemplo n.º 1
0
        public async Task UndeleteBlobContainerAsync()
        {
            // Arrange
            BlobServiceClient   service       = GetServiceClient_SoftDelete();
            string              containerName = GetNewContainerName();
            BlobContainerClient container     = InstrumentClient(service.GetBlobContainerClient(containerName));
            await container.CreateAsync();

            await container.DeleteAsync();

            IList <BlobContainerItem> containers = await service.GetBlobContainersAsync(states : BlobContainerStates.Deleted).ToListAsync();

            BlobContainerItem containerItem = containers.Where(c => c.Name == containerName).FirstOrDefault();

            // It takes some time for the Container to be deleted.
            await Delay(30000);

            // Act
            Response <BlobContainerClient> response = await service.UndeleteBlobContainerAsync(
                containerItem.Name,
                containerItem.VersionId,
                GetNewContainerName());

            // Assert
            await response.Value.GetPropertiesAsync();

            // Cleanup
            await container.DeleteAsync();
        }
        public async void CreateNewBlobTwice_FalseShouldReturn()
        {
            var uniqueContainerName = Guid.NewGuid().ToString("N");

            AzureBlobContainerClient blobProvider = GetTestBlobProvider(ConnectionString, uniqueContainerName);
            string blobName = Guid.NewGuid().ToString("N");

            var blobContainerClient = new BlobContainerClient(ConnectionString, uniqueContainerName);
            var blobClient          = blobContainerClient.GetBlobClient(blobName);
            await blobClient.DeleteIfExistsAsync();

            Assert.False(blobClient.Exists());

            // create a new blob
            using (MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes("example")))
            {
                var isCreated = await blobProvider.CreateBlobAsync(blobName, stream, CancellationToken.None);

                Assert.True(isCreated);
                Assert.True(blobClient.Exists());
            }

            // create the blob again
            using (MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes("new example")))
            {
                var isCreated = await blobProvider.CreateBlobAsync(blobName, stream, CancellationToken.None);

                Assert.False(isCreated);
                Assert.True(blobClient.Exists());
            }

            await blobContainerClient.DeleteAsync();
        }
        public async Task DownloadAsyncTest()
        {
            // Create a temporary Lorem Ipsum file on disk that we can upload
            string downloadPath = _mockupService.CreateTempFile();
            // Create a temporary Lorem Ipsum file on disk that we can upload
            string path = _mockupService.CreateTempFile();

            // Get a reference to a container named "sample-container" and then create it
            string containerName          = _mockupService.Randomize(AppConstant.SAMPLE_CONTAINER_NAME);
            BlobContainerClient container = new BlobContainerClient(connectionString, containerName);
            await container.CreateAsync();

            try
            {
                // Get a reference to a blob
                string     blobName = _mockupService.Randomize(AppConstant.SAMPLE_FILE_NAME);
                BlobClient blob     = container.GetBlobClient(blobName);

                // Open the file and upload its data
                using (FileStream file = File.OpenRead(path))
                {
                    await blob.UploadAsync(file);
                }

                /**download test**/

                await _azureFileService.DownloadAsync(blobName, containerName, downloadPath);

                Assert.IsTrue(true);
            } finally
            {
                // delete file and container after compleating operation
                await container.DeleteAsync();
            }
        }
Ejemplo n.º 4
0
        public async Task deleteContainer(string containerName)
        {
            BlobContainerClient blobContainerClient = createOrGetContainer(containerName);

            Console.WriteLine("Deleting blob container...");
            await blobContainerClient.DeleteAsync();
        }
        public async void DownloadBlob_StreamShouldReturn()
        {
            var uniqueContainerName = Guid.NewGuid().ToString("N");

            AzureBlobContainerClient blobProvider = GetTestBlobProvider(ConnectionString, uniqueContainerName);
            string blobName = Guid.NewGuid().ToString("N");

            var blobContainerClient = new BlobContainerClient(ConnectionString, uniqueContainerName);
            var blobClient          = blobContainerClient.GetBlobClient(blobName);

            string blobContent = "example";

            // create a new blob
            using (MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes(blobContent)))
            {
                var isCreated = await blobProvider.CreateBlobAsync(blobName, stream, CancellationToken.None);

                Assert.True(isCreated);
                Assert.True(blobClient.Exists());
            }

            using Stream downloadStream = await blobProvider.GetBlobAsync(blobName, CancellationToken.None);

            using var reader = new StreamReader(downloadStream);
            Assert.Equal(blobContent, reader.ReadToEnd());

            await blobContainerClient.DeleteAsync();
        }
Ejemplo n.º 6
0
        public async Task BatchSetAccessTierAsync()
        {
            // Get a connection string to our Azure Storage account.
            string connectionString = ConnectionString;

            // Get a reference to a container named "sample-container" and then create it
            BlobServiceClient   service   = new BlobServiceClient(connectionString);
            BlobContainerClient container = service.GetBlobContainerClient(Randomize("sample-container"));
            await container.CreateAsync();

            try
            {
                // Create three blobs named "foo", "bar", and "baz"
                BlobClient foo = container.GetBlobClient("foo");
                BlobClient bar = container.GetBlobClient("bar");
                BlobClient baz = container.GetBlobClient("baz");
                await foo.UploadAsync(BinaryData.FromString("Foo!"));

                await bar.UploadAsync(BinaryData.FromString("Bar!"));

                await baz.UploadAsync(BinaryData.FromString("Baz!"));

                // Set the access tier for all three blobs at once
                BlobBatchClient batch = service.GetBlobBatchClient();
                await batch.SetBlobsAccessTierAsync(new Uri[] { foo.Uri, bar.Uri, baz.Uri }, AccessTier.Cool);
            }
            finally
            {
                // Clean up after the test when we're finished
                await container.DeleteAsync();
            }
        }
Ejemplo n.º 7
0
        public async Task ContainerSample()
        {
            // Instantiate a new BlobServiceClient using a connection string.
            BlobServiceClient blobServiceClient = new BlobServiceClient(TestConfigurations.DefaultTargetTenant.ConnectionString);

            // Instantiate a new BlobContainerClient
            BlobContainerClient blobContainerClient = blobServiceClient.GetBlobContainerClient($"mycontainer-{Guid.NewGuid()}");

            try
            {
                // Create new Container in the Service
                await blobContainerClient.CreateAsync();

                // List All Containers
                await foreach (var container in blobServiceClient.GetContainersAsync())
                {
                    Assert.IsNotNull(container.Value.Name);
                }

                // List Containers By Page
                await foreach (var page in blobServiceClient.GetContainersAsync().ByPage())
                {
                    Assert.NotZero(page.Values.Length);
                }
            }
            finally
            {
                // Delete Container in the Service
                await blobContainerClient.DeleteAsync();
            }
        }
        public async Task RenameBlobContainerAsync_SourceLeaseFailed()
        {
            // Arrange
            BlobServiceClient   service          = GetServiceClient_SharedKey();
            string              oldContainerName = GetNewContainerName();
            string              newContainerName = GetNewContainerName();
            BlobContainerClient container        = InstrumentClient(service.GetBlobContainerClient(oldContainerName));
            await container.CreateAsync();

            string leaseId = Recording.Random.NewGuid().ToString();

            BlobRequestConditions sourceConditions = new BlobRequestConditions
            {
                LeaseId = leaseId
            };

            // Act
            await TestHelper.AssertExpectedExceptionAsync <RequestFailedException>(
                service.RenameBlobContainerAsync(
                    sourceContainerName: oldContainerName,
                    destinationContainerName: newContainerName,
                    sourceConditions: sourceConditions),
                e => Assert.AreEqual(BlobErrorCode.LeaseNotPresentWithContainerOperation.ToString(), e.ErrorCode));

            // Cleanup
            await container.DeleteAsync();
        }
Ejemplo n.º 9
0
        public static async Task DeleteAsync(string account, string key, string containerName)
        {
            BlobServiceClient   blobServiceClient = new BlobServiceClient(Client.GetConnectionString(account, key));
            BlobContainerClient container         = blobServiceClient.GetBlobContainerClient(containerName);

            await container.DeleteAsync();
        }
        public async Task UploadAsync()
        {
            // Create a temporary Lorem Ipsum file on disk that we can upload
            string path = CreateTempFile(SampleFileContent);

            string connectionString = ConnectionString;


            BlobContainerClient container = new BlobContainerClient(connectionString, Randomize("sample-container"));
            await container.CreateAsync();

            try
            {
                BlobClient blob = container.GetBlobClient(Randomize("sample-file"));


                using (FileStream file = File.OpenRead(path))
                {
                    await blob.UploadAsync(file);
                }


                BlobProperties properties = await blob.GetPropertiesAsync();

                Assert.AreEqual(SampleFileContent.Length, properties.ContentLength);
            }
            finally
            {
                // Clean up after the test when we're finished
                await container.DeleteAsync();
            }
        }
        public async Task ErrorsAsync()
        {
            // Get a connection string to our Azure Storage account.
            string connectionString = ConnectionString;

            // Get a reference to a container named "sample-container" and then create it
            BlobContainerClient container = new BlobContainerClient(connectionString, Randomize("sample-container"));
            await container.CreateAsync();

            try
            {
                // Try to create the container again
                await container.CreateAsync();
            }
            catch (StorageRequestFailedException ex)
                when(ex.ErrorCode == BlobErrorCode.ContainerAlreadyExists)
                {
                    // Ignore any errors if the container already exists
                }
            catch (StorageRequestFailedException ex)
            {
                Assert.Fail($"Unexpected error: {ex}");
            }

            // Clean up after the test when we're finished
            await container.DeleteAsync();
        }
        public async Task <bool> DeleteContainer(string connectionString, string containerName)
        {
            BlobContainerClient blobContainerClient = new BlobContainerClient(connectionString, containerName);
            await blobContainerClient.DeleteAsync();

            return(true);
        }
        public async Task RenameBlobContainerAsync_SourceLease()
        {
            // Arrange
            BlobServiceClient   service          = GetServiceClient_SharedKey();
            string              oldContainerName = GetNewContainerName();
            string              newContainerName = GetNewContainerName();
            BlobContainerClient container        = InstrumentClient(service.GetBlobContainerClient(oldContainerName));
            await container.CreateAsync();

            string leaseId = Recording.Random.NewGuid().ToString();

            BlobLeaseClient leaseClient = InstrumentClient(container.GetBlobLeaseClient(leaseId));
            await leaseClient.AcquireAsync(duration : TimeSpan.FromSeconds(30));

            BlobRequestConditions sourceConditions = new BlobRequestConditions
            {
                LeaseId = leaseId
            };

            // Act
            BlobContainerClient newContainer = await service.RenameBlobContainerAsync(
                sourceContainerName : oldContainerName,
                destinationContainerName : newContainerName,
                sourceConditions : sourceConditions);

            // Assert
            await newContainer.GetPropertiesAsync();

            // Cleanup
            await newContainer.DeleteAsync();
        }
        public async Task DeleteAllBlobsAsync(string containerName)
        {
            var blobContainerClient = new BlobContainerClient(this.ConnectionString, containerName);
            await blobContainerClient.DeleteAsync();

            await blobContainerClient.CreateIfNotExistsAsync();
        }
        public async Task DownloadAsync()
        {
            // Create a temporary Lorem Ipsum file on disk that we can upload
            string originalPath = CreateTempFile(SampleFileContent);

            // Get a temporary path on disk where we can download the file
            string downloadPath = CreateTempPath();

            // Get a connection string to our Azure Storage account.
            string connectionString = ConnectionString;

            // Get a reference to a container named "sample-container" and then create it
            BlobContainerClient container = new BlobContainerClient(connectionString, Randomize("sample-container"));
            await container.CreateAsync();

            try
            {
                // Get a reference to a blob named "sample-file"
                BlobClient blob = container.GetBlobClient(Randomize("sample-file"));

                // First upload something the blob so we have something to download
                await blob.UploadAsync(File.OpenRead(originalPath));

                // Download the blob's contents and save it to a file
                await blob.DownloadToAsync(downloadPath);

                // Verify the contents
                Assert.AreEqual(SampleFileContent, File.ReadAllText(downloadPath));
            }
            finally
            {
                // Clean up after the test when we're finished
                await container.DeleteAsync();
            }
        }
Ejemplo n.º 16
0
        public async Task UploadAsync()
        {
            // Create a temporary Lorem Ipsum file on disk that we can upload
            string path = _mockupService.CreateTempFile();

            // Get a reference to a container named "sample-container" and then create it
            BlobContainerClient container = new BlobContainerClient(connectionString, _mockupService.Randomize(AppConstant.SAMPLE_CONTAINER_NAME));
            await container.CreateAsync();

            try
            {
                // Get a reference to a blob
                BlobClient blob = container.GetBlobClient(_mockupService.Randomize(AppConstant.SAMPLE_FILE_NAME));

                // Open the file and upload its data
                using (FileStream file = File.OpenRead(path))
                {
                    await blob.UploadAsync(file);
                }

                // Verify we uploaded some content
                BlobProperties properties = await blob.GetPropertiesAsync();
            }
            finally
            {
                // delete file and container after compleating operation
                await container.DeleteAsync();
            }
        }
        public async Task BatchDeleteAsync()
        {
            // Get a connection string to our Azure Storage account.
            string connectionString = ConnectionString;

            // Get a reference to a container named "sample-container" and then create it
            BlobServiceClient   service   = new BlobServiceClient(connectionString);
            BlobContainerClient container = service.GetBlobContainerClient(Randomize("sample-container"));
            await container.CreateAsync();

            try
            {
                // Create three blobs named "foo", "bar", and "baz"
                BlobClient foo = container.GetBlobClient("foo");
                BlobClient bar = container.GetBlobClient("bar");
                BlobClient baz = container.GetBlobClient("baz");
                await foo.UploadAsync(new MemoryStream(Encoding.UTF8.GetBytes("Foo!")));

                await bar.UploadAsync(new MemoryStream(Encoding.UTF8.GetBytes("Bar!")));

                await baz.UploadAsync(new MemoryStream(Encoding.UTF8.GetBytes("Baz!")));

                // Delete all three blobs at once
                BlobBatchClient batch = service.GetBlobBatchClient();
                await batch.DeleteBlobsAsync(new Uri[] { foo.Uri, bar.Uri, baz.Uri });
            }
            finally
            {
                // Clean up after the test when we're finished
                await container.DeleteAsync();
            }
        }
        public async void AcquireLease_WhenALeaseExists_ExceptionShouldBeThrown()
        {
            var uniqueContainerName = Guid.NewGuid().ToString("N");

            AzureBlobContainerClient blobProvider = GetTestBlobProvider(ConnectionString, uniqueContainerName);
            string blobName = Guid.NewGuid().ToString("N");

            var blobContainerClient = new BlobContainerClient(ConnectionString, uniqueContainerName);
            var blobClient          = blobContainerClient.GetBlobClient(blobName);

            blobClient.DeleteIfExists();
            Assert.False(blobClient.Exists());

            // create a new blob
            string blobContent = "example";
            var    blobUrl_1   = await blobProvider.CreateBlobAsync(blobName, new MemoryStream(Encoding.ASCII.GetBytes(blobContent)), CancellationToken.None);

            Assert.True(blobClient.Exists());

            var lease = await blobProvider.AcquireLeaseAsync(blobName, null, TimeSpan.FromSeconds(30), default);

            Assert.NotNull(lease);

            var lease2 = await blobProvider.AcquireLeaseAsync(blobName, null, TimeSpan.FromSeconds(30), default);

            Assert.Null(lease2);

            var lease3 = await blobProvider.AcquireLeaseAsync(blobName, lease, TimeSpan.FromSeconds(30), default);

            Assert.Equal(lease, lease3);

            await blobContainerClient.DeleteAsync();
        }
        public async Task AuthWithConnectionStringDirectToBlob()
        {
            // setup blob
            string containerName = Randomize("sample-container");
            string blobName      = Randomize("sample-file");
            var    container     = new BlobContainerClient(ConnectionString, containerName);

            try
            {
                await container.CreateAsync();

                await container.GetBlobClient(blobName).UploadAsync(new MemoryStream(Encoding.UTF8.GetBytes("hello world")));

                string connectionString = this.ConnectionString;

                #region Snippet:SampleSnippetsBlobMigration_ConnectionStringDirectBlob
                BlobClient blob = new BlobClient(connectionString, containerName, blobName);
                #endregion

                var stream = new MemoryStream();
                blob.DownloadTo(stream);
                Assert.Greater(stream.Length, 0);
            }
            finally
            {
                await container.DeleteAsync();
            }
        }
Ejemplo n.º 20
0
        public async Task DeleteContainer(BlobContainerClient containerClient)
        {
            Console.Write("Press any key to begin clean up");
            Console.ReadLine();

            Console.WriteLine("Deleting blob container...");
            await containerClient.DeleteAsync();

            Console.WriteLine("Done");
        }
Ejemplo n.º 21
0
        public async Task PageBlobSample()
        {
            // Instantiate a new BlobServiceClient using a connection string.
            BlobServiceClient blobServiceClient = new BlobServiceClient(TestConfigurations.DefaultTargetTenant.ConnectionString);

            // Instantiate a new BlobContainerClient
            BlobContainerClient blobContainerClient = blobServiceClient.GetBlobContainerClient($"mycontainer3-{Guid.NewGuid()}");

            try
            {
                // Create new Container in the Service
                await blobContainerClient.CreateAsync();

                // Instantiate a new PageBlobClient
                PageBlobClient pageBlobClient = blobContainerClient.GetPageBlobClient("pageblob");

                // Create PageBlob in the Service
                const int blobSize = 1024;
                await pageBlobClient.CreateAsync(size : blobSize);

                // Upload content to PageBlob
                using (FileStream fileStream = File.OpenRead("Samples/SampleSource.txt"))
                {
                    // Because the file size varies slightly across platforms
                    // and PageBlob pages need to be multiples of 512, we'll
                    // pad the file to our blobSize
                    using (MemoryStream pageStream = new MemoryStream(new byte[blobSize]))
                    {
                        await fileStream.CopyToAsync(pageStream);

                        pageStream.Seek(0, SeekOrigin.Begin);

                        await pageBlobClient.UploadPagesAsync(
                            content : pageStream,
                            offset : 0);
                    }
                }

                // Download PageBlob
                using (FileStream fileStream = File.Create("PageDestination.txt"))
                {
                    Response <BlobDownloadInfo> downloadResponse = await pageBlobClient.DownloadAsync();

                    await downloadResponse.Value.Content.CopyToAsync(fileStream);
                }

                // Delete PageBlob in the Service
                await pageBlobClient.DeleteAsync();
            }
            finally
            {
                // Delete Container in the Service
                await blobContainerClient.DeleteAsync();
            }
        }
Ejemplo n.º 22
0
        public static async Task CleanupAsync(string localFilePath, string downloadFilePath,
                                              BlobContainerClient containerClient)
        {
            Console.WriteLine("Deleting blob container...");
            await containerClient.DeleteAsync();

            Console.WriteLine("Deleting the local source and downloaded files...");
            File.Delete(localFilePath);
            File.Delete(downloadFilePath);

            Console.WriteLine("Done");
        }
Ejemplo n.º 23
0
        public static async Task Main(string[] args)
        {
            client.DefaultRequestHeaders.Authorization  = new AuthenticationHeaderValue("Basic", "ZXF1aXBlMDI6czdaVjlTWjNNQmRkYTZ4SA==");
            client2.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", "ZXF1aXBlMDI6czdaVjlTWjNNQmRkYTZ4SA==");
            client3.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", "c2caa137d6c549b4b29b0214528105ed");
            client4.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", "c2caa137d6c549b4b29b0214528105ed");

            if (File.Exists(WantedFile))
            {
                wantedList = File.ReadAllLines(WantedFile);
            }
            else
            {
                await UpdateWantedList();
            }

            Directory.CreateDirectory("./data");
            var blobServiceClient = new BlobServiceClient("DefaultEndpointsProtocol=https;AccountName=hackatown;AccountKey=AAZhM3cXeM9kxVa1oaCvJEFyc7WRhUC3f7vSVlJNf2oivUFI8n/Uiv3n6V7/HWDeCf22N6PEwSlZg1XHAjjQ9w==;EndpointSuffix=core.windows.net");
            var containerName     = "container" + Guid.NewGuid().ToString();

            containerClient = await blobServiceClient.CreateBlobContainerAsync(containerName);

            await containerClient.SetAccessPolicyAsync(PublicAccessType.Blob);

            subscriptionClient = new SubscriptionClient(ServiceBusConnectionString, TopicName, SubscriptionName);
            var messageHandlerOptions = new MessageHandlerOptions(ExceptionReceivedHandler)
            {
                MaxConcurrentCalls = 1,
                AutoComplete       = false
            };

            subscriptionClient.RegisterMessageHandler(ProcessMessagesAsync, messageHandlerOptions);

            subscriptionClient2 = new SubscriptionClient(ServiceBusConnectionString2, TopicName2, SubscriptionName2);
            var messageHandlerOptions2 = new MessageHandlerOptions(ExceptionReceivedHandler)
            {
                MaxConcurrentCalls = 1,
                AutoComplete       = false
            };

            subscriptionClient2.RegisterMessageHandler(ProcessMessagesAsync2, messageHandlerOptions2);

            Console.ReadKey();

            await subscriptionClient.CloseAsync();

            await subscriptionClient2.CloseAsync();

            await containerClient.DeleteAsync();

            File.WriteAllLines(WantedFile, wantedList);
        }
Ejemplo n.º 24
0
        static async Task Main()
        {
            // Step 1. Connecting and building container
            Console.WriteLine("Azure Blob Storage v12 - .NET quickstart sample\n");

            string connectionString = Environment.GetEnvironmentVariable("AZURE_STORAGE_CONNECTION_STRING");

            BlobServiceClient blobServiceClient = new BlobServiceClient(connectionString);
            string            containerName     = "quickstartblobs" + Guid.NewGuid().ToString();

            BlobContainerClient containerClient = await blobServiceClient.CreateBlobContainerAsync(containerName);

            // Step 2. Uploading and listing file
            string localPath     = "./data/";
            string fileName      = "quickstart" + Guid.NewGuid().ToString() + ".txt";
            string localFilePath = Path.Combine(localPath, fileName);

            await File.WriteAllTextAsync(localFilePath, "Hello, World!");

            BlobClient blobClient = containerClient.GetBlobClient(fileName);

            Console.WriteLine("Uploading to Blob storage as blob:\n\t {0}\n", blobClient.Uri);

            await blobClient.UploadAsync(localFilePath, true);

            Console.WriteLine("Listing blobs...");

            await foreach (BlobItem blobItem in containerClient.GetBlobsAsync())
            {
                Console.WriteLine("\t" + blobItem.Name);
            }

            // Step 3. Downloading file
            string downloadFilePath = localFilePath.Replace(".txt", "DOWNLOADED.txt");

            Console.WriteLine("\nDownloading blog to\n\t{0}\n", downloadFilePath);

            await blobClient.DownloadToAsync(downloadFilePath);

            // Step 4. Cleaning
            Console.Write("Press any key to begin clean up");
            Console.ReadLine();

            Console.WriteLine("Deleting blob container...");
            await containerClient.DeleteAsync();

            Console.WriteLine("Deleting the local source and downloaded files...");
            File.Delete(localFilePath);
            File.Delete(downloadFilePath);

            Console.WriteLine("Done!");
        }
Ejemplo n.º 25
0
        /// <summary>
        /// Delete Blob document
        /// </summary>
        /// <param name="localFilePath"></param>
        /// <param name="downloadFilePath"></param>
        /// <returns></returns>
        private async Task DeleteBlobAsync(string localFilePath, string downloadFilePath)
        {
            // Clean up
            Console.Write("Press any key to begin clean up");
            Console.ReadLine();

            Console.WriteLine("Deleting blob container...");
            await containerClient.DeleteAsync();

            Console.WriteLine("Deleting the local source and downloaded files...");
            File.Delete(localFilePath);
            File.Delete(downloadFilePath);

            Console.WriteLine("Done");
        }
            public async ValueTask DisposeAsync()
            {
                if (Container != null)
                {
                    try
                    {
                        await Container.DeleteAsync();

                        Container = null;
                    }
                    catch
                    {
                        // swallow the exception to avoid hiding another test failure
                    }
                }
            }
        async void Delete_Clicked(object sender, EventArgs e)
        {
            var deleteContainer = await Application.Current.MainPage.DisplayAlert("Delete Container",
                                                                                  "You are about to delete the container proceeed?", "OK", "Cancel");

            if (deleteContainer == false)
            {
                return;
            }

            await containerClient.DeleteAsync();

            resultsLabel.Text += "Container deleted";

            deleteButton.IsEnabled = false;
        }
        public async void UpdateStreamToBlob_TheBlobShouldBeOverwriten()
        {
            var uniqueContainerName = Guid.NewGuid().ToString("N");

            AzureBlobContainerClient blobProvider = GetTestBlobProvider(ConnectionString, uniqueContainerName);
            string blobName = Guid.NewGuid().ToString("N");

            var blobContainerClient = new BlobContainerClient(ConnectionString, uniqueContainerName);
            var blobClient          = blobContainerClient.GetBlobClient(blobName);

            blobClient.DeleteIfExists();
            Assert.False(blobClient.Exists());

            // create a new blob
            string blobContent = "example";
            var    blobUrl_1   = await blobProvider.UpdateBlobAsync(blobName, new MemoryStream(Encoding.ASCII.GetBytes(blobContent)), CancellationToken.None);

            Assert.True(blobClient.Exists());

            using (var stream = new MemoryStream())
            {
                var res = await blobClient.DownloadToAsync(stream);

                stream.Position  = 0;
                using var reader = new StreamReader(stream);
                Assert.Equal(blobContent, reader.ReadToEnd());
            }

            // upload to a existing blob
            string newBlobContent = "new example";
            var    blobUrl_2      = await blobProvider.UpdateBlobAsync(blobName, new MemoryStream(Encoding.ASCII.GetBytes(newBlobContent)), CancellationToken.None);

            Assert.Equal(blobUrl_1, blobUrl_2);
            Assert.True(blobClient.Exists());

            using (var stream = new MemoryStream())
            {
                var res = await blobClient.DownloadToAsync(stream);

                stream.Position  = 0;
                using var reader = new StreamReader(stream);
                Assert.Equal(newBlobContent, reader.ReadToEnd());
            }

            await blobContainerClient.DeleteAsync();
        }
        public async void DownloadNoExistingBlob_StreamShouldReturn()
        {
            var uniqueContainerName = Guid.NewGuid().ToString("N");

            AzureBlobContainerClient blobProvider = GetTestBlobProvider(ConnectionString, uniqueContainerName);
            string blobName = Guid.NewGuid().ToString("N");

            var blobContainerClient = new BlobContainerClient(ConnectionString, uniqueContainerName);
            var blobClient          = blobContainerClient.GetBlobClient(blobName);

            Assert.False(blobClient.Exists());

            using Stream downloadStream = await blobProvider.GetBlobAsync(blobName, CancellationToken.None);

            Assert.Null(downloadStream);

            await blobContainerClient.DeleteAsync();
        }
Ejemplo n.º 30
0
        public static async Task Main()
        {
            BlobClientOptions options = new BlobClientOptions();

            options.Retry.MaxRetries             = 10;
            options.Retry.Delay                  = TimeSpan.FromSeconds(3);
            options.Diagnostics.IsLoggingEnabled = true;

            options.AddPolicy(new SimpleTracingPolicy(), HttpPipelinePosition.PerCall);

            BlobServiceClient serviceClient = new BlobServiceClient(BlobServiceUri, new DefaultAzureCredential(), options);

            await foreach (BlobContainerItem container in serviceClient.GetBlobContainersAsync())
            {
                BlobContainerClient containerClient = serviceClient.GetBlobContainerClient(container.Name);
                await containerClient.DeleteAsync();
            }
        }