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 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();
            }
        }
        private async Task UploadBlobAsync(string containerName, string blobName, string blobContent, bool isRetry = false)
        {
            BlobContainerClient containerClient = _blobServiceClient.GetBlobContainerClient(containerName);
            BlobClient          blobClient      = containerClient.GetBlobClient(blobName);

            try
            {
                await blobClient.UploadAsync(
                    BinaryData.FromString(blobContent),
                    new BlobUploadOptions
                {
                    HttpHeaders = new BlobHttpHeaders
                    {
                        ContentType = MediaTypeNames.Application.Json
                    }
                });
            }
            catch (RequestFailedException ex) when(ex.ErrorCode == BlobErrorCode.ContainerNotFound)
            {
                if (!isRetry)
                {
                    await containerClient.CreateAsync();
                    await UploadBlobAsync(containerName, blobName, blobContent, isRetry : true);
                }
            }
        }
Ejemplo n.º 4
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();
            }
        }
        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();
            }
        }
        public async Task CreateContainer()
        {
            string connectionString = this.ConnectionString;
            string containerName    = Randomize("sample-container");

            // use extra variable so the snippet gets variable declarations but we still get the try/finally
            var containerClientTracker = new BlobServiceClient(connectionString).GetBlobContainerClient(containerName);

            try
            {
                #region Snippet:SampleSnippetsBlobMigration_CreateContainer
                BlobServiceClient   blobServiceClient = new BlobServiceClient(connectionString);
                BlobContainerClient containerClient   = blobServiceClient.GetBlobContainerClient(containerName);
                await containerClient.CreateAsync();

                #endregion

                // pass if success
                containerClient.GetProperties();
            }
            finally
            {
                await containerClientTracker.DeleteIfExistsAsync();
            }
        }
Ejemplo n.º 7
0
        public async Task <string> UploadBlob(IFormFile Pixel)
        {
            string con = _config.GetSection("BlobStorageString").Value;

            BlobServiceClient blobService = new BlobServiceClient(con);

            //creates container to hold BLOBs.
            //container name should NOT have any special characters or capitals!
            BlobContainerClient containerClient = new BlobContainerClient("UseDevelopmentStorage=true", "pixel-arts");

            //makes sure container exists
            if (!containerClient.Exists())
            {
                await containerClient.CreateAsync();

                await containerClient.SetAccessPolicyAsync(PublicAccessType.Blob);
            }

            //Add BLOB to container.
            string     newfileName = Guid.NewGuid().ToString() + Path.GetExtension(Pixel.FileName);
            BlobClient blobClient  = containerClient.GetBlobClient(newfileName);
            await blobClient.UploadAsync(Pixel.OpenReadStream());

            return(newfileName);
        }
        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();
        }
Ejemplo n.º 9
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 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.º 11
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 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 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();
            }
        }
Ejemplo n.º 14
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 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();
        }
        public async Task SasBuilderIdentifier()
        {
            string accountName   = StorageAccountName;
            string accountKey    = StorageAccountKey;
            string containerName = Randomize("sample-container");
            string blobName      = Randomize("sample-blob");
            StorageSharedKeyCredential sharedKeyCredential = new StorageSharedKeyCredential(StorageAccountName, StorageAccountKey);

            // setup blob
            var container = new BlobContainerClient(ConnectionString, containerName);

            try
            {
                await container.CreateAsync();

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

                // Create one or more stored access policies.
                List <BlobSignedIdentifier> signedIdentifiers = new List <BlobSignedIdentifier>
                {
                    new BlobSignedIdentifier
                    {
                        Id           = "mysignedidentifier",
                        AccessPolicy = new BlobAccessPolicy
                        {
                            StartsOn    = DateTimeOffset.UtcNow.AddHours(-1),
                            ExpiresOn   = DateTimeOffset.UtcNow.AddDays(1),
                            Permissions = "rw"
                        }
                    }
                };
                // Set the container's access policy.
                await container.SetAccessPolicyAsync(permissions : signedIdentifiers);

                #region Snippet:SampleSnippetsBlobMigration_SasBuilderIdentifier
                // Create BlobSasBuilder and specify parameters
                BlobSasBuilder sasBuilder = new BlobSasBuilder()
                {
                    Identifier = "mysignedidentifier"
                };
                #endregion

                // Create full, self-authenticating URI to the resource
                BlobUriBuilder uriBuilder = new BlobUriBuilder(StorageAccountBlobUri)
                {
                    BlobContainerName = containerName,
                    BlobName          = blobName,
                    Sas = sasBuilder.ToSasQueryParameters(sharedKeyCredential)
                };
                Uri sasUri = uriBuilder.ToUri();

                // successful download indicates pass
                await new BlobClient(sasUri).DownloadToAsync(new MemoryStream());
            }
            finally
            {
                await container.DeleteIfExistsAsync();
            }
        }
