/// <summary> /// The upload media to azure. /// </summary> /// <param name="mediaItem"> /// The media item. /// </param> /// <param name="extension"> /// The extension. /// </param> /// <param name="language"> /// The language. /// </param> public void UploadMediaToAzure(MediaItem mediaItem, string extension = "", string language = "") { CloudBlockBlob blockBlob = this.container.GetBlockBlobReference(this.GetMediaPath(mediaItem, extension)); blockBlob.DeleteIfExists(); if (string.IsNullOrEmpty(mediaItem.Extension)) { return; } if (mediaItem.HasMediaStream("Media")) { using (var fileStream = (System.IO.FileStream)mediaItem.GetMediaStream()) { blockBlob.Properties.ContentType = mediaItem.MimeType; blockBlob.UploadFromStream(fileStream); this.SetCacheControl(blockBlob, "public,max-age=691200"); } } else { blockBlob.DeleteIfExists(); } this.logger.Info(string.Format("CDN File Uploaded : {0}", this.GetMediaPath(mediaItem, extension))); }
public bool DeleteBlob(CloudBlockBlob blob, string snapshots = "None") { bool success = false; try { switch (snapshots.ToLower()) { case "snapshotsonly": blob.DeleteIfExists(DeleteSnapshotsOption.DeleteSnapshotsOnly); break; case "includesnapshots": blob.DeleteIfExists(DeleteSnapshotsOption.IncludeSnapshots); break; case "none": default: blob.DeleteIfExists(DeleteSnapshotsOption.None); break; } success = true; } catch (Exception ex) { throw ex; } return(success); }
public void UploadMediaToAzure(MediaItem mediaItem, string extension = "", string language = "") { CloudBlockBlob blockBlob = container.GetBlockBlobReference(GetMediaPath(mediaItem, extension, language)); blockBlob.DeleteIfExists(); if (string.IsNullOrEmpty(mediaItem.Extension)) { return; } if (mediaItem.HasMediaStream("Media")) { using (var fileStream = (System.IO.FileStream)mediaItem.GetMediaStream()) { blockBlob.Properties.ContentType = mediaItem.MimeType; blockBlob.UploadFromStream(fileStream); SetCacheControl(blockBlob, "public,max-age=691200"); } } else { blockBlob.DeleteIfExists(); } Item item = mediaItem; using (new EditContext(item, SecurityCheck.Disable)) { item["CDN file path"] = GetMediaPath(mediaItem, extension, language); item["Uploaded To Cloud CDN"] = "1"; } Logger.Info(string.Format("CDN File Uploaded : {0}", GetMediaPath(mediaItem, extension, language))); }
private async Task SaveTempFile(string fileName, long contentLenght, Stream inputStream) { try { //firstly, we need check the container if exists or not. And if not, we need to create one. await container.CreateIfNotExistsAsync(); //init a blobReference CloudBlockBlob tempFileBlob = container.GetBlockBlobReference(fileName); //if the blobReference is exists, delete the old blob tempFileBlob.DeleteIfExists(); //check the count of blob if over limit or not, if yes, clear them. await CleanStorageIfReachLimit(contentLenght); //and upload the new file in this tempFileBlob.UploadFromStream(inputStream); } catch (Exception ex) { if (ex.InnerException != null) { throw ex.InnerException; } else { throw ex; } } }
public async Task <HttpResponseMessage> DeleteFile() { if (ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/scope").Value != "user_impersonation") { throw new HttpResponseException(new HttpResponseMessage { StatusCode = HttpStatusCode.Unauthorized, ReasonPhrase = "The Scope claim does not contain 'user_impersonation' or scope claim not found" }); } Claim subject = ClaimsPrincipal.Current.FindFirst(ClaimTypes.NameIdentifier); CustomerFile custFile = await ProcessCustomerFileData(); CloudBlobContainer container = GetContainer(); custFile = SqlDBRepository.GetLegalDocumentData(custFile.Id); // Delete customer case directory from container for broker. CloudBlobDirectory caseDirectory = container.GetDirectoryReference("case" + custFile.CaseId.ToString().ToLower()); CloudBlockBlob blockBlob = caseDirectory.GetBlockBlobReference(custFile.Id.ToString() + "_" + custFile.DocumentType); blockBlob.DeleteIfExists(); bool status = SqlDBRepository.DeleteLegalDocument(custFile); return(new HttpResponseMessage() { StatusCode = HttpStatusCode.OK }); }
public string CopyBlob(string fileName, string sourceContainerName, string destContainerName, bool deleteSource = false, string destFileName = null) { try { CloudBlobContainer sourceContainer = ConnectionObject.GetContainerReference(sourceContainerName); CloudBlobContainer destContainer = ConnectionObject.GetContainerReference(destContainerName); CloudBlockBlob sourceFile = sourceContainer.GetBlockBlobReference(fileName); CloudBlockBlob destFile; if (destFileName != null) destFile = destContainer.GetBlockBlobReference(destFileName); else destFile = sourceContainer.GetBlockBlobReference(fileName); destFile.StartCopy(sourceFile); if (deleteSource) { sourceFile.DeleteIfExists(); } return destFile.Uri.AbsoluteUri; } catch (Exception) { return string.Empty; } }
public ActionResult Index(String nombre) { String keys = CloudConfigurationManager.GetSetting("ConexionBlobs"); CloudStorageAccount storageAccount = CloudStorageAccount.Parse(keys); CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient(); CloudBlobContainer container = blobClient.GetContainerReference("imagenes"); if (nombre != null) { CloudBlockBlob blockBlob = container.GetBlockBlobReference(nombre); blockBlob.DeleteIfExists(); } List <Imagen> imglist = new List <Imagen>(); foreach (IListBlobItem item in container.ListBlobs(null, true)) { if (item.GetType() == typeof(CloudBlockBlob)) { CloudBlockBlob blob = (CloudBlockBlob)item; Imagen img = new Imagen(); img.Nombre = blob.Name; img.UrlImagen = blob.Uri.AbsoluteUri; imglist.Add(img); } } return(View(imglist)); }
public void BlockBlob_UploadDownload_File_Stream() { using (var file = new TemporaryFile(512)) { CloudStorageAccount storageAccount = CloudStorageAccount.DevelopmentStorageAccount; CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient(); CloudBlobContainer container = blobClient.GetContainerReference("testcontainer"); container.CreateIfNotExists(); CloudBlockBlob blob = container.GetBlockBlobReference(file.fileInfo.Name); // Create provider var provider = new SymmetricBlobCryptoProvider(); // Upload file blob.UploadFromFileEncrypted(provider, file.fileInfo.FullName, FileMode.Open); // Download stream MemoryStream downloadedStream = new MemoryStream(); blob.DownloadToStreamEncrypted(provider, downloadedStream); // Compare raw and decrypted data Assert.AreEqual(GetFileHash(file.fileInfo.FullName), GetStreamHash(downloadedStream)); // Download file again, without our library, to ensure it was actually encrypted MemoryStream encryptedStream = new MemoryStream(); blob.DownloadToStream(encryptedStream); // Delete blob blob.DeleteIfExists(); } }
public static void Run() { #region Obtain a client from the connection string CloudStorageAccount storageAccount = CloudStorageAccount.Parse(CloudConfigurationManager.GetSetting("StorageConnectionString")); CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient(); Console.WriteLine("Parsed connection string and created blob client."); #endregion #region Obtain reference to docs container CloudBlobContainer docContainer = blobClient.GetContainerReference("docs"); Console.WriteLine("Obtained reference to docs container."); #endregion #region Delete blob CloudBlockBlob blockBlob = docContainer.GetBlockBlobReference(@"Readme.txt"); blockBlob.DeleteIfExists(); Console.WriteLine("Deleted Readme.txt from docs container."); try { blockBlob.Delete(); } catch (Exception exception) { Console.WriteLine("Caught exception '" + exception.GetType() + "' while trying to delete Readme.txt again from docs container."); Console.WriteLine(exception.StackTrace); } #endregion }
public static bool DeleteFile(string accountName, string accountKey, string containerName, string fileName, bool delSubDirs) { try { CloudStorageAccount storageAccount = CloudStorageAccount.Parse("DefaultEndpointsProtocol=http;AccountName=" + accountName + ";AccountKey=" + accountKey); CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient(); CloudBlobContainer container = blobClient.GetContainerReference(containerName); container.CreateIfNotExists(); BlobContainerPermissions containerPermissions = new BlobContainerPermissions(); containerPermissions.PublicAccess = BlobContainerPublicAccessType.Blob; container.SetPermissions(containerPermissions); if (false == delSubDirs) { CloudBlockBlob remoteFile = container.GetBlockBlobReference(fileName); remoteFile.DeleteIfExists(); } if (true == delSubDirs) { foreach (IListBlobItem item in container.ListBlobs(fileName, true)) { CloudBlockBlob blob = (CloudBlockBlob)item; blob.DeleteIfExists(); } } } catch (Exception) { return(false); } return(true); }
public void RemoveBlob(string containerName, string blobName) { this.ConnectToAzure(containerName); CloudBlockBlob cloudBlockBlob = this._cloudBlobContainer.GetBlockBlobReference(blobName); cloudBlockBlob.DeleteIfExists(); }
public async Task <ActionResult> DeleteConfirmed(int id) { ARCustRemit arcustremit = await db.ARCustRemits.FindAsync(id); // Delete blob CloudStorageAccount storageAccount = CloudStorageAccount.Parse( ConfigurationManager.ConnectionStrings["ARStorageConnectionString"].ConnectionString); String containerName = ConfigurationManager.ConnectionStrings["ARContainerConnectionString"].ConnectionString; // Create the blob client. CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient(); CloudBlobContainer container = blobClient.GetContainerReference(containerName); // Retrieve reference to a blob named blobName CloudBlockBlob blockBlob = container.GetBlockBlobReference(arcustremit.Record_Number.Trim()); blockBlob.DeleteIfExists(); // Then delete meta data record db.ARCustRemits.Remove(arcustremit); await db.SaveChangesAsync(); return(RedirectToAction("Index")); }
public IActionResult Excluir() { //Cria um blob client CloudBlobClient blobClient = _storageAccount.CreateCloudBlobClient(); //Recupera a referencia do container documentos CloudBlobContainer container = blobClient.GetContainerReference("documentos"); //Caso não exista, ele cria container.CreateIfNotExists(); //Setar permissão de acesso para 'público' container.SetPermissions( new BlobContainerPermissions { PublicAccess = BlobContainerPublicAccessType.Blob } ); //Recupera a referência de um blob chamado 'cliente01' CloudBlockBlob blockBlob = container.GetBlockBlobReference("cliente01.pdf"); //Exclui o blob caso ele exista blockBlob.DeleteIfExists(); return(RedirectToAction("VerArquivos")); }
public async Task <string> UploadFileInBlocksAsync(byte[] file, string guid) { Trace.TraceError("Upload archive " + guid); var guidName = guid; var blobName = guidName + ".zip"; CloudBlockBlob blobArchive = BlobContainer.GetBlockBlobReference(blobName); blobArchive.DeleteIfExists(); using (MemoryStream inputMemoryStream = new MemoryStream(file)) { BlobRequestOptions requestOptions = new BlobRequestOptions { SingleBlobUploadThresholdInBytes = 10 * 1024 * 1024, ParallelOperationThreadCount = 2, DisableContentMD5Validation = true }; await blobArchive.UploadFromStreamAsync(inputMemoryStream, null, options : requestOptions, operationContext : null); } return(blobArchive.Uri.ToString()); }
public void DeleteBlob(string fileName) { CloudBlockBlob cloudBlockBlob = null; cloudBlockBlob = this.ImagesDirectory.GetBlockBlobReference(fileName); cloudBlockBlob.DeleteIfExists(); }
public static CloudBlockBlob WriteContentToBlob(IAsset asset, CloudBlobContainer dstContainer, string dstBlobName, string blobContent) { string uri = null; CloudBlockBlob blob = null; try { //dstContainer.CreateIfNotExists(); blob = dstContainer.GetBlockBlobReference(dstBlobName); blob.DeleteIfExists(); var options = new BlobRequestOptions() { ServerTimeout = TimeSpan.FromMinutes(10) }; using (var stream = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(blobContent), false)) { blob.UploadFromStream(stream, null, options); } IAssetFile assetFile = asset.AssetFiles.Create(dstBlobName); blob.FetchAttributes(); assetFile.ContentFileSize = blob.Properties.Length; //assetFile.IsPrimary = false; assetFile.Update(); } catch (Exception e) { throw e; } return(blob); }
public void DeleteResourceHistoryItem(Resource r) { CloudBlockBlob blobSource = blob.GetBlockBlobReference(@Enum.GetName(typeof(ResourceType), r.ResourceType) + "/" + r.Id + "/" + r.Meta.VersionId); bool blobExisted = blobSource.DeleteIfExists(); return; }
private void ListBlobs() { // 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("managemystuffphotos"); // Loop over items within the container and output the length and URI. foreach (IListBlobItem item in container.ListBlobs(null, false)) { if (item.GetType() == typeof(CloudBlockBlob)) { CloudBlockBlob blob = (CloudBlockBlob)item; blob.DeleteIfExists(); } else if (item.GetType() == typeof(CloudPageBlob)) { CloudPageBlob pageBlob = (CloudPageBlob)item; } else if (item.GetType() == typeof(CloudBlobDirectory)) { CloudBlobDirectory directory = (CloudBlobDirectory)item; } } }
/// <summary> /// Copies a blob to a new location within a container, and deletes the original copy. This process /// is recursive under the specified directory. /// </summary> public void MoveBlob(string sourceContainerName, string sourcePath, string destContainerName, string destPath) { try { // Retreive the container CloudBlobContainer sourceContainer = _blobClient.GetContainerReference(sourceContainerName); CloudBlobContainer destContainer = _blobClient.GetContainerReference(destContainerName); // Create the container if it doesn't already exist. destContainer.CreateIfNotExists(); // Get a reference to the blob, so we can either create it or overwrite it CloudBlockBlob sourceBlob = sourceContainer.GetBlockBlobReference(sourcePath); CloudBlockBlob destinationBlob = destContainer.GetBlockBlobReference(destPath); // Copy to the new location destinationBlob.StartCopyFromBlob(sourceBlob); // Delete the old one sourceBlob.DeleteIfExists(); } catch (Exception ex) { System.Diagnostics.Trace.TraceError(ex.ToString()); throw; } }
private async Task <string> CreateThumbnailAsync(string blobUri) { // TODO : PUT THIS CONNECTION STRING TO APP SETTINGS string connectionString = ConfigurationManager.ConnectionStrings["azureConnection"].ConnectionString; CloudStorageAccount storageAccount = CloudStorageAccount.Parse(connectionString); CloudBlockBlob blob = new CloudBlockBlob(new Uri(blobUri), storageAccount.Credentials); var thumbnailImage = await ResizeBlobAsync(blob).ConfigureAwait(false); if (thumbnailImage.Length > 0) { var guidName = Guid.NewGuid().ToString(); var blobName = guidName + ".png"; //var blobName = guidName + Path.GetExtension(blob.Name); CloudBlockBlob blobThumbnail = BlobContainer.GetBlockBlobReference(blobName); blobThumbnail.DeleteIfExists(); await blobThumbnail.UploadFromByteArrayAsync(thumbnailImage, 0, thumbnailImage.Length).ConfigureAwait(false); return(blobThumbnail.Uri.ToString()); } return(null); }
public virtual void Remove(string[] urls) { foreach (var url in urls) { var absoluteUri = url.IsAbsoluteUrl() ? new Uri(url) : new Uri(_cloudBlobClient.BaseUri, url.TrimStart('/')); var blobContainer = GetBlobContainer(GetContainerNameFromUrl(absoluteUri.ToString())); var directoryPath = GetDirectoryPathFromUrl(absoluteUri.ToString()); if (String.IsNullOrEmpty(directoryPath)) { blobContainer.DeleteIfExists(); } else { var blobDirectory = blobContainer.GetDirectoryReference(directoryPath); //Remove all nested directory blobs foreach (var directoryBlob in blobDirectory.ListBlobs(true).OfType <CloudBlockBlob>()) { directoryBlob.DeleteIfExists(); } //Remove blockBlobs if url not directory /* http://stackoverflow.com/questions/29285239/delete-a-blob-from-windows-azure-in-c-sharp * In Azure Storage Client Library 4.0, we changed Get*Reference methods to accept relative addresses only. */ var filePath = GetFilePathFromUrl(url); CloudBlockBlob blobBlock = blobContainer.GetBlockBlobReference(filePath); blobBlock.DeleteIfExists(); } } }
public async Task ManualTrigger_Invoke_Succeeds() { CloudBlobContainer outputContainer = _fixture.BlobClient.GetContainerReference("samples-output"); CloudBlockBlob outputBlob = outputContainer.GetBlockBlobReference("result"); outputBlob.DeleteIfExists(); CloudBlobContainer inputContainer = _fixture.BlobClient.GetContainerReference("samples-input"); CloudBlockBlob statusBlob = inputContainer.GetBlockBlobReference("status"); statusBlob.UploadText("{ \"level\": 4, \"detail\": \"All systems are normal :)\" }"); string uri = "admin/functions/manualtrigger"; HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, uri); request.Headers.Add("x-functions-key", "t8laajal0a1ajkgzoqlfv5gxr4ebhqozebw4qzdy"); request.Content = new StringContent("{ 'input': 'Hello Manual Trigger!' }"); request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json"); HttpResponseMessage response = await this._fixture.HttpClient.SendAsync(request); Assert.Equal(HttpStatusCode.Accepted, response.StatusCode); // wait for completion string result = await TestHelpers.WaitForBlobAsync(outputBlob); Assert.Equal("All systems are normal :)", result); }
public void ReplaceMediaFromAzure(MediaItem mediaItem, string extension = "", string language = "") { //Delete old files from the blob Item item = mediaItem; if (!string.IsNullOrEmpty(item["CDN file path"])) { CloudBlockBlob oldblockBlob = container.GetBlockBlobReference(item["CDN file path"]); oldblockBlob.DeleteIfExists(); Logger.Info(string.Format(" CDN File Deleted : {0} ", item["CDN file path"].ToLower())); } CloudBlockBlob blockBlob = container.GetBlockBlobReference(GetMediaPath(mediaItem, extension, language)); if (string.IsNullOrEmpty(mediaItem.Extension)) { return; } using (var fileStream = (System.IO.FileStream)mediaItem.GetMediaStream()) { blockBlob.Properties.ContentType = mediaItem.MimeType; blockBlob.UploadFromStream(fileStream); SetCacheControl(blockBlob, "public,max-age=691200"); } using (new EditContext(item, SecurityCheck.Disable)) { item["CDN file path"] = GetMediaPath(mediaItem, extension, language); item["Uploaded To Cloud CDN"] = "1"; } Logger.Info(string.Format("CDN File Uploaded : {0}", GetMediaPath(mediaItem, extension, language))); }
/// <summary> /// Deletes an item from the cache. /// </summary> /// <param name="container"> /// Identifier for the cache container holding the item. /// </param> /// <param name="itemHash"> /// Hash key for the desired item. /// </param> public void DeleteItem( ItemCacheContainer container, string itemHash) { CloudBlockBlob cloudBlob = this.cloudContainers[(int)container].GetBlockBlobReference(itemHash); cloudBlob.DeleteIfExists(); }
/// <summary> /// Delete wcf message from blob. /// </summary> /// <param name="messageId">message Id, it is used as blob name</param> public void DeleteBlob(UniqueId messageId) { string blobName = messageId.ToString(); CloudBlockBlob blob = this.container.GetBlockBlobReference(blobName); blob.DeleteIfExists(); }
public static void MoveImageFromTempToProject(Image image, int projectId) { CloudBlockBlob oldFile = TempProjectImages.GetBlockBlobReference(image.FileName); CloudBlockBlob newFile = ProjectImages.GetBlockBlobReference("Project" + projectId + image.OriginalFileName); newFile.StartCopy(oldFile); oldFile.DeleteIfExists(); }
public static void MoveIconFromTempToProject(int tempProjectId, int projectId) { CloudBlockBlob oldFile = IconsContainer.GetBlockBlobReference(TempProject.GetIconName(tempProjectId)); CloudBlockBlob newFile = IconsContainer.GetBlockBlobReference(Project.GetIconName(projectId)); newFile.StartCopy(oldFile); oldFile.DeleteIfExists(); }
public static void RemoveIcon(int projectId, bool temp) { string fileName = temp ? Project.GetIconName(projectId) : TempProject.GetIconName(projectId); CloudBlockBlob cblob = IconsContainer.GetBlockBlobReference(fileName); cblob.DeleteIfExists(); }
public void DeleteMediaFromAzure(MediaItem mediaItem, string extension = "", string language = "") { CloudBlockBlob blockBlob = container.GetBlockBlobReference(GetMediaPath(mediaItem, extension, language)); blockBlob.DeleteIfExists(); Logger.Info(string.Format(" CDN File Deleted : {0}", GetMediaPath(mediaItem, extension, language))); }
public void UploadBlob() { cloudBlockBlob.DeleteIfExists(); if (cloudBlockBlob.Metadata.ContainsKey(SampleMetadataKey)) { cloudBlockBlob.Metadata.Remove(SampleMetadataKey); } var metadataValue = SampleMetadataValue; cloudBlockBlob.Metadata.Add(new KeyValuePair <string, string>(SampleMetadataKey, metadataValue)); cloudBlockBlob.UploadText(string.Empty); Assert.IsTrue(cloudBlockBlob.Exists()); }