/// <summary>
        /// Delete the specified file from the Azure container.
        /// </summary>
        /// <param name="path">the file to be deleted</param>
        public async Task <bool> DeleteFile(string path)
        {
            if (!(await IsValidFile(path)))
            {
                return(false);
            }

            // convert to azure path
            string blobPath = path.ToAzurePath();

            var container = _container;

            rootFix(ref container, ref blobPath);

            CloudBlob b = container.GetBlobReference(blobPath);

            if (b != null)
            {
                await b.DeleteAsync();
            }
            else
            {
                Console.WriteLine("Error: Get blob reference \"{0}\" failed", path);
                return(false);
            }
            return(true);
        }
Esempio n. 2
0
        public async Task <IActionResult> OnPostAsync(int?id)
        {
            if (id == null)
            {
                return(NotFound());
            }

            Product = await _productManager.GetProductByID((int)id);


            var container = await BlobImage.GetContainer("product-image-asset-blob");

            string[] imageURIArray = Product.Image.Split("/");
            string   imageName     = imageURIArray[imageURIArray.Length - 1];

            CloudBlob image = await BlobImage.GetBlob(imageName, container.Name);

            if (image != null)
            {
                await image.DeleteAsync();
            }

            if (Product != null)
            {
                await _productManager.DeleteProduct(Product);
            }

            return(RedirectToPage("./Index"));
        }
Esempio n. 3
0
        /// <summary>
        /// Delete file from azure blob storage
        /// </summary>
        /// <param name="id">Accepting image id</param>
        public async Task <bool> Delete(string url)
        {
            try
            {
                if (CloudStorageAccount.TryParse(this._options.Value.StorageConnection, out CloudStorageAccount storageAccount))
                {
                    CloudBlobClient    BlobClient = storageAccount.CreateCloudBlobClient();
                    CloudBlobContainer container  = BlobClient.GetContainerReference(this._options.Value.Container);

                    if (await container.ExistsAsync())
                    {
                        CloudBlob file = container.GetBlobReference(url);

                        if (await file.ExistsAsync())
                        {
                            await file.DeleteAsync();
                        }
                    }
                }
                return(true);
            }
            catch (Exception ex)
            {
                return(false);
            }
        }
        public async Task <IActionResult> DeleteFile(string fileName)
        {
            try
            {
                if (CloudStorageAccount.TryParse(_config.Value.StorageConnection, out CloudStorageAccount storageAccount))
                {
                    CloudBlobClient    BlobClient = storageAccount.CreateCloudBlobClient();
                    CloudBlobContainer container  = BlobClient.GetContainerReference(_config.Value.Container);

                    if (await container.ExistsAsync())
                    {
                        CloudBlob file = container.GetBlobReference(fileName);

                        if (await file.ExistsAsync())
                        {
                            await file.DeleteAsync();
                        }
                    }
                }
                //return true;
                return(Ok(new { StatusCode = (int)HttpStatusCode.OK, Data = new { }, Message = HttpStatusCode.OK.ToString() }));
            }
            catch (Exception e)
            {
                _logger.LogError(e, e.Message);
                return(StatusCode((int)HttpStatusCode.InternalServerError, e.Message));
                //return false;
            }
        }
Esempio n. 5
0
        public async Task <bool> DeleteBlobData(int garageId, string containerName)
        {
            try
            {
                string fileName = $"{garageId}.png";

                CloudStorageAccount cloudStorageAccount = CloudStorageAccount.Parse(_configuration.GetConnectionString("StorageConnection"));
                CloudBlobClient     cloudBlobClient     = cloudStorageAccount.CreateCloudBlobClient();
                CloudBlobContainer  cloudBlobContainer  = cloudBlobClient.GetContainerReference(containerName);

                if (await cloudBlobContainer.ExistsAsync())
                {
                    CloudBlob file = cloudBlobContainer.GetBlobReference(fileName);

                    if (await file.ExistsAsync())
                    {
                        await file.DeleteAsync();
                    }
                }

                return(true);
            }
            catch (Exception ex)
            {
                throw (ex);
            }
        }
