public async Task <IActionResult> RefreshDataPackage(string packageName) { try { var dataPackage = Program.AvailablePackages.FirstOrDefault(x => x.PackageName == packageName); if (dataPackage != null) { var newDataPackage = new TelemetryPackage() { PackageName = packageName, PackageData = await BlobStorageService.GetData(BlobStorageService.DataContainerName, packageName) }; Program.AvailablePackages.Remove(dataPackage); Program.AvailablePackages.Add(newDataPackage); } return(RedirectToAction("Index")); } catch (Exception ex) { ViewData["message"] = ex.Message; ViewData["trace"] = ex.StackTrace; return(View("Error")); } }
public async Task <string> LoadData(string blobName) { try { var dataPackage = Program.AvailablePackages.FirstOrDefault(x => x.PackageName == blobName); if (dataPackage == null) { Program.CurrentData = new TelemetryPackage() { PackageName = blobName, PackageData = await BlobStorageService.GetData(BlobStorageService.DataContainerName, blobName) }; Program.AvailablePackages.Add(Program.CurrentData); } else { Program.CurrentData = dataPackage; } return(JsonConvert.SerializeObject(Program.CurrentData.PackageData)); } catch (Exception ex) { return($"Error: {ex.Message}"); } }
public async Task <IActionResult> Index() { try { var availableData = await BlobStorageService.GetBlobList(BlobStorageService.DataContainerName); if (Program.CurrentData == null) { Program.CurrentData = new TelemetryPackage() { PackageName = availableData.LastOrDefault(), PackageData = await BlobStorageService.GetData(BlobStorageService.DataContainerName, availableData.LastOrDefault()) }; Program.AvailablePackages.Add(Program.CurrentData); } var model = new DashboardViewModel(); model.AvailableData = availableData; model.CurrentData = Program.CurrentData.PackageData; ViewBag.Context = "Home"; return(View(model)); } catch (Exception ex) { ViewData["message"] = ex.Message; ViewData["trace"] = ex.StackTrace; return(View("Error")); } }
private Dictionary <string, string> GetDictFromBlob(string name) { string json = BlobStorageService.Load(name); Dictionary <string, string> Dict = JsonConvert.DeserializeObject <Dictionary <string, string> >(json); return(Dict); }
public async Task <IActionResult> DeleteDataPackage(string packageName) { try { await BlobStorageService.DeleteBlockBlob(BlobStorageService.DataContainerName, packageName); var dataPackage = Program.AvailablePackages.FirstOrDefault(x => x.PackageName == packageName); if (dataPackage != null) { if (Program.CurrentData == dataPackage) { Program.CurrentData = null; } Program.AvailablePackages.Remove(dataPackage); } return(RedirectToAction("Index")); } catch (Exception ex) { ViewData["message"] = ex.Message; ViewData["trace"] = ex.StackTrace; return(View("Error")); } }
public IActionResult Create(Product product) { if (ModelState.IsValid) { #region Read File Content var uploads = Path.Combine(env.WebRootPath, "uploads\\"); bool exists = Directory.Exists(uploads); if (!exists) { Directory.CreateDirectory(uploads); } // https://www.c-sharpcorner.com/article/upload-files-in-azure-blob-storage-using-asp-net-core/ // Code has been copied from the above link but there was a bug in it - seen below var fileName = Path.GetFileName(product.File.FileName); string mimeType = product.File.ContentType; byte[] fileData = System.IO.File.ReadAllBytes(@"C:\\Users\\robjs\\Desktop\\" + product.File.FileName); BlobStorageService objBlobService = new BlobStorageService(); product.ImagePath = objBlobService.UploadFileToBlob(product.File.FileName, fileData, mimeType); #endregion _context.ProductRepo.Add(product); _context.SaveChanges(); return(RedirectToAction(nameof(Index))); } return(View(product)); }
public void ConfigureServices(IServiceCollection services) { services .AddIdentity <BenchUser, IdentityRole>(cfg => { cfg.User.RequireUniqueEmail = true; }) .AddRoles <IdentityRole>() .AddEntityFrameworkStores <BenchContext>(); services.AddDbContext <BenchContext>(cfg => { string connecitonString = _config.GetConnectionString("BenchConnectionString"); cfg.UseSqlServer(connecitonString); }); services.AddTransient <BenchSeeder>(); services.AddTransient <IAssetService, WalksService>(); services.AddOptions(); services.Configure <AzureStorageConfig>(_config.GetSection("AzureStorageConfig")); services.AddSingleton <IStorageService>(serviceProvider => { var blobStorage = new BlobStorageService(serviceProvider.GetService <IOptions <AzureStorageConfig> >()); blobStorage.ConfigureBlobStorage().GetAwaiter().GetResult(); return(blobStorage); }); services.AddSingleton <ITableStorageService, TableStorageService>(); services.AddMvc(); }
public void Then_Expected_Method_IsCalled() { BlobStorageService.Received(1).DownloadFileAsync(Arg.Is <BlobStorageData>(x => x.ContainerName == DocumentType.Documents.ToString() && x.BlobFileName == FileName && x.SourceFilePath == $"{BlobStorageConstants.TechSpecFolderName}/{FolderName}")); }
public List <string> GetMoviePosterDetails(HtmlNode body, string movieName, ref List <string> posterPath, ref string thumbnailPath) { posterPath = posterPath ?? new List <string>(); thumbnailPath = string.Empty; bool isThumbnailDownloaded = false; var thumbListNode = helper.GetElementWithAttribute(body, "div", "class", "media_index_thumb_list"); if (thumbListNode != null) { var thumbnails = thumbListNode.Elements("a"); if (thumbnails != null) { //int imageCounter = GetMaxImageCounter(movieName); int imageCounter = new BlobStorageService().GetImageFileCount(BlobStorageService.Blob_ImageContainer, movieName.Replace(" ", "-").ToLower() + "-poster-"); foreach (HtmlNode thumbnail in thumbnails) { if (thumbnail.Attributes["itemprop"] != null && thumbnail.Attributes["itemprop"].Value == "thumbnailUrl") { string href = thumbnail.Attributes["href"].Value; CrawlPosterImagePath("http://imdb.com" + href, movieName, imageCounter, ref isThumbnailDownloaded, ref posterPath, ref thumbnailPath); imageCounter++; } } } } return(posterPath); }
private async Task <IActionResult> UploadCvFile(ApplyViewModel applyViewModel) { var formFile = applyViewModel.RealFile; if ((formFile == null || formFile.Length <= 0) && String.IsNullOrEmpty(applyViewModel.CvFile)) { TempData["BadUpload"] = "File not specified or upload failed"; return(View("Apply", applyViewModel)); } TempData["BadUpload"] = null; if (!ModelState.IsValid) { return(View("Apply", applyViewModel)); } if (formFile != null) { var uploadSuccess = false; string uploadedUri = null; using (var stream = formFile.OpenReadStream()) { (uploadSuccess, uploadedUri) = await BlobStorageService.UploadToBlob(formFile.FileName, _configuration["storageconnectionstring"], null, stream); } if (!uploadSuccess) { TempData["BadUpload"] = "File not specified or upload failed"; return(View("Apply", applyViewModel)); } applyViewModel.CvFile = uploadedUri; } return(null); }
public override void Given() { _fileStream = null; FileName = null; BlobStorageService.DownloadFileAsync(Arg.Any <BlobStorageData>()).Returns(_fileStream); Loader = new DocumentLoader(Logger, BlobStorageService); }
public IHttpActionResult Get(string id) { TableOperation retrieveOperation = TableOperation.Retrieve <VideoEntity>(partitionName, id); TableResult retrievedResult = table.Execute(retrieveOperation); // Construct response including a new DTO as apprporiatte if (retrievedResult.Result == null) { return(NotFound()); } else { CloudBlobContainer blobContainer = BlobStorageService.getCloudBlobContainer(); //CloudBlockBlob blob = blobContainer.GetBlockBlobReference(sample.SampleMp4Blob); VideoEntity sample = (VideoEntity)retrievedResult.Result; // Setting up a video after being PUT and then create it Blob var sampleBlob = BlobStorageService.getCloudBlobContainer().GetBlockBlobReference("origin/" + sample.Mp4Blob); Stream blobStream = sampleBlob.OpenRead(); HttpResponseMessage message = new HttpResponseMessage(HttpStatusCode.OK); message.Content = new StreamContent(blobStream); message.Content.Headers.ContentLength = sampleBlob.Properties.Length; message.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("video/mp4"); message.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment") { FileName = sampleBlob.Name, Size = sampleBlob.Properties.Length }; return(ResponseMessage(message)); } }
public async Task <ActionResult> Upload(HttpPostedFileBase document) { // Ids used in the seed method Guid customerId = Guid.Parse("82CEAD1F-E3FA-4DAB-BFFA-276845FB7E72"); Guid userId = Guid.Parse("2A37108E-56AF-4C18-99C4-415191591CD9"); var blobStorageService = new BlobStorageService(); var documentId = Guid.NewGuid(); var path = await blobStorageService.UploadDocument(document, customerId, documentId); var dbContext = new DashDocsContext(); dbContext.Documents.Add(new Document { Id = documentId, DocumentName = Path.GetFileName(document.FileName).ToLower(), OwnerId = userId, CreatedOn = DateTime.UtcNow, BlobPath = path }); await dbContext.SaveChangesAsync(); return(RedirectToAction("Index")); }
public static async Task <IActionResult> Run( [HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = "workflows/{workflowId}/upload")] HttpRequest req, ILogger log, int workflowId) { BlobStorageService objBlobService = new BlobStorageService("uploads"); var file = req.Form.Files[0]; byte[] bytes = null; if (file.Length > 0) { string fileName = ContentDispositionHeaderValue.Parse(file.ContentDisposition).FileName.Trim('"'); string fileSize = ContentDispositionHeaderValue.Parse(file.ContentDisposition).Size.ToString(); string ext = Path.GetExtension(fileName); using (MemoryStream ms = new MemoryStream()) { file.OpenReadStream().CopyTo(ms); bytes = ms.ToArray(); } var filePath = await objBlobService.UploadFileToBlobAsync(fileName, bytes, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"); using (var ds = new DocumentService()) { return(new OkObjectResult(await ds.CreateDocument(fileName, fileSize, bytes, ext, workflowId, filePath))); } } return(new OkObjectResult(new { Message = "No file selected" })); }
public async Task <IActionResult> CreateRole(AdminViewModel model) { if (!_context.Roles.Any(r => r.Name == model.Role.RoleName)) { var role = new AppRole { Name = model.Role.RoleName }; var result = await _roleManager.CreateAsync(role); if (result.Succeeded) { ViewBag.Message1 = "Role created"; // create blob container as well BlobStorageService blobStorageService = new BlobStorageService(); blobStorageService.CreateContainer(model.Role.RoleName); } else { ViewBag.Message1 = "Role not created"; } } else { ViewBag.Message1 = "Role already exists"; } return(View("Index")); }
private async void BtnPick_Clicked(object sender, EventArgs e) { await CrossMedia.Current.Initialize(); try { MediaFile file = await CrossMedia.Current.PickPhotoAsync(new PickMediaOptions { PhotoSize = PhotoSize.Medium, }); if (file == null) { return; } imgChoosed.Source = ImageSource.FromStream(() => { var imageStram = file.GetStream(); return(imageStram); }); fileName = await BlobStorageService.UploadBlob(file, ".jpg"); } catch (Exception ex) { Debug.WriteLine(ex.Message); } }
public async Task <ActionResult> Upload(HttpPostedFileBase document) { var blobStorageService = new BlobStorageService(); var documentId = Guid.NewGuid(); var path = await blobStorageService.UploadDocumentAsync(document, DashDocsClaims.CustomerId, documentId); var dbContext = new DashDocsContext(); var documentModel = new Document { Id = documentId, DocumentName = Path.GetFileName(document.FileName).ToLower(), OwnerId = DashDocsClaims.UserId, CreatedOn = DateTime.UtcNow, BlobPath = path }; dbContext.Documents.Add(documentModel); await dbContext.SaveChangesAsync(); var doc = new DocumentViewModel { DocumentId = documentModel.Id, Owner = DashDocsClaims.DisplayName, CreatedOn = documentModel.CreatedOn, DocumentName = documentModel.DocumentName, }; var redisService = new RedisService(); await redisService.UpdateDocumentCacheAsync(DashDocsClaims.CustomerId, doc); return(RedirectToAction("Index")); }
public async Task <IActionResult> SaveChanges(int appId, int offerId, string email, string phone, IFormFile file) { var application = _applicationData.FindById(appId); if (application == null) { return(View("NotFound")); } string uploadedUri = null; if (file != null) { var uploadSuccess = false; using (var stream = file.OpenReadStream()) { (uploadSuccess, uploadedUri) = await BlobStorageService.UploadToBlob(file.FileName, _configuration["storageconnectionstring"], null, stream); } if (uploadSuccess) { application.CvFile = uploadedUri; } } PhoneAttribute phoneAttr = new PhoneAttribute(); bool phoneValid = phoneAttr.IsValid(phone); EmailAddressAttribute emailAttr = new EmailAddressAttribute(); bool emailValid = emailAttr.IsValid(email); bool emailFree = !_jobOfferData.CheckIfEmailIsTaken(email, offerId); if (email == application.CommunicationEmail) { emailFree = true; } bool success = false; if (phoneValid && emailValid && emailFree) { application.Phone = phone; application.CommunicationEmail = email; _applicationData.Update(application); _applicationData.Commit(); success = true; } var result = Json(new { success, phoneValid, emailValid, emailFree, uploadedUri }); System.Threading.Thread.Sleep(700); return(result); }
public ActionResult CheckExist() { BlobStorageService svBlob = new BlobStorageService(); var exist = svBlob.Exists("Manual/mail-month.txt"); var notexist = svBlob.Exists("Manual/mail-month2.txt"); return(Json(new { exist = exist, notexist = notexist }, JsonRequestBehavior.AllowGet)); }
public override void Given() { BlobStorageService.DownloadFileAsync(Arg.Is <BlobStorageData>(x => x.ContainerName == DocumentType.Documents.ToString() && x.BlobFileName == FileName && x.SourceFilePath == $"{BlobStorageConstants.TechSpecFolderName}/{FolderName}")) .Returns(new MemoryStream()); }
protected async override void OnAppearing() { base.OnAppearing(); Loading(true); AlbumListView.ItemsSource = await BlobStorageService.GetBlobList(); Loading(false); }
public SettingsController(IHostingEnvironment hostingEnvironment, IOptions <StorageValues> storageValues) { _hostingEnvironment = hostingEnvironment; _storageSettings = storageValues.Value; _blobStorageService = new BlobStorageService(_storageSettings.StorageAccountCs, _storageSettings.ContainerName); _tableStorageService = new TableStorageService(_storageSettings.StorageAccountCs, _storageSettings.TableName); }
/// <summary> /// Initializes a new instance of the <see cref="MetaWeblogHandler" /> class. /// </summary> /// <exception cref="BlogSystemException">unable to create container</exception> /// <exception cref="RahulRai.Websites.Utilities.Common.Exceptions.BlogSystemException">unable to create container</exception> public MetaWeblogHandler() { TraceUtility.LogInformation("Metawebloghander started initializing"); try { if (null == this.metaweblogTable) { this.metaweblogTable = new AzureTableStorageService <TableBlogEntity>( this.connectionString, this.blogTableName, AzureTableStorageAssist.ConvertEntityToDynamicTableEntity, AzureTableStorageAssist.ConvertDynamicEntityToEntity <TableBlogEntity>); this.metaweblogTable.CreateStorageObjectAndSetExecutionContext(); TraceUtility.LogInformation("Blog table created"); } if (null == this.mediaStorageService) { this.mediaStorageService = new BlobStorageService(this.connectionString); if (FileOperationStatus.FolderCreated != this.mediaStorageService.CreateContainer( this.blogResourceContainerName, VisibilityType.FilesVisibleToAll)) { TraceUtility.LogWarning("Resource container could not be created"); throw new BlogSystemException("unable to create container"); } } if (null == this.azureQueueService) { this.azureQueueService = new AzureQueueService(this.connectionString, this.queueName); } if (null != this.searchService) { return; } this.searchService = new AzureSearchService( this.searchServiceName, this.searchServiceKey, ApplicationConstants.SearchIndex); TraceUtility.LogInformation("Search service initialized"); } catch (BlogSystemException) { //// This is a custom exception. Throw it again. throw; } catch (Exception exception) { TraceUtility.LogError(exception); throw new BlogSystemException("failed to initialize"); } }
public KeyRotationHelper(ICosmosDbService cosmosDbService, BlobStorageService blobStorageService, IKeyVaultClient keyVaultClient, IConfiguration configuration, ILogger <KeyRotationHelper> logger) { this.cosmosDbService = cosmosDbService; this.blobStorageService = blobStorageService; this.keyVaultClient = keyVaultClient; this.configuration = configuration; this.logger = logger; this.RetryCosmosPolicy = this.GetCosmosRetryPolicy(); this.RetryBlobPolicy = GetBlobRetryPolicy(); }
private void CompleteImageComarision(string actualImageContainer, string actualImage, string referenceImage, string referenceImageContainer) { var df = new BlobStorageService(); var motionDetector = new MotionDetector(); motionDetector.ProcessFrame(df.ReadImageContent(referenceImage, referenceImageContainer)); var result = new ImageComparisionResult(); result.UploadImageAfterProcess(motionDetector.ProcessFrame(df.ReadImageContent(actualImage, actualImageContainer)), actualImageContainer, actualImage); }
public IActionResult DeleteConfirmed(int id) { var product = _context.ProductRepo.GetById(id); BlobStorageService objBlob = new BlobStorageService(); objBlob.DeleteBlobData(product.ImagePath); _context.ProductRepo.Delete(product); _context.SaveChanges(); return(RedirectToAction(nameof(Index))); }
public async Task <FileResult> Download(Guid documentId) { var dbContext = new DashDocsContext(); var document = await dbContext.Documents.SingleAsync(d => d.Id == documentId); var blobStorageService = new BlobStorageService(); var content = await blobStorageService.DownloadDocumentAsync(documentId, DashDocsClaims.CustomerId); return(File(content.Value, System.Net.Mime.MediaTypeNames.Application.Octet, content.Key)); }
public ActionResult TestBlob(string name) { BlobStorageService svBlob = new BlobStorageService(); svBlob.DeleteBlobInDir(name); ViewBag.Path = "Success"; ViewBag.Exist = true; return(View()); }
public ActionResult CheckExist(string name) { BlobStorageService svBlob = new BlobStorageService(); ViewBag.Path = name; ViewBag.Exist = svBlob.Exists(name); return(View("TestBlob")); }
// This function will get triggered/executed when a new message is written // on an Azure Queue called queue. public static void ProcessQueueMessage( [QueueTrigger("videomaker")] VideoEntity videoInQueue, [Table("Videos", "{PartitionKey}", "{RowKey}")] VideoEntity videoInTable, [Table("Videos")] CloudTable tableBinding, TextWriter logger) { CloudStorageAccount storageAccount; CloudTableClient tableClient; storageAccount = CloudStorageAccount.Parse(ConfigurationManager.ConnectionStrings["AzureStorage"].ToString()); tableClient = storageAccount.CreateCloudTableClient(); tableBinding = tableClient.GetTableReference("Videos"); // Create a retrieve operation that takes a video entity. TableOperation getOperation = TableOperation.Retrieve <VideoEntity>("Video_Partition", videoInQueue.PartitionKey); // Execute the retrieve operation. TableResult getOperationResult = tableBinding.Execute(getOperation); videoInTable = (VideoEntity)getOperationResult.Result; logger.WriteLine("Video Generated started..."); var inputBlob = BlobStorageService.getCloudBlobContainer().GetBlockBlobReference("origin/" + videoInTable.Mp4Blob); inputBlob.FetchAttributes(); String videoBlobName = string.Format("{0}{1}", Guid.NewGuid(), ".mp4"); var outputBlob = BlobStorageService.getCloudBlobContainer().GetBlockBlobReference("updated/" + videoBlobName); using (Stream input = inputBlob.OpenRead()) using (Stream output = outputBlob.OpenWrite()) { ConvertVideoToPreviewMP4(input, output, 20); outputBlob.Properties.ContentType = "video/mp4"; if (inputBlob.Metadata.ContainsKey("Title")) { outputBlob.Metadata["Title"] = inputBlob.Metadata["Title"]; videoInTable.Title = inputBlob.Metadata["Title"]; } else { outputBlob.Metadata["Title"] = " "; } } videoInTable.SampleMp4Blob = videoBlobName; videoInTable.SampleDate = DateTime.Now; var updateOperation = TableOperation.InsertOrReplace(videoInTable); // Execute the insert operation. tableBinding.Execute(updateOperation); logger.WriteLine("GeneratePreview() finished..."); }