public static async Task <int> SendToAzure(AzureOptions opts)
        {
            CloudBlockBlob zipSnapshot = null;
            CloudBlockBlob zipBlob     = null;

            try
            {
                var zipFile = CreateZipFile(opts.Source, opts);

                Console.WriteLine("Upload zip file.");
                var storageCredentials  = new StorageCredentials(opts.AccountName, opts.AccountKey);
                var cloudStorageAccount = new CloudStorageAccount(storageCredentials, true);
                var cloudBlobClient     = cloudStorageAccount.CreateCloudBlobClient();

                var container = cloudBlobClient.GetContainerReference(opts.ContainerName);
                await container.CreateIfNotExistsAsync();

                zipBlob = container.GetBlockBlobReference(opts.Destination + "/software.zip");

                if (await zipBlob.ExistsAsync())
                {
                    zipSnapshot = await zipBlob.CreateSnapshotAsync();
                }
                await zipBlob.UploadFromFileAsync(zipFile);

                Console.WriteLine("Update version.");
                var xmlBlob = container.GetBlockBlobReference(opts.Destination + "/software.xml");

                var doc = CreateOrUpdateVersionFile(
                    (await xmlBlob.ExistsAsync()) ? XDocument.Parse(await xmlBlob.DownloadTextAsync()) : null,
                    zipFile,
                    opts
                    );

                //if (await xmlBlob.ExistsAsync())
                //	await xmlBlob.CreateSnapshotAsync();
                await xmlBlob.UploadTextAsync(doc.ToString());

                await zipSnapshot?.DeleteAsync();

                File.Delete(zipFile);

                return(0);
            }
            catch (Exception ex)
            {
                if (zipBlob != null && zipSnapshot != null)
                {
                    await zipBlob.StartCopyAsync(zipSnapshot);

                    await zipSnapshot.DeleteAsync();
                }
                Console.WriteLine(ex.Message);
                return(1);
            }
        }
 public async Task DeleteAsync()
 {
     try
     {
         await _Blob.DeleteAsync().ConfigureAwait(false);
     }
     catch (StorageException ex)
     {
         if (ex.RequestInformation != null && ex.RequestInformation.HttpStatusCode == 404)
         {
             return;
         }
         throw;
     }
 }
Beispiel #3
0
        public async Task DeleteBlob(string blobName)
        {
            CloudBlobContainer container = this.GetCloudBlobContainer();

            CloudBlockBlob blockBlob = container.GetBlockBlobReference(blobName);

            try
            {
                await blockBlob.DeleteAsync();
            }
            catch (StorageException)
            {
                throw new AzureXStoreException("The blob is not in the database.");
            }
        }
        public async Task <bool> DeleteContent(string key)
        {
            try
            {
                blockBlob = blobContainer.GetBlockBlobReference(key);
                await blockBlob.DeleteAsync();

                return(true);
            }
            catch (Exception)
            {
                //TODO: Logs an error
            }
            return(false);
        }
Beispiel #5
0
        public async Task DeleteImageFromStorageAsync(string pointId)
        {
            try
            {
                StringBuilder fileName = new StringBuilder(pointId);
                fileName.Append(SignatureConstants.JPG);
                CloudBlockBlob cloudBlockBlob = cloudBlobContainer.GetBlockBlobReference(fileName.ToString());

                await cloudBlockBlob.DeleteAsync();
            }
            catch (Exception ex)
            {
                throw (ex);
            }
        }