Ejemplo n.º 17
0
        public static async Task CreateAsync(string account, string key, string containerName, bool publicAccess)
        {
            BlobServiceClient   blobServiceClient = new BlobServiceClient(Client.GetConnectionString(account, key));
            BlobContainerClient container         = blobServiceClient.GetBlobContainerClient(containerName);

            PublicAccessType accessType = publicAccess ? PublicAccessType.BlobContainer : PublicAccessType.None;
            await container.CreateAsync(accessType);
        }
Ejemplo n.º 18
0
        public static async Task <BlobContainerScope> CreateContainer(string connectionString)
        {
            var containerName   = Guid.NewGuid().ToString("D");
            var containerClient = new BlobContainerClient(connectionString, containerName);
            await containerClient.CreateAsync().ConfigureAwait(false);

            return(new BlobContainerScope(containerClient, containerName));
        }
Ejemplo n.º 19
0
        public async Task <BlobContainerInfo> CloneContainer(string sourceContainerName, string targetContainerName)
        {
            try
            {
                // create target container
                BlobContainerClient targetContainerClient = new BlobContainerClient(connectionString, targetContainerName);
                BlobContainerInfo   targetContainer       = await targetContainerClient.CreateAsync();

                // get source container
                BlobContainerClient sourceContainerClient = blobServiceClient.GetBlobContainerClient(sourceContainerName);
                // blobs from source container
                await foreach (BlobItem blob in sourceContainerClient.GetBlobsAsync())
                {
                    // create a blob client for the source blob
                    BlobClient sourceBlob = sourceContainerClient.GetBlobClient(blob.Name);
                    // Ensure that the source blob exists.
                    if (await sourceBlob.ExistsAsync())
                    {
                        // Lease the source blob for the copy operation
                        // to prevent another client from modifying it.
                        BlobLeaseClient lease = sourceBlob.GetBlobLeaseClient();

                        // Specifying -1 for the lease interval creates an infinite lease.
                        await lease.AcquireAsync(TimeSpan.FromSeconds(60));

                        // Get a BlobClient representing the destination blob with a unique name.
                        BlobClient destBlob = targetContainerClient.GetBlobClient(sourceBlob.Name);

                        // Start the copy operation.
                        await destBlob.StartCopyFromUriAsync(sourceBlob.Uri);

                        // Update the source blob's properties.
                        BlobProperties sourceProperties = await sourceBlob.GetPropertiesAsync();

                        if (sourceProperties.LeaseState == LeaseState.Leased)
                        {
                            // Break the lease on the source blob.
                            await lease.BreakAsync();
                        }
                    }
                }


                return(targetContainer);
            }
            catch (RequestFailedException e)
            {
                Console.WriteLine("HTTP error code {0}: {1}",
                                  e.Status, e.ErrorCode);
                Console.WriteLine(e.Message);
                throw;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                throw;
            }
        }
Ejemplo n.º 20
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();
            }
        }
        public virtual async Task <Response <BlobContainerClient> > CreateBlobContainerAsync(
            string containerName,
            PublicAccessType publicAccessType = PublicAccessType.None,
            Metadata metadata = default,
            CancellationToken cancellationToken = default)
        {
            BlobContainerClient      container = GetBlobContainerClient(containerName);
            Response <ContainerInfo> response  = await container.CreateAsync(publicAccessType, metadata, cancellationToken).ConfigureAwait(false);

            return(new Response <BlobContainerClient>(response.GetRawResponse(), container));
        }
        //Method to list all Blob Objects in the container using Connection string.
        private static void SalesList(string ConnectionString, string Container)
        {
            string connectionString       = ConnectionString;
            BlobContainerClient container = new BlobContainerClient(connectionString, Container);

            container.CreateAsync();
            foreach (BlobItem blob in container.GetBlobs())
            {
                Console.WriteLine(blob.Name);
            }
        }