Esempio n. 6
0
        public async Task <bool> DeleteFile(string fileName)
        {
            MemoryStream        ms             = new MemoryStream();
            BlobManager         bm             = new BlobManager();
            CloudStorageAccount storageAccount = bm.InitializeAccount();
            CloudBlobClient     BlobClient     = storageAccount.CreateCloudBlobClient();
            CloudBlobContainer  container      = BlobClient.GetContainerReference("mysamplecontainer");

            try
            {
                if (await container.ExistsAsync())
                {
                    CloudBlob file = container.GetBlobReference(fileName);

                    if (await file.ExistsAsync())
                    {
                        await file.DeleteAsync();
                    }
                }
                return(true);
            }
            catch
            {
                return(false);
            }
        }
Esempio n. 7
0
        public async Task <bool> deleteAllImgs()
        {
            try
            {
                CloudBlobClient    BlobClient = acc.CreateCloudBlobClient();
                CloudBlobContainer container  = BlobClient.GetContainerReference(Container);

                if (await container.ExistsAsync())
                {
                    BlobResultSegment resultSegment = await container.ListBlobsSegmentedAsync(null);

                    foreach (IListBlobItem item in resultSegment.Results)
                    {
                        CloudBlockBlob blob = (CloudBlockBlob)item;
                        CloudBlob      file = container.GetBlobReference(blob.Name);
                        if (await file.ExistsAsync())
                        {
                            await file.DeleteAsync();
                        }
                    }
                }

                return(true);
            }
            catch (Exception ex)
            {
                return(false);
            }
        }
Esempio n. 8
0
        public override async Task <bool> MoveFile(FlatFile file, EFlatFilePath fromDirectory, EFlatFilePath toDirectory, string fileName)
        {
            try
            {
                var    fileNameWithoutExtension = Path.GetFileNameWithoutExtension(fileName);
                var    fileNameExtension        = Path.GetExtension(fileName);
                var    version = 0;
                string newFileName;

                var cloudFileDirectory = await GetFileDirectory(file);

                var cloudFromDirectory = cloudFileDirectory.GetDirectoryReference(file.GetPath(fromDirectory));
                var cloudToDirectory   = cloudFileDirectory.GetDirectoryReference(file.GetPath(toDirectory));

                CloudBlob sourceFile = cloudFromDirectory.GetBlockBlobReference(fileName);
                CloudBlob targetFile = cloudToDirectory.GetBlockBlobReference(fileName);

                while (await targetFile.ExistsAsync())
                {
                    version++;
                    newFileName = fileNameWithoutExtension + "_" + version.ToString() + fileNameExtension;
                    targetFile  = cloudToDirectory.GetBlockBlobReference(newFileName);
                }
                await targetFile.StartCopyAsync(sourceFile.Uri);

                await sourceFile.DeleteAsync();

                return(true);
            }
            catch (Exception ex)
            {
                throw new ConnectionException($"Failed to move file {file.Name} filename {Filename} from {fromDirectory} to {toDirectory}.  {ex.Message}", ex);
            }
        }
        public async Task <bool> DeleteFile(string fileName)
        {
            try
            {
                if (CloudStorageAccount.TryParse(storageConnection, out CloudStorageAccount storageAccount))
                {
                    CloudBlobClient    BlobClient = storageAccount.CreateCloudBlobClient();
                    CloudBlobContainer container  = BlobClient.GetContainerReference(storageContainer);

                    if (await container.ExistsAsync())
                    {
                        CloudBlob file = container.GetBlobReference(fileName);

                        if (await file.ExistsAsync())
                        {
                            await file.DeleteAsync();
                        }
                    }
                }
                return(true);
            }
            catch
            {
                return(false);
            }
        }
