public void AuthWithSasCredential() { //setup blob string containerName = Randomize("sample-container"); string blobName = Randomize("sample-file"); var container = new BlobContainerClient(ConnectionString, containerName); try { container.Create(); BlobClient blobClient = container.GetBlobClient(blobName); blobClient.Upload(BinaryData.FromString("hello world")); // build SAS URI for sample Uri sasUri = blobClient.GenerateSasUri(BlobSasPermissions.All, DateTimeOffset.UtcNow.AddHours(1)); #region Snippet:SampleSnippetsBlobMigration_SasUri BlobClient blob = new BlobClient(sasUri); #endregion var stream = new MemoryStream(); blob.DownloadTo(stream); Assert.Greater(stream.Length, 0); } finally { container.Delete(); } }
public void Errors() { string connectionString = ConnectionString; string containerName = Randomize("sample-container"); #region Snippet:SampleSnippetsBlob_Troubleshooting // Get a connection string to our Azure Storage account. //@@ string connectionString = "<connection_string>"; //@@ string containerName = "sample-container"; // Try to delete a container named "sample-container" and avoid any potential race conditions // that might arise by checking if the container is already deleted or is in the process // of being deleted. BlobContainerClient container = new BlobContainerClient(connectionString, containerName); try { container.Delete(); } catch (RequestFailedException ex) when(ex.ErrorCode == BlobErrorCode.ContainerBeingDeleted || ex.ErrorCode == BlobErrorCode.ContainerNotFound) { // Ignore any errors if the container being deleted or if it has already been deleted } #endregion catch (RequestFailedException ex) { Assert.Fail($"Unexpected error: {ex}"); } }
public void List() { // 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")); container.Create(); try { // Upload a couple of blobs so we have something to list container.UploadBlob("first", File.OpenRead(CreateTempFile())); container.UploadBlob("second", File.OpenRead(CreateTempFile())); container.UploadBlob("third", File.OpenRead(CreateTempFile())); // List all the blobs List <string> names = new List <string>(); foreach (BlobItem blob in container.GetBlobs()) { names.Add(blob.Name); } Assert.AreEqual(3, names.Count); Assert.Contains("first", names); Assert.Contains("second", names); Assert.Contains("third", names); } finally { // Clean up after the test when we're finished container.Delete(); } }
public void BatchDelete() { string connectionString = ConnectionString; string containerName = Randomize("sample-container"); #region Snippet:SampleSnippetsBatch_DeleteBatch // Get a connection string to our Azure Storage account. //@@ string connectionString = "<connection_string>"; //@@ string containerName = "sample-container"; // Get a reference to a container named "sample-container" and then create it BlobServiceClient service = new BlobServiceClient(connectionString); BlobContainerClient container = service.GetBlobContainerClient(containerName); container.Create(); // Create three blobs named "foo", "bar", and "baz" BlobClient foo = container.GetBlobClient("foo"); BlobClient bar = container.GetBlobClient("bar"); BlobClient baz = container.GetBlobClient("baz"); foo.Upload(new MemoryStream(Encoding.UTF8.GetBytes("Foo!"))); bar.Upload(new MemoryStream(Encoding.UTF8.GetBytes("Bar!"))); baz.Upload(new MemoryStream(Encoding.UTF8.GetBytes("Baz!"))); // Delete all three blobs at once BlobBatchClient batch = service.GetBlobBatchClient(); batch.DeleteBlobs(new Uri[] { foo.Uri, bar.Uri, baz.Uri }); #endregion Assert.AreEqual(0, container.GetBlobs().ToList().Count); // Clean up after we're finished container.Delete(); }
public void Errors() { // 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")); container.Create(); try { // Try to create the container again container.Create(); } catch (RequestFailedException ex) when(ex.ErrorCode == BlobErrorCode.ContainerAlreadyExists) { // Ignore any errors if the container already exists } catch (RequestFailedException ex) { Assert.Fail($"Unexpected error: {ex}"); } // Clean up after the test when we're finished container.Delete(); }
public void BatchSetAccessTier() { // 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")); container.Create(); try { // Create three blobs named "foo", "bar", and "baz" BlobClient foo = container.GetBlobClient("foo"); BlobClient bar = container.GetBlobClient("bar"); BlobClient baz = container.GetBlobClient("baz"); foo.Upload(new MemoryStream(Encoding.UTF8.GetBytes("Foo!"))); bar.Upload(new MemoryStream(Encoding.UTF8.GetBytes("Bar!"))); baz.Upload(new MemoryStream(Encoding.UTF8.GetBytes("Baz!"))); // Set the access tier for all three blobs at once BlobBatchClient batch = service.GetBlobBatchClient(); batch.SetBlobsAccessTier(new Uri[] { foo.Uri, bar.Uri, baz.Uri }, AccessTier.Cool); } finally { // Clean up after the test when we're finished container.Delete(); } }
public void Download() { // 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")); container.Create(); 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 blob.Upload(originalPath); // Download the blob's contents and save it to a file blob.DownloadTo(downloadPath); // Verify the contents Assert.AreEqual(SampleFileContent, File.ReadAllText(downloadPath)); } finally { // Clean up after the test when we're finished container.Delete(); } }
static void Main(string[] args) { try { string connectionString = Environment.GetEnvironmentVariable("AZURE_STORAGE_CONNECTION_STRING"); BlobServiceClient blobServiceClient = new BlobServiceClient(connectionString); BlobContainerClient containerClient = blobServiceClient.CreateBlobContainer("carddeck"); containerClient.SetAccessPolicy(PublicAccessType.Blob); int numberOfCards = 0; DirectoryInfo dir = new DirectoryInfo(@"Cards"); foreach (FileInfo f in dir.GetFiles("*.*")) { BlobClient blob = containerClient.GetBlobClient(f.Name); using (var fileStream = System.IO.File.OpenRead(@"Cards\" + f.Name)) { blob.Upload(fileStream); Console.WriteLine($"Uploading: '{f.Name}' which " + $"is {fileStream.Length} bytes."); } numberOfCards++; } Console.WriteLine($"Uploaded {numberOfCards.ToString()} cards."); Console.WriteLine(); numberOfCards = 0; foreach (BlobItem item in containerClient.GetBlobs()) { Console.WriteLine($"Card image url '{containerClient.Uri}/{item.Name}' with length " + $"of {item.Properties.ContentLength}"); numberOfCards++; } Console.WriteLine($"Listed {numberOfCards.ToString()} cards."); Console.WriteLine("If you want to delete the container and its contents enter: " + "'Yes' and the Enter key"); var delete = Console.ReadLine(); if (delete == "Yes") { containerClient.Delete(); Console.WriteLine("Container deleted."); } Console.WriteLine("All done, press the Enter key to exit."); Console.ReadLine(); } catch (RequestFailedException rfe) { Console.WriteLine($"RequestFailedException: {rfe.Message}"); } catch (Exception ex) { Console.WriteLine($"Exception: {ex.Message}"); } }
public void DeleteContainer(string containerName) { BlobContainerClient containerClient = _blobServiceClient.GetBlobContainerClient(containerName); if (!containerClient.Exists()) { throw new ApplicationException($"Unable to delete container '{containerName}' as it does not exists"); } containerClient.Delete(); }
public void DeleteContainer(string containerName) { // Try to delete a container and avoid any potential race conditions that might arise by checking if the container is already deleted or is in the process of being deleted. BlobContainerClient container = AzureBlobManager.GetBlobContainerClient(containerName); try { container.Delete(); } catch (RequestFailedException ex) when(ex.ErrorCode == BlobErrorCode.ContainerBeingDeleted || ex.ErrorCode == BlobErrorCode.ContainerNotFound) { // Ignore any errors if the container being deleted or if it has already been deleted } }
public void AuthWithSasCredential() { //setup blob string containerName = Randomize("sample-container"); string blobName = Randomize("sample-file"); var container = new BlobContainerClient(ConnectionString, containerName); try { container.Create(); container.GetBlobClient(blobName).Upload(new MemoryStream(Encoding.UTF8.GetBytes("hello world"))); // build SAS URI for sample BlobSasBuilder sas = new BlobSasBuilder { BlobContainerName = containerName, BlobName = blobName, ExpiresOn = DateTimeOffset.UtcNow.AddHours(1) }; sas.SetPermissions(BlobSasPermissions.All); StorageSharedKeyCredential credential = new StorageSharedKeyCredential(StorageAccountName, StorageAccountKey); UriBuilder sasUri = new UriBuilder(this.StorageAccountBlobUri); sasUri.Path = $"{containerName}/{blobName}"; sasUri.Query = sas.ToSasQueryParameters(credential).ToString(); string blobLocationWithSas = sasUri.Uri.ToString(); #region Snippet:SampleSnippetsBlobMigration_SasUri BlobClient blob = new BlobClient(new Uri(blobLocationWithSas)); #endregion var stream = new MemoryStream(); blob.DownloadTo(stream); Assert.Greater(stream.Length, 0); } finally { container.Delete(); } }
public void Upload() { // Create a temporary Lorem Ipsum file on disk that we can upload string path = CreateTempFile(SampleFileContent); // Get a connection string to our Azure Storage account. You can // obtain your connection string from the Azure Portal (click // Access Keys under Settings in the Portal Storage account blade) // or using the Azure CLI with: // // az storage account show-connection-string --name <account_name> --resource-group <resource_group> // // And you can provide the connection string to your application // using an environment variable. string connectionString = ConnectionString; // Get a reference to a container named "sample-container" and then create it BlobContainerClient container = new BlobContainerClient(connectionString, Randomize("sample-container")); container.Create(); try { // Get a reference to a blob named "sample-file" in a container named "sample-container" BlobClient blob = container.GetBlobClient(Randomize("sample-file")); // Open the file and upload its data using (FileStream file = File.OpenRead(path)) { blob.Upload(file); } // Verify we uploaded one blob with some content Assert.AreEqual(1, container.GetBlobs().Count()); BlobProperties properties = blob.GetProperties(); Assert.AreEqual(SampleFileContent.Length, properties.ContentLength); } finally { // Clean up after the test when we're finished container.Delete(); } }
public void FineGrainedBatching() { string connectionString = ConnectionString; string containerName = Randomize("sample-container"); #region Snippet:SampleSnippetsBatch_FineGrainedBatching // Get a connection string to our Azure Storage account. //@@ string connectionString = "<connection_string>"; //@@ string containerName = "sample-container"; // Get a reference to a container named "sample-container" and then create it BlobServiceClient service = new BlobServiceClient(connectionString); BlobContainerClient container = service.GetBlobContainerClient(containerName); container.Create(); // Create three blobs named "foo", "bar", and "baz" BlobClient foo = container.GetBlobClient("foo"); BlobClient bar = container.GetBlobClient("bar"); BlobClient baz = container.GetBlobClient("baz"); foo.Upload(new MemoryStream(Encoding.UTF8.GetBytes("Foo!"))); foo.CreateSnapshot(); bar.Upload(new MemoryStream(Encoding.UTF8.GetBytes("Bar!"))); bar.CreateSnapshot(); baz.Upload(new MemoryStream(Encoding.UTF8.GetBytes("Baz!"))); // Create a batch with three deletes BlobBatchClient batchClient = service.GetBlobBatchClient(); BlobBatch batch = batchClient.CreateBatch(); batch.DeleteBlob(foo.Uri, DeleteSnapshotsOption.IncludeSnapshots); batch.DeleteBlob(bar.Uri, DeleteSnapshotsOption.OnlySnapshots); batch.DeleteBlob(baz.Uri); // Submit the batch batchClient.SubmitBatch(batch); #endregion Pageable <BlobItem> blobs = container.GetBlobs(states: BlobStates.Snapshots); Assert.AreEqual(1, blobs.Count()); Assert.AreEqual("bar", blobs.FirstOrDefault().Name); // Clean up after the test when we're finished container.Delete(); }
public void FineGrainedBatching() { // 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")); container.Create(); try { // Create three blobs named "foo", "bar", and "baz" BlobClient foo = container.GetBlobClient("foo"); BlobClient bar = container.GetBlobClient("bar"); BlobClient baz = container.GetBlobClient("baz"); foo.Upload(new MemoryStream(Encoding.UTF8.GetBytes("Foo!"))); bar.Upload(new MemoryStream(Encoding.UTF8.GetBytes("Bar!"))); baz.Upload(new MemoryStream(Encoding.UTF8.GetBytes("Baz!"))); // Create a batch with three deletes BlobBatchClient batchClient = service.GetBlobBatchClient(); BlobBatch batch = batchClient.CreateBatch(); Response fooResponse = batch.DeleteBlob(foo.Uri, DeleteSnapshotsOption.Include); Response barResponse = batch.DeleteBlob(bar.Uri); Response bazResponse = batch.DeleteBlob(baz.Uri); // Submit the batch batchClient.SubmitBatch(batch); // Verify the results Assert.AreEqual(202, fooResponse.Status); Assert.AreEqual(202, barResponse.Status); Assert.AreEqual(202, bazResponse.Status); } finally { // Clean up after the test when we're finished container.Delete(); } }
public void List() { string connectionString = ConnectionString; string containerName = Randomize("sample-container"); string filePath = CreateTempFile(); #region Snippet:SampleSnippetsBlob_List // Get a connection string to our Azure Storage account. //@@ string connectionString = "<connection_string>"; //@@ string containerName = "sample-container"; //@@ string filePath = "hello.jpg"; // Get a reference to a container named "sample-container" and then create it BlobContainerClient container = new BlobContainerClient(connectionString, containerName); container.Create(); // Upload a few blobs so we have something to list container.UploadBlob("first", File.OpenRead(filePath)); container.UploadBlob("second", File.OpenRead(filePath)); container.UploadBlob("third", File.OpenRead(filePath)); // Print out all the blob names foreach (BlobItem blob in container.GetBlobs()) { Console.WriteLine(blob.Name); } #endregion List <string> names = new List <string>(); foreach (BlobItem blob in container.GetBlobs()) { names.Add(blob.Name); } Assert.AreEqual(3, names.Count); Assert.Contains("first", names); Assert.Contains("second", names); Assert.Contains("third", names); container.Delete(); }
public void BatchErrors() { // 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")); container.Create(); try { // Create a blob named "valid" BlobClient valid = container.GetBlobClient("valid"); valid.Upload(new MemoryStream(Encoding.UTF8.GetBytes("Valid!"))); // Get a reference to a blob named "invalid", but never create it BlobClient invalid = container.GetBlobClient("invalid"); // Delete both blobs at the same time BlobBatchClient batch = service.GetBlobBatchClient(); batch.DeleteBlobs(new Uri[] { valid.Uri, invalid.Uri }); } catch (AggregateException ex) { // An aggregate exception is thrown for all the indivudal failures Assert.AreEqual(1, ex.InnerExceptions.Count); StorageRequestFailedException failure = ex.InnerException as StorageRequestFailedException; Assert.IsTrue(BlobErrorCode.BlobNotFound == failure.ErrorCode); } finally { // Clean up after the test when we're finished container.Delete(); } }
public void Dispose() { blobContainerClient.Delete(); }
static void Main(string[] args) { //Settings for protect the connection string used to manage storage account var builder = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("appsettings.json"); //Set configuration for read access to appsettings.json where ConnectionString is storaged IConfiguration config = new ConfigurationBuilder() .AddJsonFile("appsettings.json", true, true) .Build(); //Get the ConnectionString securely and prints in terminal string getConnectionString = config["ConnectionString"]; string getStudentID = config["StudentID"]; //Settings for new container creation BlobServiceClient myBlobServiceClient = new BlobServiceClient(getConnectionString); //Settings for new container name it takes StudentID from appsettings and joins with some other data string containerName = "asn-" + getStudentID + "-" + Guid.NewGuid().ToString(); //Create the container and return an container client object BlobContainerClient myContainerClient = myBlobServiceClient.CreateBlobContainer(containerName); //Minimal validation for Blob container creation //DoubleCheck for Creation myContainerClient.CreateIfNotExists(); //Set the container access Type to blobContainer myContainerClient.SetAccessPolicy(accessType: PublicAccessType.Blob); Console.WriteLine("New Blob Container Created at: " + myContainerClient.Uri + "for Account: " + myContainerClient.AccountName + "\n\n"); Console.WriteLine("Wanna check the results? Go to your azure Account Service Dashboard"); Console.WriteLine("Wannna Proced with File Upload to our Fresh New Blob Container: " + myContainerClient.Name + "? Press Y/N"); char userResponse = Char.Parse(Console.ReadLine()); //Conditional Statement for File Upload to a Blob Container if (userResponse == 'y' || userResponse == 'Y') { //Logic for Blob Upload string localFilePath = "Azure-Migrate.svg"; BlobClient myBlobClient = myContainerClient.GetBlobClient(localFilePath); Console.WriteLine("Uploading to Blob storage as blob:\n\t {0}\n", myBlobClient.Uri); // Open the file and upload its data using FileStream uploadFileStream = File.OpenRead(localFilePath); myBlobClient.Upload(uploadFileStream, true); uploadFileStream.Close(); //logic for Listing items into a container Console.WriteLine("Listing blobs container contents...\n\n"); // List all blobs in the container foreach (BlobItem blobItem in myContainerClient.GetBlobs()) { Console.WriteLine("\t" + blobItem.Name); } Console.WriteLine("Wannna Proced to Delete to our Fresh New Blob Container: " + myContainerClient.Name + "? Press Y/N"); userResponse = Char.Parse(Console.ReadLine()); //Conditional Statement for File Upload to a Blob Container if (userResponse == 'y' || userResponse == 'Y') { Console.Write("Press any key to begin clean up"); Console.ReadLine(); Console.WriteLine("Deleting blob container..."); //Sets deletion for this container myContainerClient.Delete(); Console.WriteLine("Done"); } } else { Console.WriteLine("fine, bye"); } }