Beispiel #6
0
        public async static Task DeleteImagesAsync(
            [QueueTrigger("deleterequest")] BlobInfo blobInfo,
            [Blob(BlobInfo.ImageNameLg)] CloudBlockBlob blobLarge,
            [Blob(BlobInfo.ImageNameXs)] CloudBlockBlob blobExtraSmall,
            [Blob(BlobInfo.ImageNameSm)] CloudBlockBlob blobSmall,
            [Blob(BlobInfo.ImageNameMd)] CloudBlockBlob blobMedium)
        {
            await blobExtraSmall.DeleteAsync();

            await blobSmall.DeleteAsync();

            await blobMedium.DeleteAsync();

            await blobLarge.DeleteAsync();
        }
        // Deletes file(s) or folder(s)
        protected async Task <FileManagerResponse> RemoveAsync(string[] names, string path, params FileManagerDirectoryContent[] selectedItems)
        {
            FileManagerResponse removeResponse          = new FileManagerResponse();
            List <FileManagerDirectoryContent> details  = new List <FileManagerDirectoryContent>();
            CloudBlobDirectory          directory       = (CloudBlobDirectory)item;
            FileManagerDirectoryContent entry           = new FileManagerDirectoryContent();
            CloudBlobDirectory          sampleDirectory = container.GetDirectoryReference(path);

            foreach (FileManagerDirectoryContent FileItem in selectedItems)
            {
                if (FileItem.IsFile)
                {
                    path = this.FilesPath.Replace(this.BlobPath, "") + FileItem.FilterPath;
                    CloudBlockBlob blockBlob = container.GetBlockBlobReference(path + FileItem.Name);
                    await blockBlob.DeleteAsync();

                    entry.Name       = FileItem.Name;
                    entry.Type       = FileItem.Type;
                    entry.IsFile     = FileItem.IsFile;
                    entry.Size       = FileItem.Size;
                    entry.HasChild   = FileItem.HasChild;
                    entry.FilterPath = path;
                    details.Add(entry);
                }
                else
                {
                    path = this.FilesPath.Replace(this.BlobPath, "") + FileItem.FilterPath;
                    CloudBlobDirectory subDirectory = container.GetDirectoryReference(path + FileItem.Name);
                    BlobResultSegment  items        = await AsyncReadCall(path + FileItem.Name, "Remove");

                    foreach (IListBlobItem item in items.Results)
                    {
                        CloudBlockBlob blockBlob = container.GetBlockBlobReference(path + FileItem.Name + "/" + item.Uri.ToString().Replace(subDirectory.Uri.ToString(), ""));
                        await blockBlob.DeleteAsync();

                        entry.Name       = FileItem.Name;
                        entry.Type       = FileItem.Type;
                        entry.IsFile     = FileItem.IsFile;
                        entry.Size       = FileItem.Size;
                        entry.HasChild   = FileItem.HasChild;
                        entry.FilterPath = path;
                        details.Add(entry);
                    }
                }
            }
            removeResponse.Files = (IEnumerable <FileManagerDirectoryContent>)details;
            return(removeResponse);
        }
Beispiel #8
0
        private async Task CloneAsync(ITemplatesProvider sourceProvider, string path, IEnumerable <ITemplateItem> items, Action <string> log)
        {
            HashSet <ITemplateItem> existingItems = new HashSet <ITemplateItem>(await GetAsync(path, log));

            // Add or update the items
            foreach (ITemplateItem item in items)
            {
                log?.Invoke($"Cloning: {item.Path}");

                // Mark as done
                if (!existingItems.Remove(item))
                {
                    existingItems.RemoveWhere(i => i.Path == System.Uri.EscapeUriString(item.Path));
                }

                if (item is ITemplateFolder folder)
                {
                    // Get the children and clone the entire folder
                    IEnumerable <ITemplateItem> folderItems = await sourceProvider.GetAsync(folder.Path, log);
                    await CloneAsync(sourceProvider, folder.Path, folderItems, log);
                }
                else if (item is ITemplateFile file)
                {
                    using (Stream sourceStream = await file.DownloadAsync())
                    {
                        CloudBlockBlob blob = _container.GetBlockBlobReference(item.Path);
                        await blob.UploadFromStreamAsync(sourceStream);
                    }
                }
            }

            // Remove any additional item
            foreach (ITemplateItem item in existingItems)
            {
                log?.Invoke($"Removing: {item.Path}");

                if (item is ITemplateFolder folder)
                {
                    // To remove a directory we need to iterate through children
                    await DeleteDirectoryAsync(item.Path, log);
                }
                else if (item is ITemplateFile file)
                {
                    CloudBlockBlob blob = _container.GetBlockBlobReference(System.Uri.UnescapeDataString(item.Path));
                    await blob.DeleteAsync();
                }
            }
        }