Ejemplo n.º 23
0
        private async Task <BlobContainerClient> CreateContainer()
        {
            var blobServiceClient = new BlobServiceClient(_config.AzureStorageConnectionString);
            BlobContainerClient containerClient = blobServiceClient.GetBlobContainerClient(_config.ContainerName);

            if (!containerClient.Exists())
            {
                await containerClient.CreateAsync();
            }
            return(containerClient);
        }
Ejemplo n.º 24
0
        public async Task Capture_Span_When_Create_Container()
        {
            var containerName = Guid.NewGuid().ToString();
            var client        = new BlobContainerClient(Environment.StorageAccountConnectionString, containerName);

            await Agent.Tracer.CaptureTransaction("Create Azure Container", ApiConstants.TypeStorage, async() =>
            {
                var containerCreateResponse = await client.CreateAsync();
            });

            AssertSpan("Create", containerName);
        }
Ejemplo n.º 25
0
        internal static async Task <Uri> GetOrCreateBlobContainerSasUriForLogAsync(string storageAccountConnectionString)
        {
            string containerName   = GetAzureBlobContainerNameForLog();
            var    containerClient = new BlobContainerClient(storageAccountConnectionString, containerName);

            if (!await containerClient.ExistsAsync())
            {
                await containerClient.CreateAsync();
            }

            CloudStorageAccount storageAccount = CloudStorageAccount.Parse(storageAccountConnectionString);
            var container = new CloudBlobContainer(containerClient.Uri, storageAccount.Credentials);

            return(GetContainerSasUri(container));
        }
        public async Task SasBuilder()
        {
            string accountName   = StorageAccountName;
            string accountKey    = StorageAccountKey;
            string containerName = Randomize("sample-container");
            string blobName      = Randomize("sample-blob");
            StorageSharedKeyCredential sharedKeyCredential = new StorageSharedKeyCredential(StorageAccountName, StorageAccountKey);

            // setup blob
            var container = new BlobContainerClient(ConnectionString, containerName);

            try
            {
                await container.CreateAsync();

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

                #region Snippet:SampleSnippetsBlobMigration_SasBuilder
                // Create BlobSasBuilder and specify parameters
                BlobSasBuilder sasBuilder = new BlobSasBuilder()
                {
                    // with no url in a client to read from, container and blob name must be provided if applicable
                    BlobContainerName = containerName,
                    BlobName          = blobName,
                    ExpiresOn         = DateTimeOffset.Now.AddHours(1)
                };
                // permissions applied separately, using the appropriate enum to the scope of your SAS
                sasBuilder.SetPermissions(BlobSasPermissions.Read);

                // Create full, self-authenticating URI to the resource
                BlobUriBuilder uriBuilder = new BlobUriBuilder(StorageAccountBlobUri)
                {
                    BlobContainerName = containerName,
                    BlobName          = blobName,
                    Sas = sasBuilder.ToSasQueryParameters(sharedKeyCredential)
                };
                Uri sasUri = uriBuilder.ToUri();
                #endregion

                // successful download indicates pass
                await new BlobClient(sasUri).DownloadToAsync(new MemoryStream());
            }
            finally
            {
                await container.DeleteIfExistsAsync();
            }
        }
