public async Task <StationImageDownloadModel> DownloadBlob(int ID) { var imageName = GetImageName(ID); if (!String.IsNullOrEmpty(imageName)) { var container = BlobHelper.GetBlobContainer(); var blob = container.GetBlockBlobReference(imageName); var ms = new MemoryStream(); await blob.DownloadToStreamAsync(ms); // Strip off any folder structure so the file name is just the file name var lastPos = blob.Name.LastIndexOf('/'); var fileName = blob.Name.Substring(lastPos + 1, blob.Name.Length - lastPos - 1); // Build and return the download model with the blob stream and its relevant info var downloadModel = new StationImageDownloadModel { BlobStream = ms, BlobFileName = fileName, BlobLength = blob.Properties.Length, BlobContentType = blob.Properties.ContentType }; return(downloadModel); } // Otherwise return(null); }
public async Task <DeleteStationImageModel> DeleteBlob(DeleteStationImageModel model) { var deleteStationImageModel = new DeleteStationImageModel(); if (!String.IsNullOrEmpty(model.FileName)) { var container = BlobHelper.GetBlobContainer(); var blob = container.GetBlockBlobReference(model.FileName); bool deleted = false; string errorMessage = string.Empty; using (RiverWatchEntities _db = new RiverWatchEntities()) { var sameImageUrls = _db.StationImages .Where(si => si.FileUrl.Equals(model.FileUrl)) .ToList(); //if there is only one file, then delete it from the blob storage. if (sameImageUrls.Count() == 1) { await blob.DeleteIfExistsAsync(); } var stationImageToDelete = _db.StationImages.Find(model.ID); _db.StationImages.Remove(stationImageToDelete); _db.SaveChanges(); deleted = true; } if (!deleted) { errorMessage = "Image could not be deleted. Contact an Administrator if this problem continues."; } deleteStationImageModel = new DeleteStationImageModel() { ID = model.ID, FileName = model.FileName, FileUrl = model.FileUrl, Deleted = deleted, ErrorMessage = errorMessage }; return(deleteStationImageModel); } // Otherwise deleteStationImageModel = new DeleteStationImageModel() { ID = model.ID, FileName = model.FileName, Deleted = false, ErrorMessage = "Image could not be found. Contact an Administrator if this problem continues." }; return(deleteStationImageModel); }
public override Task ExecutePostProcessingAsync() { // NOTE: FileData is a property of MultipartFileStreamProvider and is a list of multipart // files that have been uploaded and saved to disk in the Path.GetTempPath() location. foreach (var fileData in FileData) { if (fileData.Headers.ContentDisposition.FileName == null) { continue; } // Sometimes the filename has a leading and trailing double-quote character // when uploaded, so we trim it; otherwise, we get an illegal character exception var fileName = Path.GetFileName(fileData.Headers.ContentDisposition.FileName.Trim('"')); // Retrieve reference to a blob var blobContainer = BlobHelper.GetBlobContainer(); var blob = blobContainer.GetBlockBlobReference(fileName); // Set the blob content type blob.Properties.ContentType = fileData.Headers.ContentType.MediaType; // Upload file into blob storage, basically copying it from local disk into Azure using (var fs = File.OpenRead(fileData.LocalFileName)) { blob.UploadFromStream(fs); } // Delete local file from disk File.Delete(fileData.LocalFileName); // Create blob upload model with properties from blob info var blobUpload = new BlobUploadModel { FileName = blob.Name, FileUrl = blob.Uri.AbsoluteUri, FileSizeInBytes = blob.Properties.Length }; // Add uploaded blob to the list Uploads.Add(blobUpload); } return(base.ExecutePostProcessingAsync()); }
static void Main(string[] args) { var StorageConnectionString = "DefaultEndpointsProtocol=https;AccountName=mediavaletdevasia;AccountKey=wtjIEIXRmtA6tHUW5zkhYwc1cCYhlFhsW8z2Cf3TUpKacrrnYWBaLUUrQDacfH3kQ3XhftEhVt3f2ONZQhCMog=="; var eventIds = new[] { "1aa5e37f-652f-4be2-be17-9dd805d90152", "7b103c54-07d1-4f99-b803-95711f9bcfb1", "ae7f3e28-75f3-44e6-89c9-c4aedc783869", "ae7f3e28-75f3-44e6-89c9-c4aedc783869", "c71ecd03-c2e0-4f8e-accf-282e500ddef8", "47dddb99-adf2-4a16-a2b2-4cfee3d11aea", "9ce78d54-e0fa-4e91-8870-72f3d3745fe4", "ad003c6d-807d-44b1-b5f0-26a15d622835", "0f6b9881-3a96-4ac6-99d1-576f3267421b", "4b2b105b-caf5-44f1-b622-582d6ab6bc4c", "63119fda-e335-41fd-acba-8820b5b75d74", "39798e0d-f23d-47c1-8090-dad0b03a1a28" }; var fileName = @"C:\Temp\Logs" + Guid.NewGuid().ToString() + ".txt"; foreach (var eventid in eventIds) { var _containerName = "indexer-transaction-logs"; var remoteSourceFilePath = eventid + "\\txnLog.txt"; CloudBlobClient blobClient = BlobHelper.GetBlobClient(CloudStorageAccount.Parse(StorageConnectionString), true); CloudBlobContainer container = BlobHelper.GetBlobContainer(blobClient, _containerName); CloudBlockBlob blob = container.GetBlockBlobReference(remoteSourceFilePath); var ss = blob.OpenRead(); using (StreamReader sr = new StreamReader(ss)) { var log = sr.ReadToEnd(); File.AppendAllText(fileName, "===================================================" + Environment.NewLine + Environment.NewLine + log); File.AppendAllText(fileName, log); } } }
public Task <WorkflowDownload> DownloadBlob(int blobId) { // TODO: You must implement this helper method. It should retrieve blob info from your // database, based on the blobId. The record should contain the blobName, which you // should return as the result of this helper method. var blobName = GetBlobName(blobId); if (!String.IsNullOrEmpty(blobName)) { var container = BlobHelper.GetBlobContainer(); var blob = container.GetBlockBlobReference(blobName); // Download the blob into a memory stream. Notice that we're not putting the memory // stream in a using statement. This is because we need the stream to be open for the // API controller in order for the file to actually be downloadable. The closing and // disposing of the stream is handled by the Web API framework. var ms = new MemoryStream(); await blob.DownloadToStreamAsync(ms); // Strip off any folder structure so the file name is just the file name var lastPos = blob.Name.LastIndexOf('/'); var fileName = blob.Name.Substring(lastPos + 1, blob.Name.Length - lastPos - 1); // Build and return the download model with the blob stream and its relevant info var download = new BlobDownloadModel { BlobStream = ms, BlobFileName = fileName, BlobLength = blob.Properties.Length, BlobContentType = blob.Properties.ContentType }; return(download); } // Otherwise return(null); }
public static async Task <IActionResult> Run( [HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = "mobileKiosk/getEmployeesFaceUriList/{serialNumber}/{clientId}/{employeeUid}")] HttpRequest req, string serialNumber, string clientId, string employeeUid, ILogger logger) { try { var employeeId = Convert.ToInt64(employeeUid); string azureStorage = Environment.GetEnvironmentVariable(Constants.StorageConnectionStringVariable, EnvironmentVariableTarget.Process); blobHelper = new BlobHelper <EmployeeFaceData>(azureStorage); var blobCount = 1; var containerName = Constants.FaceServiceContainer + clientId; var blobContainer = await blobHelper.GetBlobContainer(containerName, logger); var result = await FaceServiceHelper.GetBlobUrisByContainer(blobContainer, clientId, employeeId, logger); return((ActionResult) new OkObjectResult(result)); } catch (Exception ex) { return(new BadRequestObjectResult("An error occured " + ex.Message)); } }
static async Task MainAsync(string[] args) { try { var container = await BlobHelper.GetBlobContainer(); FileInfo fi = new FileInfo(@"C:\Users\atahar2380\Pictures\Assignment\IntegrationLayer.jpg"); string imageName = Guid.NewGuid().ToString() + "_" + Path.GetFileName(fi.Name); CloudBlockBlob cloudBlockBlob = container.GetBlockBlobReference(imageName); cloudBlockBlob.Properties.ContentType = "image/jpg"; using (var stream = fi.OpenRead()) { await cloudBlockBlob.UploadFromStreamAsync(stream); await cloudBlockBlob.DeleteIfExistsAsync(); } } catch (Exception ex) { } }
private async Task <List <StationImageUploadModel> > UploadBlobsToAzure(IList <HttpContent> files, StationImageUploadModel uploadedModel) { // NOTE: FileData is a property of MultipartFileStreamProvider and is a list of multipart // files that have been uploaded and saved to disk in the Path.GetTempPath() location. foreach (var fileData in files) { if (!string.IsNullOrEmpty(fileData.Headers.ContentDisposition.FileName)) { string mediaType = fileData.Headers.ContentType.MediaType.ToString(); //If the file an image media type if (System.Text.RegularExpressions.Regex.IsMatch(mediaType, "image/\\S+")) { // Sometimes the filename has a leading and trailing double-quote character // when uploaded, so we trim it; otherwise, we get an illegal character exception var fileName = Path.GetFileName(fileData.Headers.ContentDisposition.FileName.Trim('"')); var path = HttpRuntime.AppDomainAppPath; string directoryName = Path.Combine(path, "StationImage"); if (!Directory.Exists(directoryName)) { Directory.CreateDirectory(@directoryName); } string filePath = Path.Combine(directoryName, fileName); //Deletion exists file if (File.Exists(filePath)) { File.Delete(filePath); } // Retrieve reference to a blob var blobContainer = BlobHelper.GetBlobContainer(); var blob = blobContainer.GetBlockBlobReference(fileName); bool blobExists = blob.Exists(); //if is doesn't exist, then add it. if (!blobExists) { // Set the blob content type blob.Properties.ContentType = fileData.Headers.ContentType.MediaType; Stream input = await fileData.ReadAsStreamAsync(); //Directory.CreateDirectory(@directoryName); using (Stream file = File.OpenWrite(filePath)) { input.CopyTo(file); //close file file.Close(); } // Upload file into blob storage, basically copying it from local disk into Azure using (var fs = File.OpenRead(filePath)) { long fileSizeInKB = (long)(fs.Length / 1024); //If the image is greater than 1 MB don't save it if (fileSizeInKB > 1001) { continue; } blob.UploadFromStream(fs); } // Delete local file from disk File.Delete(filePath); } // Create blob upload model with properties from blob info var stationImageUploadModel = new StationImageUploadModel { FileName = blob.Name, FileUrl = blob.Uri.AbsoluteUri, FileSizeInBytes = blob.Properties.Length, StationID = uploadedModel.StationID, User = uploadedModel.User, Primary = uploadedModel.Primary, ImageTypeID = uploadedModel.ImageTypeID, Description = uploadedModel.Description, PhysHabYear = uploadedModel.PhysHabYear }; // Add uploaded blob to the list Uploads.Add(stationImageUploadModel); } } } return(Uploads); }