Beispiel #9
0
        private async Task <bool> AzureDelete(string key)
        {
            try
            {
                CloudBlockBlob   blockBlob = _AzureContainer.GetBlockBlobReference(key);
                OperationContext ctx       = new OperationContext();
                await blockBlob.DeleteAsync(DeleteSnapshotsOption.None, null, null, ctx);

                int statusCode = ctx.LastResult.HttpStatusCode;
                return(true);
            }
            catch (Exception)
            {
                return(false);
            }
        }
        public async Task <IActionResult> DeleteConfirmed(int id)
        {
            var Flower = await _context.Flower.FindAsync(id);

            CloudBlobContainer container = GetCloudBlobContainer();

            if (Flower.ImageRef != null)
            {
                CloudBlockBlob blob = container.GetBlockBlobReference(Flower.ImageRef);
                blob.DeleteAsync().Wait();
            }
            _context.Flower.Remove(Flower);
            await _context.SaveChangesAsync();

            return(RedirectToAction(nameof(Index)));
        }
Beispiel #11
0
        public async void DeleteBlobData(string fileUrl)
        {
            Uri    uriObj   = new Uri(fileUrl);
            string BlobName = Path.GetFileName(uriObj.LocalPath);

            CloudBlobContainer cloudBlobContainer =
                GetBlobContainer(_accessKey, _defaultContainerName);

            string             pathPrefix    = DateTime.Now.ToUniversalTime().ToString("yyyy-MM-dd") + "/";
            CloudBlobDirectory blobDirectory = cloudBlobContainer.GetDirectoryReference(pathPrefix);
            // get block blob
            CloudBlockBlob blockBlob = blobDirectory.GetBlockBlobReference(BlobName);

            // delete blob from container
            await blockBlob.DeleteAsync();
        }
Beispiel #12
0
 public async Task DeleteImage(string imageId)
 {
     try
     {
         CloudBlockBlob cloudBlockBlob = _profilePicturesContainer.GetBlockBlobReference(imageId);
         if (!await cloudBlockBlob.ExistsAsync())
         {
             throw new ProfilePictureNotFoundException("Profile Picture not found");
         }
         await cloudBlockBlob.DeleteAsync();
     }
     catch (StorageException e)
     {
         throw new StorageException("Could not delete from blob", e);
     }
 }
        public static async Task Run(
            [QueueTrigger(QueueName.RenderPage)] RenderPage command,

            [Blob(ContainerName.PageTemplate + "/{" + nameof(RenderPage.TemplateId) + "}", FileAccess.Read)] CloudBlockBlob pageTemplateBlob,
            [Blob(ContainerName.PageData + "/{" + nameof(RenderPage.DataInstanceId) + "}", FileAccess.ReadWrite)] CloudBlockBlob pageDataBlob,

            [Blob(ContainerName.WebHost + "/{" + nameof(RenderPage.PublicUrl) + "}", FileAccess.Write)] CloudBlockBlob pageHtmlBlob,
            [Queue(QueueName.CopyBlob)] CloudQueue copyQueue,

            ILogger log)
        {
            log.LogInformation(JsonConvert.SerializeObject(command));

            var copyQueueService = new CommandQueueService(copyQueue);

            var pageData     = JsonConvert.DeserializeObject(await pageDataBlob.DownloadTextAsync());
            var pageTemplate = await pageTemplateBlob.DownloadTextAsync();

            var html = Render.StringToString(pageTemplate, pageData, new RenderContextBehaviour
            {
                HtmlEncoder = text => text
            });

            var compressor = new HtmlCompressor();

            compressor.setEnabled(true);
            compressor.setRemoveComments(true);
            compressor.setRemoveMultiSpaces(true);
            compressor.setRemoveIntertagSpaces(true);

            html = compressor.compress(html);

            await pageHtmlBlob.UploadTextAsync(html);

            pageHtmlBlob.Properties.ContentType = "text/html";
            await pageHtmlBlob.SetPropertiesAsync();

            var copyCommand = new CopyBlob
            {
                Path = command.PublicUrl
            };

            await Task.WhenAll(
                pageDataBlob.DeleteAsync(),
                copyQueueService.SubmitCommandAsync(copyCommand)
                );
        }