Esempio n. 10
0
        public async Task <IActionResult> DeleteFile(string fileName)
        {
            try
            {
                if (CloudStorageAccount.TryParse(config.Value.StorageConnection, out CloudStorageAccount storageAccount))
                {
                    CloudBlobClient    BlobClient = storageAccount.CreateCloudBlobClient();
                    CloudBlobContainer container  = BlobClient.GetContainerReference(config.Value.Container);

                    if (await container.ExistsAsync())
                    {
                        CloudBlob file = container.GetBlobReference(fileName);

                        if (await file.ExistsAsync())
                        {
                            await file.DeleteAsync();
                        }
                        else
                        {
                            // Acceptance criterion: in case the file does not exist...
                            return(Content("Deletion failed: File does not exist"));
                        }
                    }
                }
                else
                {
                    return(Content("Deletion failed: Error opening cloud storage"));
                }
                return(Content("Deletion successful: File has been deleted successfully"));
            }
            catch
            {
                return(Content("Deletion failed: File cannot be deleted as an exception occurred"));
            }
        }
Esempio n. 11
0
        public async Task MoveFile(CloudBlobContainer container, string fileName, string targetPath)
        {
            CloudBlob existBlob = container.GetBlobReference(fileName);
            CloudBlob newBlob   = container.GetBlobReference(targetPath);
            await newBlob.StartCopyAsync(existBlob.Uri);

            await existBlob.DeleteAsync();
        }
        public async Task Delete(string fileName)
        {
            CloudBlobContainer container = GetContainer();

            CloudBlob file = container.GetBlobReference(fileName);

            await file.DeleteAsync();
        }
Esempio n. 13
0
        public async Task DeleteBlobByUrl(string blobUrl)
        {
            CloudBlob toDelete = await GetBlobFromUrl(blobUrl).ConfigureAwait(false);

            if (toDelete != null)
            {
                await toDelete.DeleteAsync().ConfigureAwait(false);
            }
        }
Esempio n. 14
0
        public async Task fntDeleteBlob(Container cntContainer, List <BlobStructure> lstFiles)
        {
            var container = fntGetContainer(cntContainer);

            foreach (var item in lstFiles)
            {
                var blob = new CloudBlob(item.fntUri, container.ServiceClient);
                await blob.DeleteAsync();
            }
        }
        async Task CopyFileAsync(CloudBlob blob, string destinationKey, bool deleteSource = false)
        {
            CloudBlob blobCopy = Container.GetBlobReference(destinationKey);
            await blobCopy.StartCopyAsync(blob.Uri);

            if (deleteSource)
            {
                await blob.DeleteAsync();
            }
        }
Esempio n. 16
0
        public async Task <List <MusicInfo> > DeleteMusic(int id)
        {
            User user = await db.Users.FindAsync(UserId);

            Music music = await db.Musics.FindAsync(id);

            List <MusicInfo> res = new List <MusicInfo>();

            if (music != null)
            {
                try
                {
                    if (CloudStorageAccount.TryParse(storageConfig.Value.ConnectionString, out CloudStorageAccount storageAccount))
                    {
                        CloudBlobClient    blobClient = storageAccount.CreateCloudBlobClient();
                        CloudBlobContainer container  = blobClient.GetContainerReference(storageConfig.Value.ContainerName);
                        if (await container.ExistsAsync())
                        {
                            CloudBlob blob = container.GetBlobReference(music.MusicFileName);
                            if (await blob.ExistsAsync())
                            {
                                await blob.DeleteAsync();
                            }
                            if (music.MusicImageName != "default.png")
                            {
                                blob = container.GetBlobReference(music.MusicImageName);
                                if (await blob.ExistsAsync())
                                {
                                    await blob.DeleteAsync();
                                }
                            }
                            db.Musics.Remove(music);
                            await db.SaveChangesAsync();
                        }
                    }
                }
                catch
                {
                }
            }
            return(await GetMusicListByUserId(UserId));
        }
 /// <summary>
 /// Delete azure blob
 /// </summary>
 /// <param name="blob">Cloudblob object</param>
 /// <param name="deleteSnapshotsOption">Delete snapshots option</param>
 /// <param name="accessCondition">Access condition</param>
 /// <param name="operationContext">Operation context</param>
 /// <returns>An enumerable collection of CloudBlob</returns>
 public void DeleteCloudBlob(CloudBlob blob, DeleteSnapshotsOption deleteSnapshotsOption, AccessCondition accessCondition, BlobRequestOptions options, XSCL.OperationContext operationContext)
 {
     try
     {
         Task.Run(() => blob.DeleteAsync(deleteSnapshotsOption, accessCondition, options, operationContext)).Wait();
     }
     catch (AggregateException e) when(e.InnerException is XSCL.StorageException)
     {
         throw e.InnerException;
     }
 }