Ejemplo n.º 27
0
        public async Task GenerateSas()
        {
            string accountName   = StorageAccountName;
            string accountKey    = StorageAccountKey;
            string containerName = Randomize("sample-container");
            string blobName      = Randomize("sample-blob");
            StorageSharedKeyCredential sharedKeyCredential = new StorageSharedKeyCredential(StorageAccountName, StorageAccountKey);

            // setup blob
            var            container  = new BlobContainerClient(ConnectionString, containerName);
            BlobUriBuilder uriBuilder = new BlobUriBuilder(container.Uri)
            {
                BlobName = blobName
            };
            Uri blobUri = uriBuilder.ToUri();

            try
            {
                await container.CreateAsync();

                await container.GetBlobClient(blobName).UploadAsync(BinaryData.FromString("hello world"));

                #region Snippet:SampleSnippetsBlobMigration_GenerateSas
                // Create a BlobClient with a shared key credential
                BlobClient blobClient = new BlobClient(blobUri, sharedKeyCredential);

                Uri sasUri;
                // Ensure our client has the credentials required to generate a SAS
                if (blobClient.CanGenerateSasUri)
                {
                    // Create full, self-authenticating URI to the resource from the BlobClient
                    sasUri = blobClient.GenerateSasUri(BlobSasPermissions.Read, DateTimeOffset.UtcNow.AddHours(1));

                    // Use newly made as SAS URI to download the blob
                    await new BlobClient(sasUri).DownloadToAsync(new MemoryStream());
                }
                #endregion
                else
                {
                    Assert.Fail("Unable to create SAS URI");
                }
            }
            finally
            {
                await container.DeleteIfExistsAsync();
            }
        }
        public BlobTriggerEndToEndTests()
        {
            _nameResolver = new RandomNameResolver();

            // pull from a default host
            var host = new HostBuilder()
                       .ConfigureDefaultTestHost(b =>
            {
                b.AddAzureStorageBlobs().AddAzureStorageQueues();
            })
                       .Build();

            _blobServiceClient = new BlobServiceClient(TestEnvironment.PrimaryStorageAccountConnectionString);
            _testContainer     = _blobServiceClient.GetBlobContainerClient(_nameResolver.ResolveInString(SingleTriggerContainerName));
            Assert.False(_testContainer.ExistsAsync().Result);
            _testContainer.CreateAsync().Wait();
        }
Ejemplo n.º 29
0
        public async Task GenerateSas_Builder()
        {
            string accountName   = StorageAccountName;
            string accountKey    = StorageAccountKey;
            string containerName = Randomize("sample-container");
            string blobName      = Randomize("sample-blob");
            StorageSharedKeyCredential sharedKeyCredential = new StorageSharedKeyCredential(StorageAccountName, StorageAccountKey);

            // setup blob
            var            container  = new BlobContainerClient(ConnectionString, containerName);
            BlobUriBuilder uriBuilder = new BlobUriBuilder(container.Uri)
            {
                BlobName = blobName
            };
            Uri blobUri = uriBuilder.ToUri();

            try
            {
                await container.CreateAsync();

                await container.GetBlobClient(blobName).UploadAsync(BinaryData.FromString("hello world"));

                // Create a BlobClient with a shared key credential
                BlobClient blobClient = new BlobClient(blobUri, sharedKeyCredential);
                // Create BlobSasBuilder and specify parameters
                #region Snippet:SampleSnippetsBlobMigration_GenerateSas_Builder
                BlobSasBuilder sasBuilder = new BlobSasBuilder(BlobSasPermissions.Read, DateTimeOffset.UtcNow.AddHours(1))
                {
                    // Since we are generating from the client, the client will have the container and blob name
                    // Specify any optional paremeters here
                    StartsOn = DateTimeOffset.UtcNow.AddHours(-1)
                };

                // Create full, self-authenticating URI to the resource from the BlobClient
                Uri sasUri = blobClient.GenerateSasUri(sasBuilder);
                #endregion

                // Use newly made as SAS URI to download the blob
                await new BlobClient(sasUri).DownloadToAsync(new MemoryStream());
            }
            finally
            {
                await container.DeleteIfExistsAsync();
            }
        }
        private async Task <DisposingContainer> GetTestContainerEncryptionAsync(
            ClientSideEncryptionOptions encryptionOptions,
            string containerName = default,
            IDictionary <string, string> metadata = default)
        {
            // normally set through property on subclass; this is easier to hook up in current test infra with internals access
            var options = GetOptions();

            options._clientSideEncryptionOptions = encryptionOptions;

            containerName ??= GetNewContainerName();
            var service = GetServiceClient_SharedKey(options);

            BlobContainerClient container = InstrumentClient(service.GetBlobContainerClient(containerName));
            await container.CreateAsync(metadata : metadata);

            return(new DisposingContainer(container));
        }