Beispiel #14
0
        public IActionResult DeleteFileNow(string fileName, int BlogPostId)
        {
            var storageAccount = CloudStorageAccount.Parse("DefaultEndpointsProtocol=https;AccountName=blogster;AccountKey=2pvh1PnvLjjAj8BG1fKfI05YQs49r0Vpo4Qv7HDVrUhwRY0w5jHVXKvQYUqgRLRDfuyIiyEi9qCTjvWGk1/RNA==");

            CloudBlobClient    blobClient = storageAccount.CreateCloudBlobClient();
            CloudBlobContainer container  = blobClient.GetContainerReference("imageblogs");
            CloudBlockBlob     blockBlob  = container.GetBlockBlobReference(fileName);

            blockBlob.DeleteAsync();

            var fileToDelete = (from f in _blogsterDataContext.Photos where (f.Filename == fileName & f.BlogPostId == BlogPostId) select f).FirstOrDefault();

            _blogsterDataContext.Remove(fileToDelete);
            _blogsterDataContext.SaveChanges();

            return(RedirectToAction("Index"));
        }
Beispiel #15
0
        public void DeleteFromBlob(string filename)
        {
            // Retrieve storage account from connection string.
            CloudStorageAccount storageAccount = CloudStorageAccount.Parse("DefaultEndpointsProtocol=https;AccountName=datossensores;AccountKey=x7W/PW86xtAuEJv+aOwyIYiG1dHC0+8EX3GP2ktC39B94ppau5PodjNvf+3NXsoG5/On6kJIQ9T2EtM5+HtAXA==");

            // Create the blob client.
            CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();

            // Retrieve reference to a previously created container.
            CloudBlobContainer container = blobClient.GetContainerReference("imagenaparatos");

            // Retrieve reference to a blob named "myblob.csv".
            CloudBlockBlob blockBlob = container.GetBlockBlobReference(filename);

            // Delete the blob.
            blockBlob.DeleteAsync();
        }
        public async void DeleteBlobData(string fileUrl)
        {
            Uri    relativeUri = new Uri(fileUrl, UriKind.Relative);
            string BlobName    = Path.GetFileName(relativeUri.ToString());

            // Parse the storage account access key
            CloudStorageAccount cloudStorageAccount = CloudStorageAccount.Parse(_settings.ConnectionString);
            CloudBlobClient     cloudBlobClient     = cloudStorageAccount.CreateCloudBlobClient();
            string strContainerName = _settings.BlobStorageContainer;
            // Get reference to blob container
            CloudBlobContainer cloudBlobContainer = cloudBlobClient.GetContainerReference(strContainerName);
            CloudBlobDirectory blobDirectory      = cloudBlobContainer.GetDirectoryReference("");
            // Get reference to blob
            CloudBlockBlob blockBlob = blobDirectory.GetBlockBlobReference(fileUrl);
            //Delete blob from container
            await blockBlob.DeleteAsync();
        }
Beispiel #17
0
        public async Task DeletePostByIdAsync(string postId, CancellationToken cancellationToken = default)
        {
            CloudBlockBlob blob = _postsContainer.GetBlockBlobReference(GetPostBlobName(postId));

            if (await blob.ExistsAsync(null, null, cancellationToken))
            {
                await blob.DeleteAsync(DeleteSnapshotsOption.None,
                                       null,
                                       null,
                                       null,
                                       cancellationToken);
            }

            await _cacheService.RemoveAsync <Post>(postId, cancellationToken);

            await UpdatePostCategoriesAsync(new PostBase { Id = postId }, true, cancellationToken);
        }
        public static async Task Run([TimerTrigger("0 */5 * * * *")] TimerInfo myTimer, ILogger log)
        {
            string output         = string.Empty;
            var    inputcontainer = client.GetContainerReference("liquid-transforms-input");
            var    blobs          = GetBlobs(inputcontainer).Result;

            foreach (var item in blobs)
            {
                CloudBlockBlob inputblob = inputcontainer.GetBlockBlobReference(item.Name);
                string         inputxml  = await inputblob.DownloadTextAsync();

                output = await GetTransformedxml(inputxml);
                await UploadBlob(output, item.Name);

                await inputblob.DeleteAsync();
            }
        }
