public static async Task DeleteBlobAsync(BlobMetadata blobMetadata, ILogger log) { log.LogInformation($"Delete queue process item: {blobMetadata}"); string containerEndpoint = string.Format("https://{0}.blob.core.windows.net/{1}", Common.GetEnvironmentVariable("SA_NAME"), blobMetadata.ContainerName); var blobPathAndName = $"{blobMetadata.BlobPath}/{blobMetadata.BlobName}"; BlobContainerClient sourceBlobContainerClient = new BlobContainerClient(new Uri(containerEndpoint), new DefaultAzureCredential()); try { if (await sourceBlobContainerClient.ExistsAsync()) { BlobClient blob = sourceBlobContainerClient.GetBlobClient(blobPathAndName); if (await blob.ExistsAsync()) { await blob.DeleteAsync(); log.LogInformation($"Blob {blobMetadata.BlobName} is deleted"); } } } catch (RequestFailedException) { log.LogInformation($"Failed to complete blob deleting operation: {blobMetadata}"); throw; } }
//private async void UploadImage(string getPath) //{ // var connectionString = "DefaultEndpointsProtocol=https;AccountName=imarketimagestorage;AccountKey=e7Panrt3KDC5WRWIq7jE3ZQ6kP6iDesjUkvWkQanU1oSYHxrgOEcCu528Tg9vA2Ra7Birbu5WOv57ga5pE9puw==;EndpointSuffix=core.windows.net"; // var containerName = "imagestorage"; // var filepath = getPath; // var container = new BlobContainerClient(connectionString, containerName); // await container.CreateIfNotExistsAsync(); // var name = Guid.NewGuid().ToString(); // await container.UploadBlobAsync($"{name}.jpg", File.OpenRead(filepath)); // string url = container.Uri.OriginalString; //} private async Task UploadImage(string getPath) { try { //Uploading pictures to image container in azure progressload.IsVisible = true; lblprogressstat.Text = "Uploading profile picture . . ."; var connectionString = "DefaultEndpointsProtocol=https;AccountName=greenmareetimagesstorage;AccountKey=fZO7MmX5iz9TWoet4B3ItpLwDdHB9NamxNC8Pw0vbIIP3kHys174yopRszz837VglA9dKEFum8iH6M1WiiNugQ==;EndpointSuffix=core.windows.net"; var containerName = "greenmareetimagesstorage"; var filepath = getPath; var container = new BlobContainerClient(connectionString, containerName); await container.CreateIfNotExistsAsync(); //Upon updating, the existing image must be deleted to avoid duplication in the container BlobClient picuri = container.GetBlobClient(picstr); if (picuri.Name != "") { await picuri.DeleteAsync(); } _imgId = Guid.NewGuid().ToString(); await container.UploadBlobAsync($"{_imgId}.jpg", File.OpenRead(filepath)); _url = container.Uri.OriginalString; await Updateprofile(); } catch { progressload.IsVisible = false; await Navigation.PushAsync(new NoInternetPage(), true); } }
public async Task <IHttpActionResult> Delete([FromUri] int id) { if (id < 0) { return(BadRequest("Id is negative")); } if (!bookService.Exist(id)) { return(NotFound()); } var book = bookService.Get(id); var containerClient = GetBlobContainer(); var name = containerClient.GetBlobs() .Where(b => b.Name.Contains($"{book.Id}-{book.Name}")) .Select(b => b.Name).FirstOrDefault(); if (name != null) { // Get a reference to a blob BlobClient blobClient = containerClient.GetBlobClient(name); await blobClient.DeleteAsync(); } bookService.Delete(id); return(ResponseMessage(new HttpResponseMessage(HttpStatusCode.NoContent))); }
public static async Task DeleteBlobAsync(string account, string key, string containerName, string blobName) { BlobServiceClient blobServiceClient = new BlobServiceClient(Client.GetConnectionString(account, key)); BlobContainerClient container = blobServiceClient.GetBlobContainerClient(containerName); BlobClient blob = container.GetBlobClient(blobName); await blob.DeleteAsync(); }
public async Task <IActionResult> Delete(string filename) { var containerClient = await StartAzureConnection(); BlobClient blobClient = containerClient.GetBlobClient(filename); await blobClient.DeleteAsync(); return(RedirectToAction("Files")); }
private static async Task RenameAsync(BlobContainerClient container, string oldName, string newName) { BlobClient source = container.GetBlobClient(oldName); BlobClient target = container.GetBlobClient(newName); await target.StartCopyFromUriAsync(source.Uri); await source.DeleteAsync(); }
public async Task RemoveAsync(ProductRef product) { BlobClient blob = await this.OpenBlobClient(product); if ((await blob.ExistsAsync())) { await blob.DeleteAsync(); } }
public async Task DeleteAsync(string containerName, string fileName) { this.logger.Info($"Call: {nameof(DeleteAsync)}('{containerName}', '{fileName}')"); BlobContainerClient containerClient = await blobServiceClient.CreateBlobContainerAsync(containerName); BlobClient blobClient = containerClient.GetBlobClient(fileName); await blobClient.DeleteAsync(); this.logger.Info($"File '{fileName}' deleted from blob storage."); }
public async Task RemoveBlobAsync(string containerName, string blobUrl, CancellationToken cancellationToken = default) { BlobClient blobClient = azureStorageClientFactory.GetBlobClient(containerName, blobUrl); if (!await blobClient.ExistsAsync(cancellationToken)) { throw new ArgumentException($"Blob {blobUrl} is not available."); } await blobClient.DeleteAsync(cancellationToken : cancellationToken); }
public async Task <bool> Delete(string uploadBlob, string downloadBlob) { BlobClient uploadClient = azureContainerClient.GetBlobClient(uploadBlob); BlobClient downloadClient = azureContainerClient.GetBlobClient(downloadBlob); var uploadDeleteTask = uploadClient.DeleteAsync(); var downloadDeleteTask = downloadClient.DeleteAsync(); var deleteResult = await Task.WhenAll(uploadDeleteTask, downloadDeleteTask); return(deleteResult.Where(m => m.Status >= 200 && m.Status <= 300)?.Count() == 2); }
public async Task DeleteAsync(string caseId) { var searchResults = await indexClient.SearchDocumentsFilteringByFieldAsync <IndexedContent>(CaseId, caseId); foreach (var result in searchResults) { var blobName = Base64Utils.Decode(result.Document.Id); await blobClient.DeleteAsync(blobName); await indexClient.DeleteEntryAsync(result.Document.Id); } }
public async Task <IHttpActionResult> Upload([FromUri] int id) { if (System.Web.HttpContext.Current.Request.Files.AllKeys.Length > 0) { // Get the files using the name attribute as a key. var httpPostedFile = System.Web.HttpContext.Current.Request.Files["file"]; if (httpPostedFile != null) { BookDTO book; if (id <= 0) { return(BadRequest("Id is negative")); } try { book = bookService.Get(id); } catch (ValidationException ex) { return(NotFound()); } var fname = httpPostedFile.FileName; var blobName = $"{book.Id}-{book.Name}{fname.Substring(fname.LastIndexOf("."))}"; var container = GetBlobContainer(); var name = container.GetBlobs() .Where(b => b.Name.Contains($"{book.Id}-{book.Name}")) .Select(b => b.Name).FirstOrDefault(); if (name != null) { // Get a reference to a blob BlobClient blobClient = container.GetBlobClient(name); await blobClient.DeleteAsync(); } var blockBlob = container.GetBlobClient(blobName); try { await blockBlob.UploadAsync(httpPostedFile.InputStream); return(Ok()); } catch (Exception ex) { return(BadRequest(ex.Message)); } } return(BadRequest("File is null")); } return(BadRequest("File is not found")); }
public async Task <bool> RemoveBlobIfExistsAsync(string containerName, string blobUrl, CancellationToken cancellationToken = default) { BlobClient blobClient = azureStorageClientFactory.GetBlobClient(containerName, blobUrl); if (await blobClient.ExistsAsync(cancellationToken)) { await blobClient.DeleteAsync(cancellationToken : cancellationToken); return(true); } return(false); }
public static async Task <IActionResult> DeleteTodo( [HttpTrigger(AuthorizationLevel.Anonymous, "delete", Route = Route + "/{id}")] HttpRequest req, [Blob(BlobPath + "/{id}.json", Connection = "AzureWebJobsStorage")] BlobClient blob, ILogger log, string id) { if (!await blob.ExistsAsync()) { return(new NotFoundResult()); } await blob.DeleteAsync(); return(new OkResult()); }
public async Task RenameBlob(string id, string newName, string displayName) { var blobClient = new BlobClient(new Uri(id)); var containerName = blobClient.BlobContainerName; var blobName = blobClient.Name; blobClient = new BlobClient(_connectionString, containerName, blobName); var targetBlobClient = new BlobClient(_connectionString, containerName, newName); await targetBlobClient.SyncCopyFromUriAsync(new Uri(id)); await blobClient.DeleteAsync(); }
public async Task DeleteAsync(Data item) { BlobClient blob = container.GetBlobClient(item.Key); if (blob.Exists()) { await blob.DeleteAsync(); } if (BackingDataAccess != null) { await BackingDataAccess.DeleteAsync(item); } }
public async Task <JsonResult> OnPostUploadProfilePhoto(IFormFile ProfilePhoto) { var returnMessage = "failure"; string userId = _userManager.GetUserId(User); // 1. Convert image to byte array for photo manipulation. byte[] result = null; using var fileStream = ProfilePhoto.OpenReadStream(); using (var outStream = new MemoryStream()) { var imageStream = Image.FromStream(fileStream); var height = (150 * imageStream.Height) / imageStream.Width; var thumbnail = imageStream.GetThumbnailImage(150, 150, null, IntPtr.Zero); using (var thumbnailStream = new MemoryStream()) { thumbnail.Save(thumbnailStream, ImageFormat.Png); result = thumbnailStream.ToArray(); } } // 2. Connect to Azure Storage account. var connectionString = _configuration.GetConnectionString("AccessKey"); BlobServiceClient blobServiceClient = new BlobServiceClient(connectionString); // 3. Use container for users profile photos. string containerName = "profilephotos"; BlobContainerClient containerClient = blobServiceClient.GetBlobContainerClient(containerName); // 4. Create new blob and upload to azure storage account. var stream = new MemoryStream(result); BlobClient blobClient = containerClient.GetBlobClient("profile-" + userId + ".png"); if (!blobClient.Exists()) { await blobClient.UploadAsync(stream, true); } else { await blobClient.DeleteAsync(); await blobClient.UploadAsync(stream, true); } return(new JsonResult(returnMessage)); }
public async Task <bool> DeleteAttachmentAsync(string queueName, string id, CancellationToken cancellationToken = default(CancellationToken)) { var blob = new BlobClient(_connectionString, queueName, id); try { await blob.DeleteAsync(DeleteSnapshotsOption.None, cancellationToken : cancellationToken).ConfigureAwait(false); return(true); } catch { return(false); } }
public async Task <Result> DeleteFile(string path) { BlobClient blob = _client.GetBlobClient(path); try { using Response response = await blob.DeleteAsync(); return(((response.Status / 100) == 2) ? Result.Succeeded : Result.Failed); } catch (RequestFailedException ex) { return(ex.Message.Contains("BlobNotFound") ? Result.FileNotFound : Result.Failed); } }
/// <inheritdoc/> public async Task <bool> DeleteBlobsAsync(string blobName) { BlobClient blobClient = this.blobContainerClient.GetBlobClient(blobName); bool isExists = await blobClient.ExistsAsync().ConfigureAwait(false); if (isExists) { var response = await blobClient.DeleteAsync().ConfigureAwait(false); return(true); } else { this.logger.TraceWarning($"BlobStorageClient - Method: {nameof(this.DeleteBlobsAsync)} - No blob found with name {blobName}."); return(false); } }
public async Task <Data> CreateAsync(Data item) { if (BackingDataAccess != null) { item = await BackingDataAccess.CreateAsync(item); } BlobClient blob = container.GetBlobClient(item.Key); if (blob.Exists()) { await blob.DeleteAsync(); } byte[] byteArray = Encoding.ASCII.GetBytes(JsonConvert.SerializeObject(item)); MemoryStream stream = new MemoryStream(byteArray); await blob.UploadAsync(stream); return(item); }
public async Task <bool> DeleteData(StoreFileInfo fileInfo) { try { if (!this.ParseBlockName(fileInfo.FileAddress, out string container, out string folder, out string fileName)) { return(false); } BlobContainerClient blobContainer = new BlobContainerClient(this.connection, container); await blobContainer.CreateIfNotExistsAsync(); // Get a reference to a blob named "sample-file" in a container named "sample-container" BlobClient blob = blobContainer.GetBlobClient(folder + "/" + fileName); Response response = await blob.DeleteAsync(); return(true); } catch (Exception e) { this.Logger.LogError(e, e.Message); return(false); } }
public async Task DeleteAsync(IFileEntry fileEntry, CancellationToken cancellationToken = default) { BlobClient blob = _container.GetBlobClient(GetBlobName(fileEntry)); await blob.DeleteAsync(cancellationToken : cancellationToken); }
public async Task RemoveAudioFileFromStorage() { await _blobClient.DeleteAsync(); TestContext.WriteLine("Deleted audio file"); }
public async Task deleteBlob(string containerName, string fileName) { BlobContainerClient blobContainerClient = createOrGetContainer(containerName); BlobClient blobClient = blobContainerClient.GetBlobClient(fileName); await blobClient.DeleteAsync(); }
public async Task DeleteAsync(string uri) { CloudBlockBlob blob_temp = new CloudBlockBlob(new Uri(uri)); BlobClient blobClient = this.GetBlobClient(this._options.ContainerName.ToLower(), blob_temp.Name); await blobClient.DeleteAsync(); }
public async Task DeleteBlobAsync(string containerName, string blobName) { var blobClient = new BlobClient(this.ConnectionString, containerName, blobName); await blobClient.DeleteAsync(); }
public async Task DeleteAsync(string containerName, string name) { BlobContainerClient container = _client.GetBlobContainerClient(containerName); BlobClient blob = container.GetBlobClient(name); await blob.DeleteAsync(); }
/// <summary> /// Deletes a blob in Storage /// </summary> /// <param name="blobId">Id of stored blob returned by <see cref="UploadBlobAsync(Stream, ClaimsPrincipal)"/></param> /// <param name="user">Current user</param> public async Task DeleteBlobAsync(Guid blobId, ClaimsPrincipal user) { BlobClient client = GetBlobClient(blobId, user); await client.DeleteAsync(); }
public async Task ClaimCheck() { await using (var scope = await ServiceBusScope.CreateWithQueue(enablePartitioning: false, enableSession: false)) { #region Snippet:CreateBlobContainer #if SNIPPET var containerClient = new BlobContainerClient("<storage connection string>", "claim-checks"); #else var containerClient = new BlobContainerClient(TestEnvironment.StorageClaimCheckConnectionString, "claim-checks"); #endif await containerClient.CreateIfNotExistsAsync(); #endregion try { #region Snippet:UploadMessage byte[] body = ServiceBusTestUtilities.GetRandomBuffer(1000000); string blobName = Guid.NewGuid().ToString(); await containerClient.UploadBlobAsync(blobName, new BinaryData(body)); var message = new ServiceBusMessage { ApplicationProperties = { ["blob-name"] = blobName } }; #endregion #region Snippet:ClaimCheckSendMessage #if SNIPPET var client = new ServiceBusClient("<service bus connection string>"); #else var client = new ServiceBusClient(TestEnvironment.ServiceBusConnectionString); #endif ServiceBusSender sender = client.CreateSender(scope.QueueName); await sender.SendMessageAsync(message); #endregion #region Snippet:ReceiveClaimCheck ServiceBusReceiver receiver = client.CreateReceiver(scope.QueueName); ServiceBusReceivedMessage receivedMessage = await receiver.ReceiveMessageAsync(); if (receivedMessage.ApplicationProperties.TryGetValue("blob-name", out object blobNameReceived)) { #if SNIPPET var blobClient = new BlobClient("<storage connection string>", "claim-checks", (string)blobNameReceived); #else var blobClient = new BlobClient( TestEnvironment.StorageClaimCheckConnectionString, "claim-checks", (string)blobNameReceived); #endif BlobDownloadResult downloadResult = await blobClient.DownloadContentAsync(); BinaryData messageBody = downloadResult.Content; // Once we determine that we are done with the message, we complete it and delete the corresponding blob. await receiver.CompleteMessageAsync(receivedMessage); await blobClient.DeleteAsync(); #if !SNIPPET Assert.AreEqual(body, messageBody.ToArray()); #endif } #endregion } finally { await containerClient.DeleteAsync(); } } }