Esempio n. 18
0
        private async static Task <bool> RunAzCopyAsync(CloudBlob blob)
        {
            //setup
            processedBytes += blob.Properties.Length;
            await blob.FetchAttributesAsync();

            //download
            ShowDownloadInfo(blob, currentBlobIndex++);
            var downloadCommand = $"{azCopyPath} cp \"{blob.Uri}{srcSAS}\" \"{localTempPath}\\{blob.Name}\"";

            ExecuteAzCommand(downloadCommand);
            //Append2Log($"Downloaded {blob.Uri.AbsoluteUri}");

            //upload
            var destUrl = $"{destStorageAccount.BlobEndpoint.AbsoluteUri}{destContainerName}/{blob.Name}";
            var message = $"Uploading {destTier} block blob to {destUrl}...";

            Console.WriteLine(message);
            // Append2Log(message);
            var filePath      = $"{ localTempPath }\\{ blob.Name}";
            var uploadCommand = $"{azCopyPath} cp {filePath} \"{destUrl}{destSAS}\" --block-blob-tier {destTier}";

            ExecuteAzCommand(uploadCommand);
            //Append2Log($"Uploaded {destUrl}. Total processed: {processedBytes / MB_FACTOR}mb");


            //delete
            if (deleteFromSource)
            {
                bool safe2Delete = !safeDeleteFromSource;
                if (safeDeleteFromSource)
                {
                    if (!(safe2Delete = destContainer.GetBlobReference(blob.Name).ExistsAsync().Result))
                    {
                        Console.WriteLine($"{blob.Uri} will not be deleted from source, because it is not yet in the destination");
                    }
                }
                if (safe2Delete)
                {
                    Console.WriteLine($"{blob.Uri} will be deleted from source");
                    _ = blob.DeleteAsync();
                }
            }
            if (deleteFromLocalTemp)
            {
                File.Delete(filePath);
            }


            //finish current blob processing
            Console.WriteLine(".............................................................................");
            return(true);
        }