Beispiel #19
0
        public bool DeleteBlob(string url)
        {
            bool check;

            try
            {
                Uri            uri  = new Uri(url);
                CloudBlockBlob blob = new CloudBlockBlob(uri);
                blob.DeleteAsync();
                check = blob.IsDeleted;
            }
            catch (Exception)
            {
                throw;
            }
            return(check);
        }
Beispiel #20
0
        public async Task DeleteFile(string shareName, string folder, string fileName)
        {
            try
            {
                CloudBlockBlob cloudBlockBlob = await this.GetBlobReference(folder, fileName);

                await cloudBlockBlob.DeleteAsync();
            }
            catch (StorageException exStorage)
            {
                this.ErrorMessage = exStorage.ToString();
            }
            catch (Exception ex)
            {
                this.ErrorMessage = ex.ToString();
            }
        }
        /// <summary>
        /// Waits for all expected blocks to finish uploading, commits the blob, then deletes the blob and container used during the test.
        /// </summary>
        /// <remarks>This method will only be called if application is running as ID 0.</remarks>
        /// <param name="container">The blob's container.</param>
        /// <param name="blobName">The name of the blob being uploaded.</param>
        /// <param name="totalBlocks">The total number of blocks to commit to the blob.</param>
        private static async Task FinalizeBlob(CloudBlobContainer container, string blobName, uint totalBlocks, bool cleanup)
        {
            // Define the order in which to commit blocks.
            List <string> blockIdList = new List <string>();

            for (uint i = 0; i < totalBlocks; ++i)
            {
                blockIdList.Add(Convert.ToBase64String(BitConverter.GetBytes(i)));
            }
            HashSet <string> blockIdSet = new HashSet <string>(blockIdList);

            CloudBlockBlob blockblob = container.GetBlockBlobReference(blobName);

            // Poll the blob's Uncommitted Block List until we determine that all expected blocks have been successfully uploaded.
            Console.WriteLine("Waiting for all expected blocks to appear in the uncommitted block list.");
            IEnumerable <ListBlockItem> currentUncommittedBlockList = new List <ListBlockItem>();

            while (true)
            {
                currentUncommittedBlockList = await blockblob.DownloadBlockListAsync(BlockListingFilter.Uncommitted, AccessCondition.GenerateEmptyCondition(), null, null);

                if (currentUncommittedBlockList.Count() >= blockIdList.Count &&
                    VerifyBlocks(currentUncommittedBlockList, blockIdSet))
                {
                    break;
                }
                Console.WriteLine($"{currentUncommittedBlockList.Count()} / {blockIdList.Count} blocks in the uncommitted block list.");
                await Task.Delay(TimeSpan.FromSeconds(5));
            }

            Console.WriteLine("Issuing PutBlockList.");
            await blockblob.PutBlockListAsync(blockIdList);

            if (cleanup)
            {
                Console.WriteLine("Press 'Enter' key to delete the example container and blob.");
                Console.ReadLine();

                Console.WriteLine("Issuing DeleteBlob.");
                await blockblob.DeleteAsync();

                Console.WriteLine("Deleting container.");
                await container.DeleteAsync();
            }
        }
