public async Task RemoveFile(Guid id) { var model = await _context.ClamUserPersonalCategoryItems.FindAsync(id); var result = FilePathUrlHelper.DataFilePathFilterIndex(model.ItemPath, 4); var path = model.ItemPath.Substring(0, result); Directory.Delete(path, true); _context.ClamUserPersonalCategoryItems.Remove(model); await _context.SaveChangesAsync(); }
public async Task AddAsyncCategory(SectionAcademicRegister model) { ClamSectionAcademicCategory result = new ClamSectionAcademicCategory { //AcademicId = model.AcademicId, AcademicDisciplineDescription = model.AcademicDisciplineDescription, AcademicDisciplineTitle = model.AcademicDisciplineTitle }; // TODO: Add insert logic here await _context.ClamSectionAcademicCategories.AddAsync(result); Task.WaitAll(_context.SaveChangesAsync()); }
public async Task AddAsyncGenre(AreaUserMusicCategory model) { var result = _mapper.Map <ClamUserMusicCategory>(model); await _context.ClamUserMusicCategories.AddAsync(result); await _context.SaveChangesAsync(); }
public async Task AddAsyncTicket(AreaUserTicket model, string userName) { //var result = _mapper.Map<ClamUserSystemTicket>(model); var user = await _userManager.FindByNameAsync(userName); var ticketResponse = "Please be patient, will look into the matter as soon as possible."; var standardStatus = "Pending Review"; var standardDesignation = "Unassigned Member"; ClamUserSystemTicket result = new ClamUserSystemTicket() { TicketTitle = model.TicketTitle, TicketMessage = model.TicketMessage, TicketStatus = standardStatus, TicketResponse = ticketResponse, UserId = user.Id, DesignatedMember = standardDesignation, LastModified = DateTime.Now, DateCreated = DateTime.Now }; await _context.ClamUserSystemTickets.AddAsync(result); await _context.SaveChangesAsync(); }
public async Task <IActionResult> UploadDatabase() { if (!MultipartRequestHelper.IsMultipartContentType(Request.ContentType)) { ModelState.AddModelError("File", $"The request couldn't be processed (Error 1)."); // Log error return(BadRequest(ModelState)); } // Accumulate the form data key-value pairs in the request (formAccumulator). var formAccumulator = new KeyValueAccumulator(); var trustedFileNameForDisplay = string.Empty; var untrustedFileNameForStorage = string.Empty; var trustedFilePathStorage = string.Empty; var trustedFileNameForFileStorage = string.Empty; var streamedFileContent = new byte[0]; var streamedFilePhysicalContent = new byte[0]; // List Byte for file storage List <byte[]> filesByteStorage = new List <byte[]>(); List <string> filesNameStorage = new List <string>(); var fileStoredData = new Dictionary <string, byte[]>(); List <string> storedPaths = new List <string>(); List <string> storedPathDictionaryKeys = new List <string>(); // List to Submit List <ClamSectionAcademicSubCategoryItem> itemList = new List <ClamSectionAcademicSubCategoryItem>(); var boundary = MultipartRequestHelper.GetBoundary( MediaTypeHeaderValue.Parse(Request.ContentType), _defaultFormOptions.MultipartBoundaryLengthLimit); var reader = new MultipartReader(boundary, HttpContext.Request.Body); var section = await reader.ReadNextSectionAsync(); while (section != null) { var hasContentDispositionHeader = ContentDispositionHeaderValue.TryParse( section.ContentDisposition, out var contentDisposition); if (hasContentDispositionHeader) { if (MultipartRequestHelper .HasFileContentDisposition(contentDisposition)) { untrustedFileNameForStorage = contentDisposition.FileName.Value; // Don't trust the file name sent by the client. To display // the file name, HTML-encode the value. trustedFileNameForDisplay = WebUtility.HtmlEncode( contentDisposition.FileName.Value); if (!Directory.Exists(_targetFilePath)) { string path = String.Format("{0}", _targetFilePath); Directory.CreateDirectory(path); } //streamedFileContent = // await FileHelpers.ProcessStreamedFile(section, contentDisposition, // ModelState, _permittedExtentions, _fileSizeLimit); streamedFilePhysicalContent = await FileHelpers.ProcessStreamedFile( section, contentDisposition, ModelState, _permittedExtentions, _fileSizeLimit); filesNameStorage.Add(trustedFileNameForDisplay); filesByteStorage.Add(streamedFilePhysicalContent); fileStoredData.Add(trustedFileNameForDisplay, streamedFilePhysicalContent); if (!ModelState.IsValid) { return(BadRequest(ModelState)); } } else if (MultipartRequestHelper .HasFormDataContentDisposition(contentDisposition)) { // Don't limit the key name length because the // multipart headers length limit is already in effect. var key = HeaderUtilities .RemoveQuotes(contentDisposition.Name).Value; var encoding = GetEncoding(section); if (encoding == null) { ModelState.AddModelError("File", $"The request couldn't be processed (Error 2)."); // Log error return(BadRequest(ModelState)); } using (var streamReader = new StreamReader( section.Body, encoding, detectEncodingFromByteOrderMarks: true, bufferSize: 1024, leaveOpen: true)) { // The value length limit is enforced by // MultipartBodyLengthLimit var value = await streamReader.ReadToEndAsync(); if (string.Equals(value, "undefined", StringComparison.OrdinalIgnoreCase)) { value = string.Empty; } formAccumulator.Append(key, value); if (formAccumulator.ValueCount > _defaultFormOptions.ValueCountLimit) { // Form key count limit of // _defaultFormOptions.ValueCountLimit // is exceeded. ModelState.AddModelError("File", $"The request couldn't be processed (Error 3)."); // Log error return(BadRequest(ModelState)); } } } } // Drain any remaining section body that hasn't been consumed and // read the headers for the next section. section = await reader.ReadNextSectionAsync(); } // Bind form data to the model var formData = new FormData(); var formValueProvider = new FormValueProvider( BindingSource.Form, new FormCollection(formAccumulator.GetResults()), CultureInfo.CurrentCulture); var bindingSuccessful = await TryUpdateModelAsync(formData, prefix : "", valueProvider : formValueProvider); //trustedFilePathStorage = String.Format("{0}\\{1}\\{2}\\{3}", // //_targetFilePath, // _targetFolderPath, // formData.AcademicId, // formData.SubCategoryId, // Path.GetRandomFileName()); if (!bindingSuccessful) { ModelState.AddModelError("File", "The request couldn't be processed (Error 5)."); // Log error return(BadRequest(ModelState)); } // **WARNING!** // In the following example, the file is saved without // scanning the file's contents. In most production // scenarios, an anti-virus/anti-malware scanner API // is used on the file before making the file available // for download or for use by other systems. // For more information, see the topic that accompanies // this sample app. foreach (var item in fileStoredData) { trustedFilePathStorage = String.Format("{0}\\{1}\\{2}\\{3}", _targetFolderPath, formData.AcademicId, formData.SubCategoryId, Path.GetRandomFileName()); Directory.CreateDirectory(trustedFilePathStorage); using (var targetStream = System.IO.File.Create( Path.Combine(trustedFilePathStorage, item.Key))) { await targetStream.WriteAsync(item.Value); _logger.LogInformation( "Uploaded file '{TrustedFileNameForDisplay}' saved to " + "'{TargetFilePath}' as {TrustedFileNameForFileStorage}", item.Key, trustedFilePathStorage, item.Key); } itemList.Add(new ClamSectionAcademicSubCategoryItem() { ItemPath = Path.Combine(trustedFilePathStorage, item.Key), ItemTitle = item.Key, //ItemDescription = formData.Note, Size = item.Value.Length, DateAdded = DateTime.Now, SubCategoryId = formData.SubCategoryId, AcademicId = formData.AcademicId }); } //using (var targetStream = System.IO.File.Create( // Path.Combine(trustedFilePathStorage, trustedFileNameForDisplay))) //{ // await targetStream.WriteAsync(streamedFilePhysicalContent); // _logger.LogInformation( // "Uploaded file '{TrustedFileNameForDisplay}' saved to " + // "'{TargetFilePath}' as {TrustedFileNameForFileStorage}", // trustedFileNameForDisplay, trustedFilePathStorage, // trustedFileNameForDisplay); //} //var file = new ClamSectionAcademicSubCategoryItem() //{ // ItemPath = Path.Combine(trustedFilePathStorage, trustedFileNameForDisplay), // ItemTitle = untrustedFileNameForStorage, // //ItemDescription = formData.Note, // Size = streamedFilePhysicalContent.Length, // DateAdded = DateTime.Now, // SubCategoryId = formData.SubCategoryId, // AcademicId = formData.AcademicId //}; await _context.AddRangeAsync(itemList); await _context.SaveChangesAsync(); return(RedirectToAction("Episode", "Academia", new { id = formData.AcademicId, said = formData.SubCategoryId })); }
public async Task AddAsyncGenre(SectionTVShowCategory model) { var trustedFileNameForDisplay = string.Empty; var trustedFilePathForStorage = string.Empty; var streamedFilePhysicalContent = new byte[0]; if (!ModelState.IsValid) { ModelState.AddModelError("Genre", $"The request couldn't be processed (Error 1)."); // Log error } streamedFilePhysicalContent = await FileHelpers.ProcessFormFile <StreamFileUploadDatabase>( model.FormFile, ModelState, _permittedExtentions, _fileSizeLimit); if (!ModelState.IsValid) { ModelState.AddModelError("Genre", $"The request couldn't be processed (Error 1)."); // Log error } trustedFilePathForStorage = String.Format("{0}\\{1}\\{2}", _targetImagePath, Guid.NewGuid().ToString(), Path.GetRandomFileName()); trustedFileNameForDisplay = String.Format("{0}_{1}", Guid.NewGuid(), WebUtility.HtmlEncode(model.FormFile.FileName)); Directory.CreateDirectory(trustedFilePathForStorage); using (var targetStream = System.IO.File.Create( Path.Combine(trustedFilePathForStorage, trustedFileNameForDisplay))) { await targetStream.WriteAsync(streamedFilePhysicalContent); //_logger.LogInformation( // "Uploaded file '{TrustedFileNameForDisplay}' saved to " + // "'{TargetFilePath}' as {TrustedFileNameForFileStorage}", // trustedFileNameForDisplay, trustedFilePathForStorage, // trustedFileNameForDisplay); } // TODO: Add insert logic here ClamSectionTVShowCategory result = new ClamSectionTVShowCategory { Genre = model.Genre, ItemPath = Path.Combine(trustedFilePathForStorage, trustedFileNameForDisplay) }; await _context.ClamSectionTVShowCategories.AddAsync(result); Task.WaitAll(_context.SaveChangesAsync()); }
public void ToDatabase(List <ClamUserPersonalCategoryItem> files) { Task.WaitAll(_context.AddRangeAsync(files)); Task.WaitAll(_context.SaveChangesAsync()); }
public async Task AddAsyncInterests(ProjectImageData model, ModelStateDictionary modelState, string userName) { var user = await _userManager.FindByNameAsync(userName); var trustedFileNameForDisplay = string.Empty; var streamedFileImageContent = new byte[0]; var untrustedFileNameForStorage = string.Empty; var trustedFilePathStorage = string.Empty; var trustedFileNameForFileStorage = string.Empty; var test = string.Empty; streamedFileImageContent = await FileHelpers.ProcessFormFile <ProjectFormData>( model.File, modelState, _permittedExtentions, _fileSizeLimit); if (!modelState.IsValid) { test = "ModelState is Invalid"; } untrustedFileNameForStorage = model.File.FileName; // Don't trust the file name sent by the client. To display // the file name, HTML-encode the value. trustedFileNameForDisplay = WebUtility.HtmlEncode( model.File.FileName); // Bind form data to the model var keyPathFolder = FilePathUrlHelper.GenerateKeyPath(user.Id); var generateKeyFolder = GenerateSecurity.Encode(user.Id); // Path Location & Directory Check trustedFilePathStorage = String.Format("{0}\\{1}\\{2}\\{3}", _targetFolderPath, keyPathFolder, generateKeyFolder, Path.GetRandomFileName()); Directory.CreateDirectory(trustedFilePathStorage); using (var fileStream = new FileStream(Path.Combine(trustedFilePathStorage, untrustedFileNameForStorage), FileMode.Create, FileAccess.Write)) { await model.File.CopyToAsync(fileStream); fileStream.Close(); } ClamProjectInterestsImageDisplay result = new ClamProjectInterestsImageDisplay() { Title = Path.GetFileNameWithoutExtension(model.File.FileName), ImageLocation = Path.Combine(trustedFilePathStorage, untrustedFileNameForStorage), Status = bool.Parse(model.Status), UserId = user.Id, LastModified = DateTime.Now, DateCreated = DateTime.Now }; await _context.AddAsync(result); await _context.SaveChangesAsync(); }
public async Task <IActionResult> UploadDatabase() { if (!MultipartRequestHelper.IsMultipartContentType(Request.ContentType)) { ModelState.AddModelError("File", $"The request couldn't be processed (Error 1)."); // Log error return(BadRequest(ModelState)); } // Accumulate the form data key-value pairs in the request (formAccumulator). var formAccumulator = new KeyValueAccumulator(); var trustedFileNameForDisplay = string.Empty; var untrustedFileNameForStorage = string.Empty; var streamedFileContent = new byte[0]; var boundary = MultipartRequestHelper.GetBoundary( MediaTypeHeaderValue.Parse(Request.ContentType), _defaultFormOptions.MultipartBoundaryLengthLimit); var reader = new MultipartReader(boundary, HttpContext.Request.Body); var section = await reader.ReadNextSectionAsync(); while (section != null) { var hasContentDispositionHeader = ContentDispositionHeaderValue.TryParse( section.ContentDisposition, out var contentDisposition); if (hasContentDispositionHeader) { if (MultipartRequestHelper .HasFileContentDisposition(contentDisposition)) { untrustedFileNameForStorage = contentDisposition.FileName.Value; // Don't trust the file name sent by the client. To display // the file name, HTML-encode the value. trustedFileNameForDisplay = WebUtility.HtmlEncode( contentDisposition.FileName.Value); streamedFileContent = await FileHelpers.ProcessStreamedFile(section, contentDisposition, ModelState, _permittedExtentions, _fileSizeLimit); if (!ModelState.IsValid) { return(BadRequest(ModelState)); } } else if (MultipartRequestHelper .HasFormDataContentDisposition(contentDisposition)) { // Don't limit the key name length because the // multipart headers length limit is already in effect. var key = HeaderUtilities .RemoveQuotes(contentDisposition.Name).Value; var encoding = GetEncoding(section); if (encoding == null) { ModelState.AddModelError("File", $"The request couldn't be processed (Error 2)."); // Log error return(BadRequest(ModelState)); } using (var streamReader = new StreamReader( section.Body, encoding, detectEncodingFromByteOrderMarks: true, bufferSize: 1024, leaveOpen: true)) { // The value length limit is enforced by // MultipartBodyLengthLimit var value = await streamReader.ReadToEndAsync(); if (string.Equals(value, "undefined", StringComparison.OrdinalIgnoreCase)) { value = string.Empty; } formAccumulator.Append(key, value); if (formAccumulator.ValueCount > _defaultFormOptions.ValueCountLimit) { // Form key count limit of // _defaultFormOptions.ValueCountLimit // is exceeded. ModelState.AddModelError("File", $"The request couldn't be processed (Error 3)."); // Log error return(BadRequest(ModelState)); } } } } // Drain any remaining section body that hasn't been consumed and // read the headers for the next section. section = await reader.ReadNextSectionAsync(); } // Bind form data to the model var formData = new FormData(); var formValueProvider = new FormValueProvider( BindingSource.Form, new FormCollection(formAccumulator.GetResults()), CultureInfo.CurrentCulture); var bindingSuccessful = await TryUpdateModelAsync(formData, prefix : "", valueProvider : formValueProvider); if (!bindingSuccessful) { ModelState.AddModelError("File", "The request couldn't be processed (Error 5)."); // Log error return(BadRequest(ModelState)); } // **WARNING!** // In the following example, the file is saved without // scanning the file's contents. In most production // scenarios, an anti-virus/anti-malware scanner API // is used on the file before making the file available // for download or for use by other systems. // For more information, see the topic that accompanies // this sample app. var file = new ClamSectionAcademicSubCategoryItem() { ItemPath = null, ItemTitle = untrustedFileNameForStorage, ItemDescription = formData.Note, Size = streamedFileContent.Length, DateAdded = DateTime.Now, SubCategoryId = new Guid("8d7af8fa-4659-4aef-1746-08d7d7789232") }; _context.Add(file); await _context.SaveChangesAsync(); return(RedirectToAction(nameof(Index))); }