Esempio n. 19
0
        public async Task <bool> DeleteFile(string fileName, string containerName)
        {
            try
            {
                var           member = User.Identity.Name;
                MemberLicense ml     = this.iMemberLicenseRepository.MyLicense(member);
                // if (CloudStorageAccount.TryParse(config.Value.StorageConnection, out CloudStorageAccount storageAccount))
                if (CloudStorageAccount.TryParse(ml?.AzureSaConnectionString, out CloudStorageAccount storageAccount))
                {
                    CloudBlobClient    BlobClient = storageAccount.CreateCloudBlobClient();
                    CloudBlobContainer container  = BlobClient.GetContainerReference(containerName);

                    if (await container.ExistsAsync())
                    {
                        CloudBlob file = container.GetBlobReference(fileName);

                        if (await file.ExistsAsync())
                        {
                            await file.DeleteAsync();

                            //Decrease used storage
                            MemberLicenseUsedStorage mlus = this.iMemberLicenseRepository.GetUsedStorage(ml.LicenseId);
                            await container.FetchAttributesAsync();

                            // await file.FetchAttributesAsync();

                            mlus.AzureSaUsedSizeInBytes = long.Parse(BigInteger.Subtract(mlus.AzureSaUsedSizeInBytes, file.Properties.Length).ToString());


                            if (mlus.AzureSaUsedSizeInBytes < 0)
                            {
                                mlus.AzureSaUsedSizeInBytes = 0;
                            }

                            this.iMemberLicenseRepository.UpdateUsedStorage(mlus);
                            // End of Decrease Used Storage Size

                            return(true);
                        }
                    }
                }
                else
                {
                    return(false);
                }
            }
            catch
            {
                return(false);
            }
            return(true);
        }
 internal static async Task DeleteBlobAsync(this CloudBlob blob)
 {
     try
     {
         if (await blob.ExistsAsync())
         {
             await blob.DeleteAsync();
         }
     }
     catch (Exception e)
     {
         Console.WriteLine($"Can not delete blob: {blob.Name}. Reason:{e.Message}");
     }
 }
        /// <summary>
        /// Forcefully deletes a blob.
        /// </summary>
        /// <param name="blob">The CloudBlob to delete.</param>
        /// <returns>A task that completes when the operation is finished.</returns>
        public static async Task <bool> ForceDeleteAsync(CloudBlob blob)
        {
            try
            {
                await blob.DeleteAsync();

                return(true);
            }
            catch (StorageException e) when(BlobDoesNotExist(e))
            {
                return(false);
            }
            catch (StorageException e) when(CannotDeleteBlobWithLease(e))
            {
                try
                {
                    await blob.BreakLeaseAsync(TimeSpan.Zero).ConfigureAwait(false);
                }
                catch
                {
                    // we ignore exceptions in the lease breaking since there could be races
                }

                // retry the delete
                try
                {
                    await blob.DeleteAsync().ConfigureAwait(false);

                    return(true);
                }
                catch (StorageException ex) when(BlobDoesNotExist(ex))
                {
                    return(false);
                }
            }
        }
        /// <summary>
        /// Copies the BLOB and removes the original one.
        /// </summary>
        /// <param name="sourceBlob">Source Cloud BLOB</param>
        /// <param name="targetBlob">Target Cloud BLOB</param>
        /// <param name="cancellation">Cancellation token</param>
        /// <returns>A <see cref="Task"/> that represents asynchronous copy operation.</returns>
        private async Task RenameBlob(CloudBlob sourceBlob, CloudBlob targetBlob, CancellationToken cancellation)
        {
            await targetBlob.StartCopyAsync(sourceBlob.Uri, cancellation);

            while (targetBlob.CopyState.Status == CopyStatus.Pending)
            {
                await Task.Delay(250);
            }

            if (targetBlob.CopyState.Status != CopyStatus.Success)
            {
                throw Errors.BlobCopyFailed(targetBlob.CopyState.Status, targetBlob.CopyState.StatusDescription);
            }

            await sourceBlob.DeleteAsync(cancellation);
        }
Esempio n. 23
0
        public override async Task <bool> DeleteFile(FlatFile file, EFlatFilePath path, string fileName)
        {
            try
            {
                var cloudFileDirectory = await GetFileDirectory(file);

                var       cloudSubDirectory = cloudFileDirectory.GetDirectoryReference(file.GetPath(path));
                CloudBlob cloudFile         = cloudSubDirectory.GetBlockBlobReference(fileName);
                await cloudFile.DeleteAsync();

                return(true);
            }
            catch (Exception ex)
            {
                throw new ConnectionException($"Failed to delete file {file.Name} filename {Filename} from {path}.  {ex.Message}", ex);
            }
        }
        /// <summary>
        /// Deletes the specified blob.
        /// </summary>
        /// <param name="blobPath"></param>
        /// <returns>Returns true if the blob has been deleted or false if the blob did not exist.</returns>
        public async Task <bool> DeleteBlobAsync(string blobPath)
        {
            CloudBlobClient blobClient = m_LazyBlobClient.Value;
            var             blob       = new CloudBlob(GetAbsoluteBlobUri(blobPath), blobClient.Credentials);

            try
            {
                await blob.DeleteAsync();

                return(true);
            }
            catch (StorageException ex) when(ex.RequestInformation.ErrorCode == BlobErrorCodeStrings.BlobNotFound)
            {
                //swallow blob not found to ease delete operations
                return(false);
            }
        }