Beispiel #22
0
        /// <summary>
        /// Adds a file to the user's tenant container in the repository.  An owner file permission record is also created allowing all WOPI operations.
        /// </summary>
        /// <param name="userId">UserID of the file owner</param>
        /// <param name="stream">Stream containing file contents</param>
        /// <param name="fileName">Name of file with extension</param>
        /// <returns>Returns a string with unique FileID identifier, which is unique across the repository</returns>
        public async Task <WopiFile> AddFile(string userId, string tenant, Stream stream, string fileName)
        {
            var            fileId    = Guid.NewGuid().ToString();
            CloudBlockBlob blockBlob = null;

            try
            {
                using (var wopiContext = new WopiContext())
                {
                    var existingFiles = await wopiContext.Files.Where(f => f.FileName == fileName && f.Container == tenant).ToListAsync();

                    var storageAccount = CloudStorageAccount.Parse(CloudConfigurationManager.GetSetting("StorageConnectionString"));
                    var blobClient     = storageAccount.CreateCloudBlobClient();
                    var containerName  = tenant.ToLower(); // blob containers must be lowercase
                    var container      = blobClient.GetContainerReference(containerName);
                    await container.CreateIfNotExistsAsync();

                    blockBlob = container.GetBlockBlobReference(fileId);
                    await blockBlob.UploadFromStreamAsync(stream);

                    int newVersion = 1;

                    if (existingFiles.Count() > 0)
                    {
                        var versions   = existingFiles.Select(file => file.Version);
                        var maxVersion = versions.Max();
                        newVersion = maxVersion + 1;
                    }

                    var wopiFile = CreateOwnerRecords(fileName, userId, blockBlob, newVersion);
                    wopiContext.Files.Add(wopiFile);
                    await wopiContext.SaveChangesAsync();

                    return(wopiFile);
                }
            }
            catch (Exception ex)
            {
                if (blockBlob != null && await blockBlob.ExistsAsync())
                {
                    await blockBlob.DeleteAsync();
                }
                throw;
            }
        }
Beispiel #23
0
        public async void DeleteBlobData(string fileUrl)
        {
            Uri    uriObj   = new Uri(fileUrl);
            string BlobName = Path.GetFileName(uriObj.LocalPath);

            CloudStorageAccount cloudStorageAccount = CloudStorageAccount.Parse(accessKey);
            CloudBlobClient     cloudBlobClient     = cloudStorageAccount.CreateCloudBlobClient();
            string             strContainerName     = "fileconatiner";
            CloudBlobContainer cloudBlobContainer   = cloudBlobClient.GetContainerReference(strContainerName);

            string             pathPrefix    = DateTime.Now.ToUniversalTime().ToString("yyyy-MM-dd") + "/";
            CloudBlobDirectory blobDirectory = cloudBlobContainer.GetDirectoryReference(pathPrefix);
            // get block blob refarence
            CloudBlockBlob blockBlob = blobDirectory.GetBlockBlobReference(BlobName);

            // delete blob from container
            await blockBlob.DeleteAsync();
        }
Beispiel #24
0
        public async Task DeleteFileFromBlobAsync(string ContainerName, string ResourceName)
        {
            try
            {
                //1) Get Blob Container Reference
                CloudBlobContainer blobContainer = _cloudBlobClient.GetContainerReference(ContainerName);

                //2) Get Resource Reference
                CloudBlockBlob _blockBlob = blobContainer.GetBlockBlobReference(ResourceName);

                //3) Delete resource from Blob Container
                await _blockBlob.DeleteAsync();
            }
            catch (Exception)
            {
                throw;
            }
        }
Beispiel #25
0
        public async Task DeleteDocAsync(string filename)
        {
            var strorageconn = _appSettings.AzureDataStorageConnection;
            CloudStorageAccount storageacc = CloudStorageAccount.Parse(strorageconn);

            //Create Reference to Azure Blob
            CloudBlobClient blobClient = storageacc.CreateCloudBlobClient();

            //The next 2 lines create if not exists a container named "democontainer"
            CloudBlobContainer container = blobClient.GetContainerReference("quotes");

            await container.CreateIfNotExistsAsync();

            //The next 7 lines upload the file test.txt with the name DemoBlob on the container "democontainer"
            CloudBlockBlob blockBlob = container.GetBlockBlobReference(filename);

            await blockBlob.DeleteAsync();
        }
