public async Task DeleteByPrefixAsync(string prefix, CancellationToken ct = default) { var name = GetFileName(prefix, nameof(prefix)); var items = blobContainer.GetBlobsAsync(prefix: name, cancellationToken: ct); await foreach (var item in items.WithCancellation(ct)) { ct.ThrowIfCancellationRequested(); await blobContainer.DeleteBlobIfExistsAsync(item.Name, cancellationToken : ct); } }
public async Task <IActionResult> Delete(string mediaId) { try { _logger.LogDebug("deleting media"); var mediaModel = (await _unitOfWork.Media.SelectAsync(e => e.id == mediaId)).First(); string blobName = mediaModel.Uri.Substring(mediaModel.Uri.LastIndexOf('/') + 1); BlobServiceClient blobServiceClient = new BlobServiceClient(_configuration.GetConnectionString("storage")); BlobContainerClient containerClient = blobServiceClient.GetBlobContainerClient(mediaModel.Group); await containerClient.DeleteBlobIfExistsAsync(blobName); await _unitOfWork.Media.DeleteAsync(mediaModel.id); await _unitOfWork.CommitAsync(); _logger.LogInformation($"deleted media"); return(Ok(mediaModel)); } catch { _logger.LogWarning($"missing media"); return(NotFound()); } }
public Task Delete(IWorkContext context, string path) { context.Verify(nameof(context)).IsNotNull(); path.Verify(nameof(path)).IsNotEmpty(); return(_containerClient.DeleteBlobIfExistsAsync(path, cancellationToken: context.CancellationToken)); }
private async Task DeleteBlobsAsync(BlobContainerClient container, IEnumerable <BlobItem> blobs) { foreach (var blobItem in blobs) { await container.DeleteBlobIfExistsAsync(blobItem.Name, DeleteSnapshotsOption.IncludeSnapshots); } }
/// <summary> /// Deletes a file or folder. /// </summary> /// <param name="filepath">The path to the file.</param> /// <param name="isDirectory">Determines if the <paramref name="filepath"/> points to a single file or a directory.</param> public async Task <bool> DeleteAsync(string filepath, bool isDirectory = false) { filepath = filepath.TrimStart('\\', '/'); var folder = _environmentName ?? Path.GetDirectoryName(filepath); var filename = _environmentName == null?filepath.Substring(folder.Length) : filepath; var container = new BlobContainerClient(_connectionString, folder); var exists = await container.ExistsAsync(); if (!exists) { throw new FileNotFoundServiceException($"Container {folder} not found."); } bool deleted; if (!isDirectory) { var blob = container.GetBlobClient(filename); deleted = await blob.DeleteIfExistsAsync(); } else { var segment = container.GetBlobsAsync(prefix: filename); await foreach (var blob in segment) { await container.DeleteBlobIfExistsAsync(blob.Name, DeleteSnapshotsOption.IncludeSnapshots); } deleted = true; } return(deleted); }
private async void Upload_DoWork(object sender, DoWorkEventArgs e) { try { string connectionString = $@"DefaultEndpointsProtocol=https; AccountName={_Account}; AccountKey={_Key}; BlobEndpoint=https://{_Account}.blob.core.windows.net; TableEndpoint=https://{_Account}.blob.core.windows.net; QueueEndpoint=https://{_Account}.blob.core.windows.net;"; var client = new BlobServiceClient(connectionString); BlobContainerClient container = (await client.CreateBlobContainerAsync(_ContainerName)).Value; await container.CreateIfNotExistsAsync(PublicAccessType.BlobContainer); await container.SetAccessPolicyAsync(PublicAccessType.BlobContainer); string directoryName = Path.GetDirectoryName(_FovFilename); string blobName = $"{_ContainerName}/{_ManifestInfo.Name}.ism/Manifest"; await container.DeleteBlobIfExistsAsync(blobName); using (var manifest = File.OpenRead(_ManifestInfo.Filename)) { await container.UploadBlobAsync(blobName, manifest); } await Task.WhenAll(File.ReadAllLines(_FovFilename).Select(async line => { string[] arr = line.Split(','); string mediatype = arr[0].Split('=')[1]; string bitrate = arr[1].Split('=')[1]; string starttime = arr[2].Split('=')[1]; string file = arr[3].Split('=')[1]; string offset = arr[4].Split('=')[1]; string size = arr[5].Split('=')[1]; string path = $"{_ContainerName}/{_ManifestInfo.Name}.ism/QualityLevels({bitrate})/Fragments({mediatype}={starttime})"; using var stream = File.OpenRead(Path.Combine(directoryName, file)); stream.Position = int.Parse(offset); stream.SetLength(stream.Position + int.Parse(size)); await container.DeleteBlobIfExistsAsync(path); await container.UploadBlobAsync(path, stream); })); } catch (Exception ex) { _DoWorkException = ex; } }
private static async Task DeleteObjectAsync(BlobContainerClient client, string fileName, CancellationToken token) { try { await client.DeleteBlobIfExistsAsync(fileName, cancellationToken : token); } catch (Exception ex) { throw; } }
public async Task DeleteAsync(string fileName) { try { await _container.DeleteBlobIfExistsAsync(fileName); } catch (Exception e) { _logger.LogError(e, $"Error deleting file {fileName} on Azure, it must be my problem, not Microsoft."); throw; } }
private async Task DeleteOldBlobsAsync(List <string> blobNames) { var currentBlobs = containerClient.GetBlobsAsync(); await foreach (var cb in currentBlobs) { if (!Constants.GithubSitePages.Equals(cb.Name, StringComparison.OrdinalIgnoreCase) && !blobNames.Where(bn => bn.Equals(cb.Name, StringComparison.OrdinalIgnoreCase)).Any()) { await containerClient.DeleteBlobIfExistsAsync(cb.Name); } } }
public async Task DeleteFile(string fileUrl) { if (string.IsNullOrWhiteSpace(fileUrl)) { return; } var uri = new Uri(fileUrl); var filename = Path.GetFileName(uri.LocalPath); var blobContainer = new BlobContainerClient(settings.ConnectionString, settings.ProfileContainer); await blobContainer.DeleteBlobIfExistsAsync(filename, DeleteSnapshotsOption.IncludeSnapshots); }
public static async Task DeleteBlobAsync(this BlobContainerClient blobContainerClient, string name) { if (!AzureStorage.UseExists) { await blobContainerClient.DeleteBlobIfExistsAsync(name); } else { var blobClient = blobContainerClient.GetBlobClient(name); if (await blobClient.ExistsAsync()) { await blobClient.DeleteAsync(); } } }
/// <summary> /// Initiates an asynchronous operation to delete picture thumbs /// </summary> /// <param name="picture">Picture</param> protected override async Task DeletePictureThumbsAsync(Picture picture) { //create a string containing the Blob name prefix var prefix = $"{picture.Id:0000000}"; var tasks = new List <Task>(); await foreach (var blob in _blobContainerClient.GetBlobsAsync(BlobTraits.All, BlobStates.All, prefix)) { tasks.Add(_blobContainerClient.DeleteBlobIfExistsAsync(blob.Name, DeleteSnapshotsOption.IncludeSnapshots)); } await Task.WhenAll(tasks); await _staticCacheManager.RemoveByPrefixAsync(NopMediaDefaults.ThumbsExistsPrefix); }
public async Task DehydrateBlob(CancellationToken cancellationToken) { // Set the scrub time to one hour var scrubTime = DateTimeOffset.Now.AddHours(-1); _logger.LogInformation($"Attempting to dehydrate container {_blobContainerClient.Name}..."); await foreach (var blob in _blobContainerClient.GetBlobsAsync(cancellationToken: cancellationToken).ConfigureAwait(false)) { if (!blob.Properties.CreatedOn.HasValue || DateTimeOffset.Compare(scrubTime, blob.Properties.CreatedOn.Value) > 0) { _logger.LogInformation($"Long lived CSV found {blob.Name}, removing from container {_blobContainerClient.Name}..."); await _blobContainerClient.DeleteBlobIfExistsAsync(blob.Name, cancellationToken : cancellationToken).ConfigureAwait(false); _logger.LogInformation($"CSV blob {blob.Name} successfully removed from container {_blobContainerClient.Name}!"); } } _logger.LogInformation($"Container {_blobContainerClient.Name} successfully dehydrated!"); }
public async Task <IActionResult> DeleteBlobs() { BlobContainerClient cc = new BlobContainerClient(_configuration["StorageConnString"], "content"); var blobs = cc.GetBlobs(BlobTraits.All, BlobStates.All).ToList(); foreach (var b in blobs) { await cc.DeleteBlobIfExistsAsync(b.Name); } _telemetryClient.TrackEvent("sponsorDeleted", new Dictionary <string, string>() { { "user", User.Identity.Name } }); return(new OkResult()); }
/// <inheritdoc/> public async Task <List <string> > ListBlobVersions(string org, string app, string instanceGuid, string dataGuid) { List <string> deletedBlobs = new List <string>(); List <string> versions = new List <string>(); int counter = 1; BlobContainerClient container = await _clientProvider.GetBlobClient(org, Program.Environment); BlockBlobClient client = container.GetBlockBlobClient($"{org}/{app}/{instanceGuid}/data/{dataGuid}"); await foreach (BlobItem i in container.GetBlobsAsync(BlobTraits.None, BlobStates.Deleted, prefix: client.Name)) { if (i.Deleted) { deletedBlobs.Add(i.Name); } } if (!await client.ExistsAsync()) { return(new List <string>()); } await client.UndeleteAsync(); await foreach (BlobItem i in container.GetBlobsAsync(BlobTraits.None, BlobStates.All, prefix: client.Name)) { versions.Add($"Version {counter} \t Last modified {i.Properties.LastModified} \t Restore timestamp: {i.Snapshot ?? "N/A"}"); counter++; } // original state for snapshots is deleteing, so restoring this state await client.DeleteIfExistsAsync(DeleteSnapshotsOption.OnlySnapshots); // deleting the blob itself if it was originally deleted foreach (string name in deletedBlobs) { await container.DeleteBlobIfExistsAsync(name, DeleteSnapshotsOption.None); } return(versions); }
public async Task <ActionResult> DeleteAll() { try { foreach (var blob in blobContainer.GetBlobs()) { if (blob.Properties.BlobType == BlobType.Block) { await blobContainer.DeleteBlobIfExistsAsync(blob.Name); } } return(RedirectToAction("Index")); } catch (Exception ex) { ViewData["message"] = ex.Message; ViewData["trace"] = ex.StackTrace; return(View("Error")); } }
public async Task RemoveExpiredAsync(string directoryRelativeAddress = null, CancellationToken cancellationToken = default) { directoryRelativeAddress ??= _defaultDirectoryRelativeAddress; var utcNow = DateTimeOffset.UtcNow; await foreach (var blob in _containerClient.GetBlobsAsync(BlobTraits.Metadata, BlobStates.None, directoryRelativeAddress, cancellationToken)) { cancellationToken.ThrowIfCancellationRequested(); // skip non-expired if (!blob.Properties.ExpiresOn.HasValue || blob.Properties.ExpiresOn.Value > utcNow) { continue; } try { await _containerClient.DeleteBlobIfExistsAsync(blob.Name, DeleteSnapshotsOption.IncludeSnapshots, new BlobRequestConditions() { IfMatch = blob.Properties.ETag }, cancellationToken).ConfigureAwait(false); } catch (RequestFailedException ex) { // 404: not found if (ex.Status == 404) { continue; } // 412: preconditions failed, optimistic concurrency check failed if (ex.Status == 412) { continue; } throw; } } }
public async Task <Response> DeleteAsync(string fileName) { try { var ok = await _container.DeleteBlobIfExistsAsync(fileName); if (ok) { return(new SuccessResponse()); } return(new FailedResponse((int)ImageResponseCode.ImageNotExistInAzureBlob)); } catch (Exception e) { _logger.LogError(e, $"Error deleting file {fileName} on Azure, it must be my problem, not Microsoft."); return(new FailedResponse((int)ImageResponseCode.GeneralException) { Exception = e, Message = e.Message }); } }
public async Task PurgeAsync() { var imageTableResults = new List <ImageTableEntity>(); TableQuery <ImageTableEntity> tableQuery = new TableQuery <ImageTableEntity>(); TableContinuationToken tableContinuationToken = null; do { TableQuerySegment <ImageTableEntity> tableQueryResult = await imageTable.ExecuteQuerySegmentedAsync(tableQuery, tableContinuationToken); tableContinuationToken = tableQueryResult.ContinuationToken; var tasks = tableQueryResult.Results.Select(async result => await imageTable.ExecuteAsync(TableOperation.Delete(result))); await Task.WhenAll(tasks); } while (tableContinuationToken != null); string continuationToken = null; do { var resultSegment = blobContainerClient.GetBlobs().AsPages(continuationToken); foreach (Azure.Page <BlobItem> blobPage in resultSegment) { foreach (BlobItem blobItem in blobPage.Values) { await blobContainerClient.DeleteBlobIfExistsAsync(blobItem.Name); } continuationToken = blobPage.ContinuationToken; } } while (continuationToken != ""); }
/*public async Task<> GetimageBlob(string id){ * if(await containerClient.ExistsAsync()){ * var f = containerClient.GetBlobClient(id); * Stream im; * var g = await f.DownloadAsync(); * } * }*/ public async Task RemoveBlobContainer(int order) { await containerClient.DeleteBlobIfExistsAsync(order.ToString()); }
public async Task DeleteBlobAsync(BlobContainerClient blobContainerClient, string name) { Guard.IsNotNull(blobContainerClient, nameof(blobContainerClient)); await blobContainerClient.DeleteBlobIfExistsAsync(name); }
public override Task DeleteAsync(Upload upload, CancellationToken cancellationToken) { return(_blobContainerClient.DeleteBlobIfExistsAsync(upload.Id + upload.Extension)); }
public async Task DeleteFile(string userId) { await containerClient.DeleteBlobIfExistsAsync($"{userId}.zip"); }
public async Task DeleteBlobAsync(string blobName) { await containerClient.DeleteBlobIfExistsAsync(blobName); }
public async Task DeleteAsync(string fileName) { await _container.DeleteBlobIfExistsAsync(fileName); }
public Task DeleteTestData(string id) { return(_testRunSummariesContainer.DeleteBlobIfExistsAsync(id)); }
public async Task <ActionResult> Delete (Guid id, [Bind("ProductId,ProductName,Quantity,SellingPricePerUnit,Image,CreatedByUserId,UpdatedByUserId,LastUpdatedOn")] ProductViewModel productViewModel) { var user = await _userManager.GetUserAsync(User); if (user == null) { ModelState.AddModelError("Delete", "User not found. Please log back in"); } var errors = ModelState .Where(x => x.Value.Errors.Count > 0) .Select(x => new { x.Key, x.Value.Errors }) .ToArray(); foreach (var key in ModelState.Keys) { ModelState[key].Errors.Clear(); } if (!ModelState.IsValid) { return(View(productViewModel)); } //load the data from db for row to be deleted Product deleteProduct = await _context.Products.FindAsync(id); if (deleteProduct == null) { return(NotFound()); } var storageConn = _config.GetValue <string>("ConnectionStrings:AzureConnection"); // Get a reference to a Container BlobContainerClient blobContainerClient = new BlobContainerClient(storageConn, BlobContainerNAME); // Create the container if it does not exist - granting PUBLIC access. await blobContainerClient.CreateIfNotExistsAsync( Azure.Storage.Blobs.Models.PublicAccessType.BlobContainer); //delete the image file in azure blob container await blobContainerClient.DeleteBlobIfExistsAsync(id.ToString()); // update the db try { _context.Products.Remove(deleteProduct); _context.SaveChanges(); return(RedirectToAction(nameof(Index))); } catch (System.Exception exp) { ModelState.AddModelError("Delete", "Unable to Delete from the db. Contact Admin"); _logger.LogError($"Delete Product Failed: {exp.Message}"); return(View(productViewModel)); } }
public static async Task UploadBlobAsync(this BlobContainerClient blobContainerClient, string name, Stream stream) { await blobContainerClient.DeleteBlobIfExistsAsync(name); await blobContainerClient.UploadBlobAsync(name, stream); }
public async Task DeleteAsync(string path) { await _client.DeleteBlobIfExistsAsync(path); }
public Task DeleteTestRunRecord(string id) { return(_testDataContainer.DeleteBlobIfExistsAsync(id)); }