Esempio n. 25
0
        public async Task ProcessMessage(
            [QueueTrigger("requests-v1")] string message,
            ILogger logger)
        {
            var blobClient = _storageProvider.Get(null).CreateCloudBlobClient();
            var blob       = new CloudBlob(new Uri(message), blobClient);

            HttpRequestMessage request;

            using (var stream = await blob.OpenReadAsync())
                request = await RequestSerialization.Deserialize(stream);

            HttpResponseMessage response;

            using (var client = _httpClientFactory.CreateClient())
                response = await client.SendAsync(request);

            logger.LogInformation(
                (int)response.StatusCode + " " +
                request.Method + " " +
                request.RequestUri);

            if (!response.IsSuccessStatusCode)
            {
                throw new ApplicationException(
                          request.Method + " " +
                          request.RequestUri + " failed with status code " +
                          (int)response.StatusCode);
            }

            try
            {
                await blob.DeleteAsync();
            }
            catch (Exception e)
            {
                logger.LogWarning(e, "Failed to delete blob");
            }
        }
Esempio n. 26
0
        public async Task <bool> deleteImg(string fileName)
        {
            try
            {
                CloudBlobClient    BlobClient = acc.CreateCloudBlobClient();
                CloudBlobContainer container  = BlobClient.GetContainerReference(Container);

                if (await container.ExistsAsync())
                {
                    CloudBlob file = container.GetBlobReference(fileName);

                    if (await file.ExistsAsync())
                    {
                        await file.DeleteAsync();
                    }
                }

                return(true);
            }
            catch (Exception ex)
            {
                return(false);
            }
        }
Esempio n. 27
0
 public static void Delete(this CloudBlob blob)
 {
     blob.DeleteAsync().Wait();
 }
 /// <summary>
 /// Return a task that asynchronously delete the specified blob
 /// </summary>
 /// <param name="blob">CloudBlob object</param>
 /// <param name="deleteSnapshotsOption">Snapshot delete option</param>
 /// <param name="accessCondition">Access condition</param>
 /// <param name="requestOptions">Blob request option</param>
 /// <param name="operationContext">Operation context</param>
 /// <param name="cmdletCancellationToken">Cancellation token</param>
 /// <returns>Return a task that asynchronously delete the specified blob</returns>
 public Task DeleteCloudBlobAsync(CloudBlob blob, DeleteSnapshotsOption deleteSnapshotsOption, AccessCondition accessCondition, BlobRequestOptions requestOptions, XSCL.OperationContext operationContext, CancellationToken cancellationToken)
 {
     return(blob.DeleteAsync(deleteSnapshotsOption, accessCondition, requestOptions, operationContext, cancellationToken));
 }
 async Task RemoveFileAsync(CloudBlob blob)
 {
     await blob.DeleteAsync();
 }
Esempio n. 30
0
 public static void Delete(this CloudBlob blob, DeleteSnapshotsOption deleteSnapshotsOption = DeleteSnapshotsOption.None, AccessCondition accessCondition = null, BlobRequestOptions options = null, OperationContext operationContext = null)
 {
     blob.DeleteAsync(deleteSnapshotsOption, accessCondition, options, operationContext).GetAwaiter().GetResult();
 }