Beispiel #26
0
        static async Task DeleteBlob(CloudBlobContainer blobContainer, string blobName)
        {
            // Get Blob reference using the container reference previously created
            CloudBlockBlob blockBlob = blobContainer.GetBlockBlobReference(blobName);

            try
            {
                // Delete Blob
                await blockBlob.DeleteAsync();

                Console.WriteLine("Blob {0} deleted successfully from container {1}", blobName, blobContainer.Name);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            Console.WriteLine();
        }
        public async void DeleteBlob()
        {
            // Retrieve storage account from connection string.
            CloudStorageAccount storageAccount = CloudStorageAccount.Parse(
                CloudConfigurationManager.GetSetting("StorageConnectionString"));

            // Create the blob client.
            CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();

            // Retrieve reference to a previously created container.
            CloudBlobContainer container = blobClient.GetContainerReference("mycontainer");

            // Retrieve reference to a blob named "myblob.txt".
            CloudBlockBlob blockBlob = container.GetBlockBlobReference("myblob.txt");

            // Delete the blob.
            await blockBlob.DeleteAsync();
        }
Beispiel #28
0
        public async Task DeleteBlobStorageAsync(string url)
        {
            try
            {
                //  get the container reference
                var container = GetImagesBlobContainer();

                var blobName = url.Split('/').Last();
                // using the container reference, get a block blob reference and set its type
                CloudBlockBlob blockBlob = container.GetBlockBlobReference($"{_petPicturesBlobName}/{blobName}");

                // finally, upload the image into blob storage using the block blob reference
                await blockBlob.DeleteAsync();
            }
            catch (Exception)
            {
            }
        }
Beispiel #29
0
        public static async Task <bool> DeleteBlobAsync(string fileName)
        {
            try
            {
                CloudStorageAccount cloudStorageAccount = CloudStorageAccount.Parse(connectionString);
                CloudBlobClient     _blobClient         = cloudStorageAccount.CreateCloudBlobClient();
                CloudBlobContainer  _cloudBlobContainer = _blobClient.GetContainerReference(containerName);
                CloudBlockBlob      _blockBlob          = _cloudBlobContainer.GetBlockBlobReference(fileName);
                //delete file from container
                await _blockBlob.DeleteAsync();

                return(true);
            }
            catch (Exception ex)
            {
                return(false);
            }
        }
Beispiel #30
0
        /// <summary>
        /// Basic operations to work with block blobs
        /// </summary>
        /// <returns>Task<returns>
        private static async Task BasicStorageBlockBlobOperations()
        {
            const string ImageToUpload = "HelloWorld.png";

            // Retrieve storage account information from connection string
            // How to create a storage connection string - http://msdn.microsoft.com/en-us/library/azure/ee758697.aspx
            CloudStorageAccount storageAccount = storageAccount = CloudStorageAccount.Parse(CloudConfigurationManager.GetSetting("StorageConnectionString"));

            // Create a blob client for interacting with the blob service.
            CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();

            // Create a container for organizing blobs within the storage account.
            Console.WriteLine("1. Creating Container");
            CloudBlobContainer container = blobClient.GetContainerReference("democontainerblockblob");
            await container.CreateIfNotExistsAsync();

            // To view the uploaded blob in a browser, you need to set permissions to allow public access to blobs in this container.
            // Then you can view the image using: https://[InsertYourStorageAccountNameHere].blob.core.windows.net/democontainer/HelloWorld.png
            // await container.SetPermissionsAsync(new BlobContainerPermissions { PublicAccess = BlobContainerPublicAccessType.Blob });

            // Upload a BlockBlob to the newly creating container
            Console.WriteLine("2. Uploading BlockBlob");
            CloudBlockBlob blockBlob = container.GetBlockBlobReference(ImageToUpload);
            await blockBlob.UploadFromFileAsync(ImageToUpload, FileMode.Open);

            // List all the blobs in the container
            Console.WriteLine("3. List Blobs in Container");
            foreach (IListBlobItem blob in container.ListBlobs())
            {
                // Blob type will be CloudBlockBlob, CloudPageBlob or CloudBlobDirectory
                // Use blob.GetType() and cast to appropriate type to gain access to properties specific to each type
                Console.WriteLine("- {0} (type: {1})\n", blob.Uri, blob.GetType());
            }

            // Download a blob to your file system
            Console.WriteLine("4. Download Blob from {0}", blockBlob.Uri.AbsoluteUri);
            await blockBlob.DownloadToFileAsync(string.Format("./CopyOf{0}", ImageToUpload), FileMode.Create);

            // Clean up after the demo
            Console.WriteLine("5. Delete blok Blob and container");
            await blockBlob.DeleteAsync();

            await container.DeleteAsync();
        }