//private static Task<TagBlob> WriteActiveTag(CloudBlobContainer channelContainer, string tagBlobName, TagTransactionEntity tag) //{ // var activeTagBlobRelativeUri = AzureUris.JsonActiveTagBlobRelativeUri(tagBlobName); // var versionedTagBlobRelativeUri = AzureUris.JsonTagVersionedBlobRelativeUri(tagBlobName, tag.Version); // var blob = channelContainer.GetBlockBlobReference(activeTagBlobRelativeUri); // var history = GetTagBlobHistory(blob); // history.Add(new TagBlobHistory() { Id = versionedTagBlobRelativeUri, Version = tag.Version }); // var tagBlob = new TagBlob(blob.Uri, tag, history); // return UploadTagToBlob(tagBlob, blob, tag.Fingerprint); //} private static async Task <TagBlobUris> WriteVersionedTag(CloudBlobDirectory sourceContainer, TagEntity tagEntity, SoftwareIdentity SoftwareIdentity) { var json = SoftwareIdentity.SwidTagJson; var xml = SoftwareIdentity.SwidTagXml; var jsonBlobUri = AzureUris.JsonTagVersionedBlobRelativeUri(tagEntity.TagAzid, tagEntity.Version); var xmlBlobUri = AzureUris.XmlTagVersionedBlobRelativeUri(tagEntity.TagAzid, tagEntity.Version); var jsonBlob = sourceContainer.GetBlockBlobReference(jsonBlobUri); var xmlBlob = sourceContainer.GetBlockBlobReference(xmlBlobUri); //var revisions = GetTagBlobRevisions(blob); await Task.WhenAll( UploadTagToBlob(tagEntity, jsonBlob, json, FearTheCowboy.Iso19770.Schema.MediaType.SwidTagJsonLd), UploadTagToBlob(tagEntity, xmlBlob, xml, FearTheCowboy.Iso19770.Schema.MediaType.SwidTagXml) ); return(new TagBlobUris() { JsonUri = jsonBlob.Uri, XmlUri = xmlBlob.Uri }); }
private async Task WriteIndexTags(SoftwareIdentity indexJsonTag, SoftwareIdentity indexXmlTag, CloudBlobDirectory sourceDirectory) { var blobJson = sourceDirectory.GetBlockBlobReference("index.json.SoftwareIdentity"); var blobXml = sourceDirectory.GetBlockBlobReference("index.xml.SoftwareIdentity"); var json = indexJsonTag.SwidTagJson; var xml = indexXmlTag.SwidTagXml; await Task.WhenAll( blobJson.UploadTextAsync(json), blobXml.UploadTextAsync(xml) ); blobJson.Properties.CacheControl = "public, max-age=300"; // cache for 5 minutes. blobXml.Properties.CacheControl = "public, max-age=300"; // cache for 5 minutes. blobJson.Properties.ContentType = FearTheCowboy.Iso19770.Schema.MediaType.SwidTagJsonLd; blobXml.Properties.ContentType = FearTheCowboy.Iso19770.Schema.MediaType.SwidTagXml; await Task.WhenAll( blobJson.SetPropertiesAsync(), blobXml.SetPropertiesAsync() ); }
internal static CloudBlockBlob CreateBlob(string containerName, string tableName, string ext) { IsdkStorageProviderInterface service = Helper.ServiceObject; CloudBlobDirectory ContainerDirectory = convertedData.GetDirectoryReference(containerName); switch (ext) { case ".xml": // Get dbf data and save to blob XDocument dataInDbfFormat = service.GetDataAsDaisy(containerName, tableName, null); CloudBlockBlob dbfBlob = ContainerDirectory.GetBlockBlobReference(tableName + ext); using (MemoryStream xmlStream = new MemoryStream()) { using (XmlWriter xmlWriter = XmlWriter.Create(xmlStream)) { dataInDbfFormat.Save(xmlWriter); xmlWriter.Close(); xmlStream.Position = 0; dbfBlob.UploadFromStream(xmlStream); } } return(dbfBlob); case ".csv": // Get csv data and save to blob string dataInCsvFormat = service.GetdDataAsCsv(containerName, tableName, null); CloudBlockBlob csvBlob = ContainerDirectory.GetBlockBlobReference(tableName + ext); using (MemoryStream csvStream = new MemoryStream()) { using (StreamWriter sw = new StreamWriter(csvStream)) { sw.Write(dataInCsvFormat); sw.Flush(); csvStream.Position = 0; csvBlob.UploadFromStream(csvStream); sw.Close(); } } return(csvBlob); case ".ANSI.csv": // Get csv data and save to blob for Excel string dataInANSICsvFormat = service.GetdDataAsCsv(containerName, tableName, null); //Encoding winLatinCodePage = Encoding.GetEncoding(1252); Encoding winLatinCodePage = Encoding.GetEncoding(Convert.ToInt32(OgdiConfiguration.GetValue("ANSICodePage"))); CloudBlockBlob ANSIcsvBlob = ContainerDirectory.GetBlockBlobReference(tableName + ext); MemoryStream ANSIcsvStream = new MemoryStream(Encoding.Convert(Encoding.Unicode, winLatinCodePage, Encoding.Unicode.GetBytes(dataInANSICsvFormat))); ANSIcsvStream.Position = 0; ANSIcsvBlob.UploadFromStream(ANSIcsvStream); return(ANSIcsvBlob); } return(null); }
public string ParsearPDF() { string storageConnectionString = Environment.GetEnvironmentVariable("AzureWebJobsStorage"); string azureFolderPath = ""; CloudStorageAccount storageAccount = CloudStorageAccount.Parse(storageConnectionString); CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient(); CloudBlobContainer container = blobClient.GetContainerReference("carpetapdf"); CloudBlobDirectory cloudBlobDirectory = container.GetDirectoryReference(azureFolderPath); ////get source file to split string pdfFile = "pliego.pdf"; CloudBlockBlob blockBlob1 = cloudBlobDirectory.GetBlockBlobReference(pdfFile); //convert to memory stream MemoryStream memStream = new MemoryStream(); blockBlob1.DownloadToStreamAsync(memStream).Wait(); PdfSharp.Pdf.PdfDocument outputDocument = new PdfSharp.Pdf.PdfDocument(); //get source file to split for (var i = 0; i <= doc.Pages.Count - 1; i++) { //define output file for azure string outputPDFFile = "output" + i + ".pdf"; CloudBlockBlob outputblockBlob = cloudBlobDirectory.GetBlockBlobReference(outputPDFFile); //create new document MemoryStream newPDFStream = new MemoryStream(); PdfSharp.Pdf.PdfDocument pdfDoc = PdfSharp.Pdf.IO.PdfReader.Open(strOriginal, PdfDocumentOpenMode.Import); for (var j = doc.Pages.Count - 1; j >= 0; j--) { if (j != i) { pdfDoc.Pages.RemoveAt(j); } } byte[] pdfData; using (var ms = new MemoryStream()) { //doc.Save(ms); pdfDoc.Save(ms); pdfData = ms.ToArray(); //outputblockBlob.UploadFromStreamAsync(ms); outputblockBlob.UploadFromByteArrayAsync(pdfData, 0, pdfData.Length); } } return("Ok"); }
public Task CreateFileAsync( string fileName, byte[] buffer, int offset, int count, CancellationToken cancellationToken = default) { return(_directory .GetBlockBlobReference(fileName) .UploadFromByteArrayAsync(buffer, offset, count, cancellationToken)); }
private async Task <CloudBlockBlob> GetAvailableBlob(CloudBlobDirectory folder, string name) { if (await folder.GetBlockBlobReference(name).ExistsAsync()) { return(await GetAvailableBlob(folder, RandomizeBlobName(name))); } return(folder.GetBlockBlobReference(name)); }
public Uri GetBlobUrl(string blobName, bool cdn = false) { var blob = _blobDirectory.GetBlockBlobReference(blobName); var uri = blob.Uri; if (cdn) { uri = uri.ChangeHost(CdnHostEndpoint); } return(uri); }
/// <inheritdoc /> public async Task UpdateCheckpointAsync(Lease lease, Checkpoint checkpoint) { using (_logger.BeginScope("Updating checkpoint")) { _checkpointUpdateCounter.Increment(); CheckpointLease blobLease = new CheckpointLease(lease) { Offset = checkpoint.Offset, SequenceNumber = checkpoint.SequenceNumber, PartitionId = checkpoint.PartitionId }; _logger.LogInformation("Updating checkpoint: Partition Id: {partitionId}", blobLease.PartitionId); CloudBlockBlob leaseBlob = _consumerGroupDirectory.GetBlockBlobReference(blobLease.PartitionId); try { string jsonToUpload = JsonConvert.SerializeObject(lease); _logger.LogTrace("Updating checkpoint: Partition Id: {partitionId}, RawJson: {json}", blobLease.PartitionId, jsonToUpload); AccessCondition accessCondition; if (_etags.ContainsKey(lease.PartitionId)) { accessCondition = AccessCondition.GenerateIfMatchCondition(_etags[lease.PartitionId]); } else { accessCondition = AzureBlobCommon.DefaultAccessCondition; } using (_storagePerformanceSummary.Time()) { await leaseBlob.UploadTextAsync(jsonToUpload, _checkpointEncoding, accessCondition, _defaultRequestOptions, AzureBlobCommon.DefaultOperationContext).ConfigureAwait(false); } _etags.AddOrUpdate(lease.PartitionId, leaseBlob.Properties.ETag, (pid, petag) => leaseBlob.Properties.ETag); _logger.LogInformation("Updated checkpoint for partition {partitionId}", blobLease.PartitionId); } catch (StorageException e) { _checkpointErrorCounter.Increment(); _logger.LogError(e, "Error updating partition {partitionId}", blobLease.PartitionId); throw; } } }
//Blob exists public override bool Exists(string fileName) { Uri packageRegistrationUri = ResolveUri(fileName); string blobName = GetName(packageRegistrationUri); CloudBlockBlob blob = _directory.GetBlockBlobReference(blobName); if (blob.Exists()) { return(true); } return(false); }
public void DownloadToStream(CloudBlobDirectory container, string Name, Stream memoryStream) { CloudBlockBlob blockBlob2 = container.GetBlockBlobReference(ToURLSlug(Name)); blockBlob2.DownloadToStream(memoryStream); memoryStream.Seek(0, SeekOrigin.Begin); }
private static string ParserPDF(TraceWriter log, string name) { string storageConnectionString = Environment.GetEnvironmentVariable("AzureWebJobsStorage"); string azureFolderPath = ""; CloudStorageAccount storageAccount = CloudStorageAccount.Parse(storageConnectionString); CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient(); CloudBlobContainer container = blobClient.GetContainerReference("carpetapdf"); CloudBlobDirectory cloudBlobDirectory = container.GetDirectoryReference(azureFolderPath); ////get source file to split string pdfFile = name + ".pdf"; PDFnameGuid = pdfFile.ToString(); CloudBlockBlob blockBlob1 = cloudBlobDirectory.GetBlockBlobReference(pdfFile); //convert to memory stream MemoryStream memStream = new MemoryStream(); blockBlob1.DownloadToStreamAsync(memStream).Wait(); LoadPdf(memStream, log); return("Ok"); }
private async Task <string> UploadBase64Image(string moduleName, string imageBase64, string imageName) { string path = null; try { string imageFile = this.getBase64File(imageBase64); string imageType = this.getBase64Type(imageBase64); byte[] imageBytes = Convert.FromBase64String(imageFile); if (imageBytes != null) { CloudBlobContainer container = this.StorageContainer; CloudBlobDirectory dir = container.GetDirectoryReference(moduleName); CloudBlockBlob blob = dir.GetBlockBlobReference(imageName); blob.Properties.ContentType = imageType; await blob.UploadFromByteArrayAsync(imageBytes, 0, imageBytes.Length); path = "/" + this.StorageContainer.Name + "/" + moduleName + "/" + imageName; } } catch (Exception ex) { if (!(ex is ArgumentNullException) && !(ex is FormatException)) { throw new Exception(ex.Message, ex.InnerException); } } return(path); }
/// <summary> /// Upload a header image. /// HTTP form body should include <see cref="File"/> pic containing the image to upload. /// </summary> public static async Task <IActionResult> Create( HttpRequest req, ClaimsPrincipal principal, ILogger log, CloudBlobDirectory blobDirectory) { var pic = req.Form.Files.GetFile("pic"); if (pic == null) { return(Response.BadRequest("No image included in request.")); } var picStream = pic.OpenReadStream(); var img = Image.Load(picStream); // resize to width of 1920 while maintaining aspect ratio if (img.Size().Width > 1920) { img.Mutate(i => i.Resize(0, 1920)); } // upload into storage var blob = blobDirectory.GetBlockBlobReference(pic.FileName.WithTimestamp()); await blob.UploadFromStreamAsync(pic.OpenReadStream()); // insert record var link = blob.Uri.ToString(); var(_, id) = await FancyConn.Shared.Scalar("INSERT INTO [header]([link]) VALUES (@link); SELECT SCOPE_IDENTITY();", new Dictionary <string, object>() { { "link", link } }); return(Response.Ok("Image uploaded successfully.", new { id, link })); }
public async Task <IDictionary <string, string> > GetMetadataAsync(string fileName, string folderPath) { try { var container = await this.GetBlobContainerAsync(""); if (container != null) { CloudBlobDirectory blobDirectory = container.GetDirectoryReference(folderPath); CloudBlockBlob blockBlob = blobDirectory.GetBlockBlobReference(fileName); if (blockBlob != null) { await blockBlob.FetchAttributesAsync(); return(blockBlob.Metadata); } return(null); } return(null); } catch (Exception ex) { this.logger.LogError(ex, ex.Message); return(null); } }
public async Task <string> DownloadPathAsync(string fileName, string folderPath) { try { var container = await this.GetBlobContainerAsync(""); if (container != null) { CloudBlobDirectory blobDirectory = container.GetDirectoryReference(folderPath); CloudBlockBlob blockBlob = blobDirectory.GetBlockBlobReference(fileName); if (blockBlob != null) { var sasConstraints = new SharedAccessBlobPolicy(); sasConstraints.SharedAccessStartTime = DateTime.UtcNow.AddMinutes(-5); sasConstraints.SharedAccessExpiryTime = DateTime.UtcNow.AddMinutes(5); sasConstraints.Permissions = SharedAccessBlobPermissions.Read; var sasBlobToken = blockBlob.GetSharedAccessSignature(sasConstraints); return(blockBlob.Uri + sasBlobToken); } return(null); } return(null); } catch (Exception ex) { string test = ex.Message; test += "test"; return(null); } }
private static async Task BasicBlobOperation() { const string ImageToUplaod = "Cloud.xml"; const string connectionString = "DefaultEndpointsProtocol=https;AccountName=az203sa;AccountKey=WF9Ojv2ghJwFuQ9YNuKJPRBpPotvRbhN4ScJaGy7qLBuXgAJgQVej/AVfu3MWTGxzxBp1pk7jqT5yJ33BwWcDg==;EndpointSuffix=core.windows.net"; CloudStorageAccount storageAccount = CloudStorageAccount.Parse(connectionString); CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient(); CloudBlobContainer container = blobClient.GetContainerReference("newcontainer"); await container.CreateIfNotExistsAsync().ConfigureAwait(false); CloudBlobDirectory dir = container.GetDirectoryReference("vsdir"); CloudBlockBlob blockBlob = dir.GetBlockBlobReference(ImageToUplaod); await blockBlob.UploadFromFileAsync(ImageToUplaod); var blobs = container.ListBlobs("vsdir", true); blockBlob.Metadata["Author"] = "Visual Studio"; blockBlob.Metadata["Priority"] = "High"; await blockBlob.SetMetadataAsync(); //await HandleConCurrencyForUpdate(blockBlob, ConcurrencyType.Default); //await HandleConCurrencyForUpdate(blockBlob, ConcurrencyType.Optimistic); await HandleConCurrencyForUpdate(blockBlob, ConcurrencyType.Pessimistic); //await blockBlob.DownloadToFileAsync("copyof" + ImageToUplaod, System.IO.FileMode.Create); //await blockBlob.DeleteAsync(); }
private static string ParserPDF(TraceWriter log) { log.Info("Inicio Carga PDF 1"); try { string storageConnectionString = Environment.GetEnvironmentVariable("AzureWebJobsStorage"); string azureFolderPath = ""; CloudStorageAccount storageAccount = CloudStorageAccount.Parse(storageConnectionString); CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient(); CloudBlobContainer container = blobClient.GetContainerReference("carpetapdf"); CloudBlobDirectory cloudBlobDirectory = container.GetDirectoryReference(azureFolderPath); ////get source file to split string pdfFile = "pliego.pdf"; CloudBlockBlob blockBlob1 = cloudBlobDirectory.GetBlockBlobReference(pdfFile); log.Info("Inicio Carga PDF 2"); //convert to memory stream MemoryStream memStream = new MemoryStream(); blockBlob1.DownloadToStreamAsync(memStream).Wait(); log.Info("Cargó MemStream"); LoadPdf(memStream, log); }catch (Exception ex) { log.Info("exception 1 " + ex.Message.ToString()); } return("Ok"); }
private static CloudBlockBlob CreateBlockBlob(CloudBlobContainer container, string strDirectoryName, string strFileName) { CloudBlobDirectory directory = container.GetDirectoryReference(strDirectoryName); CloudBlockBlob blockblob = directory.GetBlockBlobReference(strFileName); return(blockblob); }
public async Task DeleteBlobFileAsync(string fileUrl, string container) { Uri uriObj = new Uri(fileUrl); string BlobName = Path.GetFileName(uriObj.LocalPath); CloudStorageAccount cloudStorageAccount = CloudStorageAccount.Parse(accessKey); CloudBlobClient cloudBlobClient = cloudStorageAccount.CreateCloudBlobClient(); string strContainerName = container; 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); if (blockBlob.Exists()) { // delete blob from container await blockBlob.DeleteAsync(); } }
public async Task <string> LoadLabels() { // Get a azure storage client string storageConnection = Engine.GetEnvironmentVariable("AzureWebJobsStorage"); CloudStorageAccount storageAccount = CloudStorageAccount.Parse(storageConnection); CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient(); // Get references to the test label data and the location the test blobs needs to be to run tests. string jsonStorageContainerName = Engine.GetEnvironmentVariable("jsonStorageContainerName"); CloudBlobContainer jsonStorageContainer = blobClient.GetContainerReference(jsonStorageContainerName); string labelingTagsBlobName = Engine.GetEnvironmentVariable("labelingTagsBlobName"); CloudBlockBlob dataLabelingTagsBlob = jsonStorageContainer.GetBlockBlobReference(labelingTagsBlobName); string testDataContainerName = "testdata"; CloudBlobContainer testDataContainer = blobClient.GetContainerReference(testDataContainerName); CloudBlobDirectory labelingTagsDirectory = testDataContainer.GetDirectoryReference("LabelingTags"); CloudBlockBlob testDataLabelingTagsBlob = labelingTagsDirectory.GetBlockBlobReference(labelingTagsBlobName); //copy the test labeling tags blob to the expected location. //*****TODO***** we cannot copy the training lables JSON to the JSON file as it will trigger indexing of the // file which will fail do to mismatched schema. What we actually need to do is figure out how to retrieve the // training tags from the labeling solution such as VoTT. //await dataLabelingTagsBlob.StartCopyAsync(testDataLabelingTagsBlob); //Load the list of valid training tags to ensure all data labels are valid. string loadTrainingTagsResult = Model.LoadTrainingTags(); return($"\nCompleted loading labeling tags with result {loadTrainingTagsResult}."); }
public async Task <MemoryStream> DownloadToMemoryStreamAsync(string fileName, string folderPath) { try { var container = await this.GetBlobContainerAsync(""); if (container != null) { CloudBlobDirectory blobDirectory = container.GetDirectoryReference(folderPath); CloudBlockBlob blockBlob = blobDirectory.GetBlockBlobReference(fileName); if (blockBlob != null) { await blockBlob.FetchAttributesAsync(); var memoryStream = new MemoryStream(); await blockBlob.DownloadToStreamAsync(memoryStream); return(memoryStream); } return(null); } return(null); } catch (Exception ex) { string test = ex.Message; test += "test"; return(null); } }
private async static void SaveTransferCheckpoint(string jobId, TransferCheckpoint transferCheckpoint) { try { // Get reference to storage account we are using for Web Jobs Storage CloudBlobDirectory directory = await GetCheckpointStorage(); CloudBlockBlob blob = directory.GetBlockBlobReference(jobId); await blob.DeleteIfExistsAsync(DeleteSnapshotsOption.None, null, _blobRequestOptions, _opContext); using (var stream = new MemoryStream()) { IFormatter formatter = new BinaryFormatter(); formatter.Serialize(stream, transferCheckpoint); stream.Position = 0; await blob.UploadFromStreamAsync(stream, null, _blobRequestOptions, _opContext); } } catch (Exception ex) { throw new Exception("Error in SaveTransferCheckpoint(): " + ex.Message); } }
public async Task <bool> DeleteAsync(string fileName, string folderPath) { try { var container = await this.GetBlobContainerAsync(""); if (container != null) { CloudBlobDirectory blobDirectory = container.GetDirectoryReference(folderPath); CloudBlockBlob blockBlob = blobDirectory.GetBlockBlobReference(fileName); if (blockBlob != null) { return(await blockBlob.DeleteIfExistsAsync()); } } return(false); } catch (Exception ex) { this.logger.LogError(ex, ex.Message); return(false); } }
public void UploadToBlob_WasImageArrayUploaded() { string directoryName = "test"; string imagepath = @"Testimage\testimage.jpg"; byte[] imgArray = ConvertImageToByte(imagepath); string blobName = string.Format(@"{0}_{1}.jpg", "profiletest", "testimage"); CloudStorageAccount storageAccount = CloudStorageAccount.Parse(CloudConfigurationManager.GetSetting("StorageConnectionString")); CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient(); CloudBlobContainer container = blobClient.GetContainerReference("brothership"); container.CreateIfNotExists(); CloudBlobDirectory directory = container.GetDirectoryReference(directoryName); CloudBlockBlob blockBlob = directory.GetBlockBlobReference(blobName); //blockBlob.Properties.ContentType = "image/jpg"; //blockBlob.SetProperties(); blockBlob.UploadFromByteArray(imgArray, 0, imgArray.Length); }
private async Task <string> GetPlayerImageUri() { if (imageLoadedFromLocalFilesystem) { //// Upload new image as BlockBlob if not already in any of the container's folders // Set the blob's content type so that the browser knows to treat it as an image. string imageType = Path.GetExtension(AvatarImagePictureBox.ImageLocation); string imageFileName = Path.GetFileName(AvatarImagePictureBox.ImageLocation); //Upload new image as blockBlob CloudBlockBlob blockBlob = customDir.GetBlockBlobReference(imageFileName); blockBlob.Properties.ContentType = "image/" + imageType; await blockBlob.UploadFromFileAsync(AvatarImagePictureBox.ImageLocation); return(blockBlob.Uri.AbsoluteUri); } else { // Image with same name already in storage? bool isInDefaultFolder = defaultBlobs.Contains(new CloudBlockBlob(new Uri(AvatarImagePictureBox.ImageLocation))); customDir = clickycratesBlobContainer.GetDirectoryReference("custom"); customBlobs = customDir.ListBlobs().ToList(); bool isInCustomFolder = customBlobs.Contains(new CloudBlockBlob(new Uri(AvatarImagePictureBox.ImageLocation))); if (isInCustomFolder || isInDefaultFolder) { return(AvatarImagePictureBox.ImageLocation); } else { return(string.Empty); } } }
/// <summary> /// Gets or add an item. /// </summary> /// <param name="cacheKey">The cache key.</param> /// <param name="directoryName">Name of the directory.</param> /// <param name="addFactory">The function that is called if the item is not found in the remote storage, it is called with the cacheKey and the directoryName and the return value will be uploaded as text.</param> /// <returns> /// The value /// </returns> /// <exception cref="ArgumentException"> /// Value cannot be null or whitespace. /// or /// Value cannot be null or whitespace. /// </exception> public string GetOrAdd(string cacheKey, string directoryName, Func <string, string, string> addFactory) { if (string.IsNullOrWhiteSpace(cacheKey)) { throw new ArgumentException("Value cannot be null or whitespace.", nameof(cacheKey)); } if (string.IsNullOrWhiteSpace(directoryName)) { throw new ArgumentException("Value cannot be null or whitespace.", nameof(directoryName)); } CloudBlobDirectory cloudBlobDirectory = _container.GetDirectoryReference(directoryName); CloudBlob blobReference = cloudBlobDirectory.GetBlobReference(cacheKey); if (blobReference.ExistsAsync().Result) { return(DownloadAsText(blobReference)); } CloudBlockBlob blockBlobReference = cloudBlobDirectory.GetBlockBlobReference(cacheKey); if (!blockBlobReference.ExistsAsync().Result) //double check { string content = addFactory(cacheKey, directoryName); blockBlobReference.UploadTextAsync(content); return(content); } return(DownloadAsText(blobReference)); }
/// <summary> /// Delete a header image. /// </summary> public static async Task <IActionResult> Delete( HttpRequest req, ClaimsPrincipal principal, ILogger log, CloudBlobDirectory blobDirectory, int id) { // delete file var(err, url) = await FancyConn.Shared.Scalar("SELECT [link] FROM [header] WHERE [header_id] = @id", new Dictionary <string, object>() { { "id", id } }); if (err) { return(Response.Error("Failed to find record.", FancyConn.Shared.lastError)); } var uri = new Uri((string)url); var fn = Path.GetFileName(uri.LocalPath); var blob = blobDirectory.GetBlockBlobReference(fn); await blob.DeleteIfExistsAsync(); // delete record (err, _) = await FancyConn.Shared.NonQuery("DELETE FROM [header] WHERE [header_id] = @id;", new Dictionary <string, object>() { { "id", id } }); if (err) { return(Response.Error("Failed to delete record.", FancyConn.Shared.lastError)); } return(Response.Ok("Image deleted successfully.")); }
public List <multiDocument> uploadMultipleDocuments(List <PDFStream> pdfStreams, String folderName) { CloudStorageAccount storageacc = CloudStorageAccount.Parse(connectionString); CloudBlobClient blobClient = storageacc.CreateCloudBlobClient(); CloudBlobContainer container = blobClient.GetContainerReference(containerRef); container.CreateIfNotExists(); CloudBlobDirectory directory = container.GetDirectoryReference(folderName); List <multiDocument> documentUrls = new List <multiDocument>(); foreach (PDFStream pdfs in pdfStreams) { CloudBlockBlob blockBlob = directory.GetBlockBlobReference(pdfs.fileName); blockBlob.Metadata["keepUntil"] = getKeepUntilDate(); blockBlob.UploadFromByteArray(pdfs.stream, 0, pdfs.stream.Length); //documentUrls.Add(blockBlob.Uri.AbsoluteUri); documentUrls.Add(new multiDocument(blockBlob.Uri.AbsoluteUri, pdfs.identifier)); } return(documentUrls); }
private async Task <string> DownloadBase64Image(string moduleName, string imageName) { string imageSrc = string.Empty; try { CloudBlobContainer container = this.StorageContainer; CloudBlobDirectory dir = container.GetDirectoryReference(moduleName); CloudBlockBlob blob = dir.GetBlockBlobReference(imageName); await blob.FetchAttributesAsync(); byte[] imageBytes = new byte[blob.Properties.Length]; await blob.DownloadToByteArrayAsync(imageBytes, 0); string imageBase64 = Convert.ToBase64String(imageBytes); imageSrc = "data:" + blob.Properties.ContentType + ";base64," + imageBase64; } catch (Exception ex) { if (!(ex is StorageException)) { throw new Exception(ex.Message, ex.InnerException); } } return(imageSrc); }
public async Task <(Stream, string, string)> DownloadFileAsync(string fileUrl) { try { MemoryStream ms = new MemoryStream(); Uri uriObj = new Uri(fileUrl); string BlobName = Path.GetFileName(uriObj.LocalPath); CloudStorageAccount cloudStorageAccount = CloudStorageAccount.Parse(accessKey); CloudBlobClient cloudBlobClient = cloudStorageAccount.CreateCloudBlobClient(); string strContainerName = "uploads"; 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); await blockBlob.DownloadToStreamAsync(ms); Stream blobStream = await blockBlob.OpenReadAsync(); return(blobStream, blockBlob.Properties.ContentType, BlobName); } catch (StorageException ex) { throw ex; } }