Exemplo n.º 1
0
        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);
            }
        }
Exemplo n.º 2
0
        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());
            }
        }
Exemplo n.º 3
0
        public Task Delete(IWorkContext context, string path)
        {
            context.Verify(nameof(context)).IsNotNull();
            path.Verify(nameof(path)).IsNotEmpty();

            return(_containerClient.DeleteBlobIfExistsAsync(path, cancellationToken: context.CancellationToken));
        }
Exemplo n.º 4
0
 private async Task DeleteBlobsAsync(BlobContainerClient container, IEnumerable <BlobItem> blobs)
 {
     foreach (var blobItem in blobs)
     {
         await container.DeleteBlobIfExistsAsync(blobItem.Name, DeleteSnapshotsOption.IncludeSnapshots);
     }
 }
Exemplo n.º 5
0
        /// <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);
        }
Exemplo n.º 6
0
        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;
     }
 }
Exemplo n.º 8
0
 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;
     }
 }
Exemplo n.º 9
0
        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);
        }
Exemplo n.º 11
0
 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();
         }
     }
 }
Exemplo n.º 12
0
        /// <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!");
        }
Exemplo n.º 14
0
        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());
        }
Exemplo n.º 15
0
        /// <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"));
            }
        }
Exemplo n.º 17
0
        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;
                }
            }
        }
Exemplo n.º 18
0
        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
                });
            }
        }
Exemplo n.º 19
0
        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 != "");
        }
Exemplo n.º 20
0
 /*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());
 }
Exemplo n.º 21
0
 public async Task DeleteBlobAsync(BlobContainerClient blobContainerClient, string name)
 {
     Guard.IsNotNull(blobContainerClient, nameof(blobContainerClient));
     await blobContainerClient.DeleteBlobIfExistsAsync(name);
 }
Exemplo n.º 22
0
 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");
 }
Exemplo n.º 24
0
 public async Task DeleteBlobAsync(string blobName)
 {
     await containerClient.DeleteBlobIfExistsAsync(blobName);
 }
Exemplo n.º 25
0
 public async Task DeleteAsync(string fileName)
 {
     await _container.DeleteBlobIfExistsAsync(fileName);
 }
Exemplo n.º 26
0
 public Task DeleteTestData(string id)
 {
     return(_testRunSummariesContainer.DeleteBlobIfExistsAsync(id));
 }
Exemplo n.º 27
0
        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));
            }
        }
Exemplo n.º 28
0
        public static async Task UploadBlobAsync(this BlobContainerClient blobContainerClient, string name, Stream stream)
        {
            await blobContainerClient.DeleteBlobIfExistsAsync(name);

            await blobContainerClient.UploadBlobAsync(name, stream);
        }
Exemplo n.º 29
0
 public async Task DeleteAsync(string path)
 {
     await _client.DeleteBlobIfExistsAsync(path);
 }
Exemplo n.º 30
0
 public Task DeleteTestRunRecord(string id)
 {
     return(_testDataContainer.DeleteBlobIfExistsAsync(id));
 }