remember the code below i will pass the front codes and then ask multiple questions…
- User
remember the code below i will pass the front codes and then ask multiple questions using System; using System.Collections.Generic; using System.Linq; using Mining.DataAccess.Data.Repository.IRepository; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; using System.IO; using Mining.Models.ViewModels; using Microsoft.AspNetCore.Http.Features; using Newtonsoft.Json; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Logging;
namespace Mining.App.Areas.Admin.Mines.Pages.SampleAnalyze { public class UpsertModel : PageModel { private readonly IUnitOfWork _unitOfWork; private readonly IWebHostEnvironment _hostingEnvironment; private readonly ILogger _logger; public UpsertModel(IUnitOfWork unitOfWork, IWebHostEnvironment hostingEnvironment, ILogger logger) { _unitOfWork = unitOfWork; _hostingEnvironment = hostingEnvironment; _logger = logger; }
[BindProperty] public SampleAnalyzeVM SampleAnalyzeObj { get; set; } public SampleAnalyzeAnalyzeTypeVM SampleAnalyzeAnalyzeTypeObj { get; set; } public SampleAnalyzeAnalyzeTypeVM SampleAnalyzeAnalyzeTypeObj2 { get; set; } [BindProperty] public List<SampleAnalyzeAnalyzeTypeVM> DeniedSampleAnalyzeAnalyzeTypeObjList { get; set; } [BindProperty] public List<SampleAnalyzeAnalyzeTypeVM> DeniedSampleAnalyzeAnalyzeTypeObjList1 { get; set; } [BindProperty] public SampleAnalyzeFileVM SampleAnalyzeFileObj { get; set; } public SampleAnalyzeFileVM SampleAnalyzeFileObj2 { get; set; } public IActionResult OnGet(int? id) { SampleAnalyzeObj = new SampleAnalyzeVM { MineOrRangeList = _unitOfWork.MineOrRange.GetMineOrRangeListForDropdown(), LaboratoryList = _unitOfWork.Laboratory.GetLaboratoryListForDropdown(), SampleTypeList = _unitOfWork.SampleType.GetSampleTypeListForDropdown(), SampleStatusList = _unitOfWork.SampleStatus.GetSampleStatusListForDropdown(), SampleAnalyze = new Models.Entities.Mines.SampleAnalyze() }; if (id != null) { SampleAnalyzeObj.SampleAnalyze = _unitOfWork.SampleAnalyze.GetFirstOrDefault(u => u.Id == id); if (SampleAnalyzeObj == null) { return NotFound(); } var previousFiles = _unitOfWork.SampleAnalyzeFile.GetAll(u => u.SampleAnalyzeId == id.Value).ToList(); dataList = previousFiles.Select(file => new DataType { File = file.File, FileName = file.FileName, FileExtention = file.FileExtention }).ToList(); } return Page(); } [BindProperty] public IFormFile UploadfileResult { get; set; } [BindProperty] public IFormFile UploadfileInvoice { get; set; } [BindProperty] public IFormFile UploadedFiles { get; set; } public class DataType { public string File { get; set; } public string FileName { get; set; } public string FileExtention { get; set; } } public class PostDataFile { public List<DataType> list { get; set; } } public static JsonResult jsonResult = new JsonResult(""); public static List<DataType> dataList = new List<DataType>(); public static List<DataType> tempDataList = new List<DataType>(); public static List<DataType> tempDataList2 = new List<DataType>(); public static bool firstReload = true; public IActionResult OnPost() { if (User.IsInRole(Mining.Utility.SD.MineLab)) { string ContentRootPath = _hostingEnvironment.WebRootPath; if (!ModelState.IsValid) { //SampleAnalyzeObj.SampleAnalyze = new Models.Entities.Mines.SampleAnalyze(); SampleAnalyzeObj = new SampleAnalyzeVM { MineOrRangeList = _unitOfWork.MineOrRange.GetMineOrRangeListForDropdown(), LaboratoryList = _unitOfWork.Laboratory.GetLaboratoryListForDropdown(), SampleTypeList = _unitOfWork.SampleType.GetSampleTypeListForDropdown(), SampleStatusList = _unitOfWork.SampleStatus.GetSampleStatusListForDropdown(), SampleAnalyze = new Models.Entities.Mines.SampleAnalyze() }; return Page(); } if (SampleAnalyzeObj.SampleAnalyze.Id == 0) { _unitOfWork.SampleAnalyze.Add(SampleAnalyzeObj.SampleAnalyze); _unitOfWork.Save(); if (UploadfileResult != null) { var fileResult = Path.Combine(_hostingEnvironment.WebRootPath, @"Files\SamplesAnalyze\", UploadfileResult.FileName); if (System.IO.File.Exists(Path.Combine(ContentRootPath, @"Files\SamplesAnalyze\" + SampleAnalyzeObj.SampleAnalyze.Id)) == false) { System.IO.Directory.CreateDirectory(Path.Combine(ContentRootPath, @"Files\SamplesAnalyze\" + SampleAnalyzeObj.SampleAnalyze.Id)); } //var fileResult = Path.Combine(_hostingEnvironment.ContentRootPath, @"Files\SamplesAnalyze\", UploadfileResult.FileName); if (fileResult.Length > 0) { string fileName = Guid.NewGuid().ToString(); var uploads = Path.Combine(ContentRootPath, @"Files\SamplesAnalyze\" + SampleAnalyzeObj.SampleAnalyze.Id); var extention = Path.GetExtension(UploadfileResult.FileName); //using (var fileStream = new FileStream(fileResult, FileMode.Create)) using (var fileStream = new FileStream(Path.Combine(uploads, fileName + extention), FileMode.Create)) { UploadfileResult.CopyTo(fileStream); } SampleAnalyzeObj.SampleAnalyze.ResultFile = fileName + extention; } } if (UploadfileInvoice != null) { var fileInvoice = Path.Combine(_hostingEnvironment.WebRootPath, @"Files\SamplesAnalyze\", UploadfileInvoice.FileName); if (System.IO.File.Exists(Path.Combine(ContentRootPath, @"Files\SamplesAnalyze\" + SampleAnalyzeObj.SampleAnalyze.Id)) == false) { System.IO.Directory.CreateDirectory(Path.Combine(ContentRootPath, @"Files\SamplesAnalyze\" + SampleAnalyzeObj.SampleAnalyze.Id)); } //var fileInvoice= Path.Combine(_hostingEnvironment.ContentRootPath, @"Files\SamplesAnalyze\", UploadfileResult.FileName); if (fileInvoice.Length > 0) { string fileName = Guid.NewGuid().ToString(); var uploads = Path.Combine(ContentRootPath, @"Files\SamplesAnalyze\" + SampleAnalyzeObj.SampleAnalyze.Id); var extention = Path.GetExtension(UploadfileInvoice.FileName); //using (var fileStream = new FileStream(fileResult, FileMode.Create)) using (var fileStream = new FileStream(Path.Combine(uploads, fileName + extention), FileMode.Create)) { UploadfileInvoice.CopyTo(fileStream); } SampleAnalyzeObj.SampleAnalyze.InvoiceFile = fileName + extention; } } _unitOfWork.SampleAnalyze.Update(SampleAnalyzeObj.SampleAnalyze); _unitOfWork.Save(); int SampleAnalyzeId = SampleAnalyzeObj.SampleAnalyze.Id; PrepareSampleAnalyzeAnalyzeType(SampleAnalyzeId); //tempDataList.Clear(); PrepareSampleAnalyzeFile(SampleAnalyzeId); } else { var objFromDb = _unitOfWork.SampleAnalyze.Get(SampleAnalyzeObj.SampleAnalyze.Id); if (UploadfileResult != null) { var fileResult = Path.Combine(_hostingEnvironment.WebRootPath, @"Files\SamplesAnalyze\" + SampleAnalyzeObj.SampleAnalyze.Id, UploadfileResult.FileName); if (System.IO.File.Exists(Path.Combine(ContentRootPath, @"Files\SamplesAnalyze\" + SampleAnalyzeObj.SampleAnalyze.Id)) == false) { System.IO.Directory.CreateDirectory(Path.Combine(ContentRootPath, @"Files\SamplesAnalyze\" + SampleAnalyzeObj.SampleAnalyze.Id)); } if (fileResult.Length > 0) { string fileName = Guid.NewGuid().ToString(); var uploads = Path.Combine(ContentRootPath, @"Files\SamplesAnalyze\" + SampleAnalyzeObj.SampleAnalyze.Id); var extention = Path.GetExtension(UploadfileResult.FileName); if (objFromDb.ResultFile != null) { if (System.IO.File.Exists(Path.Combine(uploads, objFromDb.ResultFile.TrimStart('\\')))) { System.IO.File.Delete(Path.Combine(uploads, objFromDb.ResultFile.TrimStart('\\'))); } } using (var fileStream = new FileStream(Path.Combine(uploads, fileName + extention), FileMode.Create)) { UploadfileResult.CopyTo(fileStream); } SampleAnalyzeObj.SampleAnalyze.ResultFile = fileName + extention; } } else { SampleAnalyzeObj.SampleAnalyze.ResultFile = objFromDb.ResultFile; } if (UploadfileInvoice != null) { var fileInvoice = Path.Combine(_hostingEnvironment.WebRootPath, @"Files\SamplesAnalyze\" + SampleAnalyzeObj.SampleAnalyze.Id, UploadfileInvoice.FileName); if (System.IO.File.Exists(Path.Combine(ContentRootPath, @"Files\SamplesAnalyze\" + SampleAnalyzeObj.SampleAnalyze.Id)) == false) { System.IO.Directory.CreateDirectory(Path.Combine(ContentRootPath, @"Files\SamplesAnalyze\" + SampleAnalyzeObj.SampleAnalyze.Id)); } if (fileInvoice.Length > 0) { string fileName = Guid.NewGuid().ToString(); var uploads = Path.Combine(ContentRootPath, @"Files\SamplesAnalyze\" + SampleAnalyzeObj.SampleAnalyze.Id); var extention = Path.GetExtension(UploadfileInvoice.FileName); if (objFromDb.InvoiceFile != null) { if (System.IO.File.Exists(Path.Combine(uploads, objFromDb.InvoiceFile.TrimStart('\\')))) { System.IO.File.Delete(Path.Combine(uploads, objFromDb.InvoiceFile.TrimStart('\\'))); } } using (var fileStream = new FileStream(Path.Combine(uploads, fileName + extention), FileMode.Create)) { UploadfileInvoice.CopyTo(fileStream); } SampleAnalyzeObj.SampleAnalyze.InvoiceFile = fileName + extention; } } else { SampleAnalyzeObj.SampleAnalyze.InvoiceFile = objFromDb.InvoiceFile; } _unitOfWork.SampleAnalyze.Update(SampleAnalyzeObj.SampleAnalyze); _unitOfWork.Save(); int SampleAnalyzeId = SampleAnalyzeObj.SampleAnalyze.Id; PrepareSampleAnalyzeAnalyzeType(SampleAnalyzeId); //tempDataList.Clear(); PrepareSampleAnalyzeFile(SampleAnalyzeId); } //_unitOfWork.Save(); return RedirectToPage("./index"); } else { SampleAnalyzeObj = new SampleAnalyzeVM { MineOrRangeList = _unitOfWork.MineOrRange.GetMineOrRangeListForDropdown(), LaboratoryList = _unitOfWork.Laboratory.GetLaboratoryListForDropdown(), SampleTypeList = _unitOfWork.SampleType.GetSampleTypeListForDropdown(), SampleStatusList = _unitOfWork.SampleStatus.GetSampleStatusListForDropdown(), SampleAnalyze = new Models.Entities.Mines.SampleAnalyze() }; return Page(); } } public void PrepareSampleAnalyzeAnalyzeType(int sampleAnalyzeId) { List<SampleAnalyzeAnalyzeTypeVM> SampleAnalyzeAnalyzeTypeObjList = new List<SampleAnalyzeAnalyzeTypeVM>(); DeniedSampleAnalyzeAnalyzeTypeObjList = new List<SampleAnalyzeAnalyzeTypeVM>(); for (int i = 0; i < lstString.Count; i++) { SampleAnalyzeAnalyzeTypeObj2 = new SampleAnalyzeAnalyzeTypeVM { SampleAnalyzeAnalyzeType = new Models.Entities.Mines.SampleAnalyzeAnalyzeType() }; SampleAnalyzeAnalyzeTypeObj2.SampleAnalyzeAnalyzeType.SampleAnalyzeId = sampleAnalyzeId; SampleAnalyzeAnalyzeTypeObj2.SampleAnalyzeAnalyzeType.AnalyzeTypeId = int.Parse(lstString[i]); //EventTeacherObj2.EventTeacher.Id = null; SampleAnalyzeAnalyzeTypeObjList.Add(SampleAnalyzeAnalyzeTypeObj2); } var objFromDb = _unitOfWork.SampleAnalyzeAnalyzeType.GetAll(u => u.SampleAnalyzeId == sampleAnalyzeId, null, null).ToList(); if (objFromDb == null) { return; } foreach (var item in objFromDb) { _unitOfWork.SampleAnalyzeAnalyzeType.Remove(item); } if (SampleAnalyzeAnalyzeTypeObjList.Count > 0) { _unitOfWork.SampleAnalyzeAnalyzeType.AddRange(SampleAnalyzeAnalyzeTypeObjList); } _unitOfWork.Save(); } public class PostData { public string[] list { get; set; } } public static List<string> lstString = new List<string>(); public IActionResult OnPostSend() { List<string> sPostValue1 = new List<string>(); { var syncIOFeature = HttpContext.Features.Get<IHttpBodyControlFeature>(); if (syncIOFeature != null) { syncIOFeature.AllowSynchronousIO = true; } MemoryStream stream = new MemoryStream(); Request.Body.CopyTo(stream); stream.Position = 0; using (StreamReader reader = new StreamReader(stream)) { string requestBody = reader.ReadToEnd(); if (requestBody.Length > 0) { var obj = JsonConvert.DeserializeObject<PostData>(requestBody); if (obj != null) { for (int i = 0; i < obj.list.Length; i++) { sPostValue1.Add(obj.list[i]); } } } } } lstString = sPostValue1; return new JsonResult(lstString); } public IActionResult OnPostDelete() { // Clear the tempDataList to ensure it only holds the current session data tempDataList.Clear(); string contentRootPath = _hostingEnvironment.WebRootPath; bool isFileDeleted = false; // Step 1: Retrieve DataList JSON from the request string dataListJson = Request.Form["DataList"]; if (string.IsNullOrEmpty(dataListJson)) { _logger.LogWarning("DataList is empty or missing."); return new JsonResult(new { success = false, message = "DataList is empty or missing." }); } _logger.LogInformation($"Received DataList JSON: {dataListJson}"); // Step 2: Deserialize the DataList JSON PostDataFile obj; try { obj = JsonConvert.DeserializeObject<PostDataFile>(dataListJson); _logger.LogInformation("DataList deserialized successfully."); } catch (JsonException ex) { _logger.LogError($"Deserialization failed: {ex.Message}"); return new JsonResult(new { success = false, message = "Failed to deserialize DataList.", error = ex.Message }); } if (obj?.list != null && obj.list.Count > 0) { // Create a HashSet of the incoming files for faster lookup var incomingFiles = new HashSet<string>(obj.list.Select(d => d.File)); // Step 3: Remove items from dataList that are not in the incoming data, and delete associated files var itemsToRetain = new List<DataType>(); foreach (var item in dataList) { if (incomingFiles.Contains(item.File)) { itemsToRetain.Add(item); // Retain items present in incoming data } else { // Delete the associated file if it exists string fileToDelete = Path.Combine(contentRootPath, @"Files\TempSamplesAnalyze\", item.File); if (System.IO.File.Exists(fileToDelete)) { try { System.IO.File.Delete(fileToDelete); isFileDeleted = true; _logger.LogInformation($"File {item.File} deleted successfully."); } catch (Exception ex) { _logger.LogError($"Error deleting file {item.File}: {ex.Message}"); } } } } // Update dataList to retain only the intersected items dataList = itemsToRetain; _logger.LogInformation("DataList updated successfully to retain only incoming items."); } else { _logger.LogWarning("Deserialized DataList is null or empty."); return new JsonResult(new { success = false, message = "No valid items found in DataList." }); } // Synchronize tempDataList with the updated dataList tempDataList = dataList; // Step 4: Return the Final DataList as JSON with file deletion status string finalJsonString = JsonConvert.SerializeObject(dataList.ToList()); _logger.LogInformation($"Final DataList JSON: {finalJsonString}"); return new JsonResult(new { success = true, dataList = finalJsonString, fileDeleted = isFileDeleted }); } public IActionResult OnPostFileSend() { tempDataList.Clear(); // Clear tempDataList as well if necessary string contentRootPath = _hostingEnvironment.WebRootPath; // Step 1: Handle UploadedFiles var uploadedFile = Request.Form.Files["UploadedFiles"]; if (uploadedFile != null && uploadedFile.Length > 0) { string tempDirectory = Path.Combine(contentRootPath, @"Files\TempSamplesAnalyze\"); if (!Directory.Exists(tempDirectory)) Directory.CreateDirectory(tempDirectory); string fileName = Path.GetFileNameWithoutExtension(uploadedFile.FileName); string extension = Path.GetExtension(uploadedFile.FileName); string filePath = Path.Combine(tempDirectory, fileName + extension); try { using (var fileStream = new FileStream(filePath, FileMode.Create)) { uploadedFile.CopyTo(fileStream); } _logger.LogInformation($"File saved successfully at {filePath}"); } catch (Exception ex) { _logger.LogError($"Error saving file: {ex.Message}"); return new JsonResult(new { success = false, message = "Failed to save the uploaded file.", error = ex.Message }); } } else { _logger.LogWarning("No file was uploaded."); return new JsonResult(new { success = false, message = "No file was uploaded." }); } // Step 2: Handle DataList string dataListJson = Request.Form["DataList"]; if (string.IsNullOrEmpty(dataListJson)) { _logger.LogWarning("DataList is empty or missing."); return new JsonResult(new { success = false, message = "DataList is empty or missing." }); } _logger.LogInformation($"Received DataList JSON: {dataListJson}"); // Step 3: Deserialize the DataList JSON PostDataFile obj; try { obj = JsonConvert.DeserializeObject<PostDataFile>(dataListJson); _logger.LogInformation("DataList deserialized successfully."); } catch (JsonException ex) { _logger.LogError($"Deserialization failed: {ex.Message}"); return new JsonResult(new { success = false, message = "Failed to deserialize DataList.", error = ex.Message }); } // Step 4: Validate and Process the Deserialized Data if (obj?.list != null && obj.list.Count > 0) { foreach (var item in obj.list) { if (!dataList.Exists(d => d.File == item.File)) { dataList.Add(item); // Only add unique items to avoid duplicates } else { _logger.LogInformation($"Duplicate entry found for file: {item.File}"); } } _logger.LogInformation("DataList processed successfully."); } else { _logger.LogWarning("Deserialized DataList is null or empty."); return new JsonResult(new { success = false, message = "No valid items found in DataList." }); } tempDataList=dataList; // Clear tempDataList after use // Step 6: Return the Final DataList as JSON string finalJsonString = JsonConvert.SerializeObject(dataList.ToList()); _logger.LogInformation($"Final DataList JSON: {finalJsonString}"); jsonResult = new JsonResult(finalJsonString); return jsonResult; } public class DataTypeComparer : IEqualityComparer<DataType> { public bool Equals(DataType x, DataType y) { return x.File == y.File; } public int GetHashCode(DataType obj) { return obj.File.GetHashCode(); } } public void PrepareSampleAnalyzeFile(int sampleAnalyzeId) { List<SampleAnalyzeFileVM> SampleAnalyzeFileObjList = new List<SampleAnalyzeFileVM>(); for (int i = 0; i < dataList.Count; i++) { SampleAnalyzeFileObj2 = new SampleAnalyzeFileVM { SampleAnalyzeFile = new Models.Entities.Mines.SampleAnalyzeFile() }; SampleAnalyzeFileObj2.SampleAnalyzeFile.SampleAnalyzeId = sampleAnalyzeId; SampleAnalyzeFileObj2.SampleAnalyzeFile.File = dataList[i].File; SampleAnalyzeFileObj2.SampleAnalyzeFile.FileName = dataList[i].FileName; SampleAnalyzeFileObj2.SampleAnalyzeFile.FileExtention = dataList[i].FileExtention; SampleAnalyzeFileObjList.Add(SampleAnalyzeFileObj2); } if (SampleAnalyzeFileObjList.Count >= 0) { var objFromDb = _unitOfWork.SampleAnalyzeFile.GetAll(u => u.SampleAnalyzeId == sampleAnalyzeId, null, null).ToList(); if (objFromDb == null) { return; } foreach (var item in objFromDb) { _unitOfWork.SampleAnalyzeFile.Remove(item); } _unitOfWork.SampleAnalyzeFile.AddRange(SampleAnalyzeFileObjList); _unitOfWork.Save(); } } - Assistant
Understood! I've reviewed and stored the backend code you provided for the
UpsertModelclass in theSampleAnalyzearea. Whenever you're ready, please share the front-end code along with your questions, and I'll be here to help you with any queries or issues you might have.Feel free to proceed whenever you're ready!