public async Task <ActionResult> AssignSection([Bind(Exclude = "CaseStudyName, Semesters")] AssignSectionViewModel caseStudyModel) { if (ModelState.IsValid) { CaseStudy caseStudy = await Db.CaseStudies.Where(x => x.Id == caseStudyModel.Id).FirstOrDefaultAsync(); if (caseStudy == null) { Flash.Error("Error", "No existe el caso de estudio"); return(RedirectToAction("Index")); } List <Section> activatedSections = caseStudy.Sections.Where(x => x.IsActivedSimulation == true).ToList(); List <Section> finalizedSections = caseStudy.Sections.Where(x => x.IsActivedSimulation == false && x.Periods.Select(c => c.IsLastPeriod).Contains(true)).ToList(); caseStudy.Sections.Clear(); if (caseStudyModel.Sections != null) { List <Section> sections = Db.Sections.Where(x => caseStudyModel.Sections.Contains(x.Id)).ToList(); caseStudy.Sections = sections; } if (activatedSections.Count() > 0) { var displayWarning = false; foreach (var activatedSection in activatedSections) { caseStudy.Sections.Add(activatedSection); if (caseStudyModel.Sections != null) { if (!caseStudyModel.Sections.Contains(activatedSection.Id)) { displayWarning = true; } } else { displayWarning = true; } } if (displayWarning) { Flash.Warning("Advertencia", "No pueden ser desasignados los casos estudios que tengan simulaciones activas"); } } if (finalizedSections.Count() > 0) { finalizedSections.ForEach(x => x.Groups.ToList().ForEach(t => Db.Groups.Where(z => z.Id == t.Id).FirstOrDefault().IsInSimulation = false)); finalizedSections.SelectMany(x => x.Periods).ToList().ForEach(x => Db.Periods.Remove(x)); Flash.Warning("Adventencia", "Simulaciones finalizadas han sido eliminadas"); } await Db.SaveChangesAsync(); Flash.Success("Ok", "El caso de Estudio ha sido asignado a las sección(es) satisfactoriamente"); return(RedirectToAction("Index")); } ViewBag.SelectedSections = Db.Sections.Where(y => y.CaseStudyId == caseStudyModel.Id).Select(x => x.Id).ToList(); Flash.Error("Error", "Ha Ocurrido un error"); return(View(caseStudyModel)); }
public IActionResult Delete(int id) { CaseStudy abs = _casestudyRepository.GetCaseStudyById(id); if (abs == null) { return(NotFound()); } _casestudyRepository.DeleteCaseStudy(abs); return(RedirectToAction("index")); }
public IActionResult Create(CaseStudyViewModel abs) { if (ModelState.IsValid) { CaseStudy model = _mapper.Map <CaseStudyViewModel, CaseStudy>(abs); model.CreatedBy = _admin.FullName; _casestudyRepository.CreateCaseStudy(model); return(RedirectToAction("index")); } return(View(abs)); }
public static CaseStudyPersonViewModel Create(IRepository repository, CaseStudy caseStudy) { Check.Require(repository != null, "Repository is required."); var viewModel = new CaseStudyPersonViewModel() { CaseStudy = caseStudy, SeminarPeople = caseStudy.Seminar.SeminarPeople }; return(viewModel); }
public static CaseStudyViewModel Create(IRepository repository, Seminar seminar, CaseStudy caseStudy = null) { Check.Require(repository != null, "Repository must be supplied"); var viewModel = new CaseStudyViewModel { Seminar = seminar, CaseStudy = caseStudy ?? new CaseStudy() }; return viewModel; }
public async Task <IActionResult> PostCaseStudy([FromBody] CaseStudy caseStudy) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } _context.CaseStudies.Add(caseStudy); await _context.SaveChangesAsync(); return(CreatedAtAction("GetCaseStudy", new { id = caseStudy.Id }, caseStudy)); }
public void UpdateCaseStudy(CaseStudy modelToUpdate, CaseStudy model) { modelToUpdate.Status = model.Status; modelToUpdate.SolutionText = model.SolutionText; modelToUpdate.ResultText = model.ResultText; modelToUpdate.MainTitle = model.MainTitle; modelToUpdate.Image = model.Image; modelToUpdate.Text = model.Text; modelToUpdate.Title = model.Title; modelToUpdate.AgentId = model.AgentId; _context.SaveChanges(); }
public IActionResult Edit(int id) { CaseStudy abs = _casestudyRepository.GetCaseStudyById(id); if (abs == null) { return(NotFound()); } var model = _mapper.Map <CaseStudy, CaseStudyViewModel>(abs); ViewBag.Agents = _agentRepository.GetAllAgents(); return(View(model)); }
public async Task <ActionResult> Details(Guid?id) { if (id == null) { return(new HttpStatusCodeResult(HttpStatusCode.BadRequest)); } CaseStudy caseStudy = await Db.CaseStudies.Where(x => x.Id == id).FirstOrDefaultAsync(); if (caseStudy == null) { return(HttpNotFound()); } return(View(caseStudy)); }
public async Task OnPost(CaseStudy caseStudy) { using (IDbContextTransaction transaction = _context.Database.BeginTransaction()) { try { if (Upload.FileName.ToLower().EndsWith(".pdf")) { var user = await _userManager.GetUserAsync(User); String fileName = System.Guid.NewGuid().ToString() + ".pdf"; var file = Path.Combine(_environment.ContentRootPath, "wwwroot\\uploads", fileName); using (var fileStream = new FileStream(file, FileMode.Create)) { await Upload.CopyToAsync(fileStream); } var cStudy = new CaseStudy() { CaseTitle = caseStudy.CaseTitle, CaseDescription = caseStudy.CaseDescription, UploadedBy = user.Id, UploadedByStudent = false, FileName = fileName, UploadedOn = DateTime.Now }; _context.Entry(cStudy).State = EntityState.Added; await _context.SaveChangesAsync(); await transaction.CommitAsync(); ModelState.Clear(); isSuccessful = true; } else { ModelState.Clear(); } } catch (Exception ex) { await transaction.RollbackAsync(); throw ex; } } }
public IActionResult Edit(CaseStudyViewModel abs) { if (ModelState.IsValid) { CaseStudy model = _mapper.Map <CaseStudyViewModel, CaseStudy>(abs); model.ModifiedBy = _admin.FullName; CaseStudy TestToUpdate = _casestudyRepository.GetCaseStudyById(abs.Id); if (TestToUpdate == null) { return(NotFound()); } _casestudyRepository.UpdateCaseStudy(TestToUpdate, model); return(RedirectToAction("index")); } return(View(abs)); }
public ActionResult EditPost(Guid id, IList <GalleryImage> images, Guid?links, AreaKind farea, IList <Tag> tags) { CaseStudy caseStudy; if (Guid.Empty.Equals(id)) { caseStudy = new CaseStudy(); } else { caseStudy = DbSession.Get <CaseStudy>(id); caseStudy.Image = null; caseStudy.SharedLinks = null; } if (TryUpdateModel(caseStudy)) { caseStudy.Tags.Clear(); if (tags != null) { foreach (var dtoTag in tags) { caseStudy.Tags.Add(DbSession.Get <Tag>(dtoTag.ID)); } } caseStudy.Area = DbSession.Get <Area>(farea); if (images != null) { ImagesController.SaveImages(images, DbSession); caseStudy.Image = images.FirstOrDefault(img => !img.ShouldDelete); } if (links.HasValue) { caseStudy.SharedLinks = DbSession.Get <CmsBlock>(links.Value); } DbSession.SaveOrUpdate(caseStudy); DbSession.Flush(); return(RedirectToAction("Edit", new { id = caseStudy.ID })); } ViewBag.Areas = DbSession.GetAll <Area>(true); ViewBag.CmsBlocks = DbSession.GetAll <CmsBlock>(true); return(View(caseStudy)); }
public async Task <ActionResult> RegisterDemands(Guid?Id) { try { Section section = await Db.Sections.Where(x => x.Id == Id).FirstOrDefaultAsync <Section>(); if (section == null) { throw new Exception(); } if (section.IsActivedSimulation == false && section.Periods.Count() > 0) { Flash.Error("El Modelo de gestión ha finalizado"); return(RedirectToAction("Index")); } if (section.IsActivedSimulation == false) { Flash.Error("Error", "No ha sido activada la simulación"); return(RedirectToAction("Index")); } var caseStudyQuery = Db.CaseStudies.Where(x => x.Id == section.CaseStudyId); CaseStudy caseStudy = await caseStudyQuery.FirstOrDefaultAsync(); DemandViewModel sellViewModel = new DemandViewModel { ProductDemands = caseStudy.InitialCharges.Select(y => new ProductDemand { Product = y.Product }).OrderBy(t => t.Product.Number).ToList <ProductDemand>(), Section = section, SectionId = section.Id, }; return(View(sellViewModel)); } catch { Flash.Error("Error", "Ha ocurrido un error inesperado"); return(RedirectToAction("Index")); } }
public async Task <ActionResult> AssignSection(Guid?id) { if (id == null) { return(new HttpStatusCodeResult(HttpStatusCode.BadRequest)); } CaseStudy caseStudy = await Db.CaseStudies.Where(x => x.Id == id).FirstOrDefaultAsync(); if (caseStudy == null) { return(HttpNotFound()); } AssignSectionViewModel asignSection = new AssignSectionViewModel { Id = caseStudy.Id, CaseStudyName = caseStudy.Name, Semesters = Db.Semesters.ToList(), }; ViewBag.SelectedSections = caseStudy.Sections.Select(x => x.Id).ToList(); return(View(asignSection)); }
public ActionResult Edit(int id, int seminarId, CaseStudy caseStudy, HttpPostedFileBase file) { // load the case study var existing = _casestudyRepository.GetNullableById(id); if (existing == null) { Message = string.Format(Messages.NotFound, "Case Study", id); return(this.RedirectToAction <SeminarController>(a => a.Edit(seminarId))); } if (file != null) { var reader = new BinaryReader(file.InputStream); var data = reader.ReadBytes(file.ContentLength); existing.File = data; existing.ContentType = file.ContentType; } // copy all the other fields existing.Name = caseStudy.Name; existing.Session = caseStudy.Session; existing.IsPublic = caseStudy.IsPublic; existing.Description = caseStudy.Description; existing.LastUpdate = DateTime.Now; ModelState.Clear(); existing.TransferValidationMessagesTo(ModelState); if (ModelState.IsValid) { _casestudyRepository.EnsurePersistent(existing); Message = string.Format(Messages.Saved, "Case Study"); return(this.RedirectToAction <SeminarController>(a => a.Edit(existing.Seminar.Id))); } var viewModel = CaseStudyViewModel.Create(Repository, existing.Seminar, existing); return(View()); }
public ActionResult Edit(Guid?id) { CaseStudy caseStudy; if (id == null) { caseStudy = new CaseStudy(); caseStudy.Inx = (DbSession.QueryOver <CaseStudy>().RowCount() + 1) * 10; } else { caseStudy = DbSession.Get <CaseStudy>(id.Value); } if (caseStudy == null) { return(HttpNotFound()); } ViewBag.Areas = DbSession.GetAll <Area>(true); ViewBag.CmsBlocks = DbSession.GetAll <CmsBlock>(true); return(View(caseStudy)); }
private double GetOrderCost(CaseStudy caseStudy, Order order) { OrderType orderType = order.OrderType; int productPrice = caseStudy.InitialCharges.Where(x => x.ProductId == order.ProductId).Select(x => x.Price).FirstOrDefault(); switch (orderType) { case OrderType.Normal: return(productPrice * order.Quantity); case OrderType.Fast: return(caseStudy.PreparationCost + (productPrice * order.Quantity)); case OrderType.Courier: return(((double)(caseStudy.CourierCharges * productPrice) * order.Quantity) + (productPrice * order.Quantity)); case OrderType.FastCourier: return(((double)(caseStudy.CourierCharges * productPrice) * order.Quantity) + caseStudy.PreparationCost + (productPrice * order.Quantity)); default: return(0); } }
private Balance CalculateNextBalance(CaseStudy caseStudy, Demand demand, Group group, List <Period> periods) { List <Order> orders = group.Orders.Where(x => x.ProductId == demand.ProductId).OrderBy(y => y.Created).ToList(); periods = periods.OrderBy(x => x.Created).ToList(); //List de períodos ordenados de menor a mayor en orden de creación //Si el estudiante no creo ninguna orden en este período se le crea //Pero se le crea vacia Order lastOrder; if (periods.Count() - 1 > orders.Count()) { lastOrder = new Order { Id = Guid.NewGuid(), OrderType = OrderType.None, Quantity = 0, Group = group, Product = demand.Product, Period = demand.Period, Created = DateTime.Now, }; //group.Orders.Add(lastOrder); } else { lastOrder = orders.Last(); } Balance lastBalance = group.Balances.OrderByDescending(x => x.Created).Where(x => x.ProductId == demand.ProductId).FirstOrDefault(); Balance newBalance = CloneBalance(lastBalance, demand); foreach (var order in orders) { newBalance = BalanceWithPendingOrders(newBalance, order, demand, caseStudy, periods); } newBalance = UpdateBalance(newBalance, demand, caseStudy, lastOrder); return(newBalance); }
private Balance UpdateBalance(Balance balance, Demand demand, CaseStudy caseStudy, Order lastOrder) { InitialCharge initialChargeProduct = caseStudy.InitialCharges.Where(x => x.Product == demand.Product).FirstOrDefault(); int initialStock = balance.FinalStock + balance.ReceivedOrders; int demandNumber = demand.Quantity; int sells = (initialStock - demandNumber) < 0 ? initialStock : demandNumber; int finalStock = initialStock - sells; int dissastifiedDemand = (finalStock > 0) ? 0 : (demandNumber - initialStock); double orderCost = GetOrderCost(caseStudy, lastOrder); #region UpdateBalance balance.Demand = demand.Quantity; balance.DissatisfiedDemand = dissastifiedDemand; balance.DissatisfiedCostPast = balance.DissatisfiedCost; balance.FinalStockCostPast = balance.FinalStockCost; balance.DissatisfiedCost = dissastifiedDemand * initialChargeProduct.Price; balance.OrderCost = orderCost; balance.InitialStock = initialStock; balance.FinalStock = finalStock; balance.FinalStockCost = finalStock * initialChargeProduct.Price; balance.Sells = sells; #endregion return(balance); }
public void CreateCaseStudy(CaseStudy model) { model.CreatedAt = DateTime.Now; _context.CaseStudy.Add(model); _context.SaveChanges(); }
private Balance BalanceWithPendingOrders(Balance balance, Order order, Demand demand, CaseStudy caseStudy, List <Period> periods) { int periodLength = periods.Count(); //Número de períodos en el caso de Estudio int indexOrderPeriod = periods.IndexOf(order.Period) + 1; Product product = demand.Product; OrderType orderType = order.OrderType; if (orderType != OrderType.None) { int periodDelivering = PeriodWillBeDelivered(caseStudy, product, orderType); if ((periodDelivering + indexOrderPeriod) == periodLength) { balance.ReceivedOrders += order.Quantity; } } return(balance); }
public List<CaseStudy> UpdateCaseStudy(CaseStudy sTemperatureData) { List<CaseStudy> returnValue = new List<CaseStudy>(); CaseStudy temp = new CaseStudy(); DataBase Base = new DataBase(); string strSql = ""; foreach (System.Reflection.FieldInfo fldInfo in sTemperatureData.GetType().GetFields()) { switch (fldInfo.Name) { case "CreateFileBy": case "CreateFileDate": case "ID": case "Unit": case "WriteNameName": case "WriteName1Name": case "RecordedByName": // strSql += (string.IsNullOrEmpty(strSql) ? "" : ",") + fldInfo.Name + " = " + fldInfo.GetValue(sTemperatureData); break; //case "CreateFileDate": case "UpFileDate": strSql += (string.IsNullOrEmpty(strSql) ? "" : ",") + fldInfo.Name + "=getdate()"; // strSqlPara += (string.IsNullOrEmpty(strSqlPara) ? "" : ",") + "getdate() "; //cmd.Parameters.Add("@" + fldInfo.Name, SqlDbType.Date).Value = DateTime.Now.ToLongDateString(); break; default: strSql += (string.IsNullOrEmpty(strSql) ? "" : ",") + fldInfo.Name + "=@" + fldInfo.Name; //strSqlPara += (string.IsNullOrEmpty(strSqlPara) ? "@" : ",@") + fldInfo.Name; break; } } using (SqlConnection Sqlconn = new SqlConnection(Base.GetConnString())) { try { StaffDataBase sDB = new StaffDataBase(); List<string> CreateFileName = sDB.getStaffDataName(HttpContext.Current.User.Identity.Name); Sqlconn.Open(); string sql = " update CaseStudy set " + strSql + " where id=@ID "; //sql += " select @@identity as id "; SqlCommand cmd = new SqlCommand(sql, Sqlconn); foreach (System.Reflection.FieldInfo fldInfo in sTemperatureData.GetType().GetFields()) { switch (fldInfo.Name) { //case "ID": case "CreateFileDate": case "Unit": // strSql += (string.IsNullOrEmpty(strSql) ? "" : ",") + fldInfo.Name + " = " + fldInfo.GetValue(sTemperatureData); break; case "UpFileBy": //cmd.Parameters.Add("@" + fldInfo.Name, fldInfo.GetValue(sTemperatureData)); cmd.Parameters.Add("@" + fldInfo.Name, SqlDbType.Int).Value = Chk.CheckStringtoIntFunction(CreateFileName[0]); break; default: if (fldInfo.GetValue(sTemperatureData) != null) { cmd.Parameters.Add("@" + fldInfo.Name, fldInfo.GetValue(sTemperatureData).ToString()); } else { cmd.Parameters.Add("@" + fldInfo.Name, ""); } break; } } cmd.ExecuteNonQuery(); temp.ID = sTemperatureData.ID; } catch (Exception e) { string a = e.Message.ToString(); } Sqlconn.Close(); } returnValue.Add(temp); return returnValue; }
public List<AchievementAssessmentLoad> ShowCaseStudy(int ID) { string strSql = ""; List<AchievementAssessmentLoad> returnvalue = new List<AchievementAssessmentLoad>(); AchievementAssessmentLoad temp = new AchievementAssessmentLoad(); CaseStudy sTemperatureData = new CaseStudy(); foreach (System.Reflection.FieldInfo fldInfo in sTemperatureData.GetType().GetFields()) { switch (fldInfo.Name) { case "ID": case "Unit": case "WriteNameName": case "WriteName1Name": case "RecordedByName": break; case "WriteDate": case "RecordedDateTime": strSql += (string.IsNullOrEmpty(strSql) ? "" : ",") + "convert(varchar, isnull(convert(date, a." + fldInfo.Name + ",1),'1912'), 111) as " + fldInfo.Name; break; default: strSql += (string.IsNullOrEmpty(strSql) ? "" : ",") + "a." + fldInfo.Name; break; } } DataBase Base = new DataBase(); using (SqlConnection Sqlconn = new SqlConnection(Base.GetConnString())) { try { StaffDataBase sDB = new StaffDataBase(); Sqlconn.Open(); string sql = "select b.studentname ,convert(varchar, isnull(convert(date, b.studentbirthday ,1),'1912'), 23) as studentbirthday , c.WriteNameName , d.WriteName1Name,e.RecordedByName , " + strSql + " from CaseStudy a "; sql += " left join ( select staffid as cid , StaffName as WriteNameName from staffDatabase ) c on a.WriteName = c.cid "; sql += " left join ( select staffid as did , StaffName as WriteName1Name from staffDatabase ) d on a.WriteName1 = d.did "; sql += " left join ( select staffid as eid , StaffName as RecordedByName from staffDatabase ) e on a.RecordedBy = e.eid "; sql += " left join studentDatabase b on a.studentid = b.id where a.ID=@ID and isnull(a.isDeleted,0) = 0 "; SqlCommand cmd = new SqlCommand(sql, Sqlconn); cmd.Parameters.Add("@ID", SqlDbType.Int).Value = ID; SqlDataReader dr = cmd.ExecuteReader(); if (dr.Read()) { temp.IDname = "studentName"; temp.ThisValue = dr["studentName"].ToString(); returnvalue.Add(temp); temp.IDname = "WriteNameName"; temp.ThisValue = dr["WriteNameName"].ToString(); returnvalue.Add(temp); temp.IDname = "WriteName1Name"; temp.ThisValue = dr["WriteName1Name"].ToString(); returnvalue.Add(temp); temp.IDname = "RecordedByName"; temp.ThisValue = dr["RecordedByName"].ToString(); returnvalue.Add(temp); temp.IDname = "studentbirthday"; temp.ThisValue = dr["studentbirthday"].ToString(); returnvalue.Add(temp); foreach (System.Reflection.FieldInfo fldInfo in sTemperatureData.GetType().GetFields()) { switch (fldInfo.Name) { case "ID": case "Unit": case "WriteNameName": case "WriteName1Name": case "RecordedByName": break; case "WriteDate": case "RecordedDateTime": temp.IDname = fldInfo.Name; temp.ThisValue = Convert.ToDateTime(dr[fldInfo.Name].ToString()).AddYears(-1911).ToShortDateString().Remove(0, 1); returnvalue.Add(temp); break; default: string namee = fldInfo.Name; string namee2 = dr[fldInfo.Name].ToString(); temp.IDname = fldInfo.Name; temp.ThisValue = dr[fldInfo.Name].ToString(); returnvalue.Add(temp); break; } } } dr.Close(); Sqlconn.Close(); } catch (Exception e) { string error = e.Message; } } return returnvalue; }
public List<CaseStudy> CreatCaseStudy(CaseStudy sTemperatureData) { List<CaseStudy> returnValue = new List<CaseStudy>(); CaseStudy temp = new CaseStudy(); DataBase Base = new DataBase(); string strSql = ""; string strSqlPara = ""; foreach (System.Reflection.FieldInfo fldInfo in sTemperatureData.GetType().GetFields()) { switch (fldInfo.Name) { case "ID": case "Unit": case "WriteNameName": case "WriteName1Name": case "RecordedByName": break; case "isDeleted": strSql += (string.IsNullOrEmpty(strSql) ? "" : ",") + fldInfo.Name; strSqlPara += (string.IsNullOrEmpty(strSqlPara) ? "" : ",") + "0 "; break; case "CreateFileDate": case "UpFileDate": strSql += (string.IsNullOrEmpty(strSql) ? "" : ",") + fldInfo.Name; strSqlPara += (string.IsNullOrEmpty(strSqlPara) ? "" : ",") + "getdate() "; break; default: strSql += (string.IsNullOrEmpty(strSql) ? "" : ",") + fldInfo.Name; strSqlPara += (string.IsNullOrEmpty(strSqlPara) ? "@" : ",@") + fldInfo.Name; break; } } using (SqlConnection Sqlconn = new SqlConnection(Base.GetConnString())) { try { StaffDataBase sDB = new StaffDataBase(); List<string> CreateFileName = sDB.getStaffDataName(HttpContext.Current.User.Identity.Name); Sqlconn.Open(); string sql = " insert into CaseStudy ( " + strSql + ")values(" + strSqlPara + ") "; sql += " select @@identity as id "; SqlCommand cmd = new SqlCommand(sql, Sqlconn); foreach (System.Reflection.FieldInfo fldInfo in sTemperatureData.GetType().GetFields()) { switch (fldInfo.Name) { case "ID": case "Unit": case "WriteNameName": case "WriteName1Name": case "RecordedByName": // strSql += (string.IsNullOrEmpty(strSql) ? "" : ",") + fldInfo.Name + " = " + fldInfo.GetValue(sTemperatureData); break; case "CreateFileBy": case "UpFileBy": //cmd.Parameters.Add("@" + fldInfo.Name, fldInfo.GetValue(sTemperatureData)); cmd.Parameters.Add("@" + fldInfo.Name, SqlDbType.Int).Value = Chk.CheckStringtoIntFunction(CreateFileName[0]); break; default: if (fldInfo.GetValue(sTemperatureData) != null) { cmd.Parameters.Add("@" + fldInfo.Name, fldInfo.GetValue(sTemperatureData).ToString()); } else { cmd.Parameters.Add("@" + fldInfo.Name, ""); } break; } } SqlDataReader dr = cmd.ExecuteReader(); if (dr.Read()) { temp.ID = dr["id"].ToString(); } } catch (Exception e) { string ex = e.Message.ToString(); } Sqlconn.Close(); } returnValue.Add(temp); return returnValue; }
public async Task <ActionResult> Create([Bind(Include = "Name,Periods,PreparationTime,AcceleratedPreparationTime,FillTime,ExistingFillTime,DeliveryTime,CourierDeliveryTime,PurchaseOrderRecharge,CourierCharges,PreparationCost,AnnualMaintenanceCost,SemesterId,SectionId,ChargeTypeName,XmlUpload,InitialCharges,PreparationTimeOption,FillTimeOption,DeliveryTimeOption")] CaseStudyViewModel caseStudyViewModel) { try { CaseStudyBL caseStudyBL = new CaseStudyBL(); if (caseStudyViewModel.ChargeTypeName == "xml") { caseStudyBL.ModelStateForXML(ModelState); if (ModelState.IsValid) { CaseStudyXmlBL caseStudyXmlBL = new CaseStudyXmlBL(); CaseStudyXml caseStudyXml = caseStudyXmlBL.Deserealize(caseStudyViewModel.XmlUpload.InputStream); CaseStudy caseStudy = caseStudyXmlBL.XmlToModel(caseStudyXml); caseStudy.Name = caseStudyViewModel.Name; caseStudy.Periods = caseStudyViewModel.Periods; foreach (var initialCharge in caseStudy.InitialCharges) { if (!TryValidateModel(initialCharge)) { throw new Exception("Ha ocurrido un error agregando los datos de un producto"); } } if (!TryValidateModel(caseStudy)) { throw new Exception("Ha ocurrido un error agregando los datos de un producto"); } if (caseStudyViewModel.SectionId != null) { Section section = Db.Sections.Where(x => x.Id == caseStudyViewModel.SectionId && x.CaseStudy == null).FirstOrDefault(); if (section != null) { caseStudy.Sections.Add(section); } else { Flash.Warning("Advertencia", "No se ha podido asignar la sección seleccionada, ya está asignada a un caso de estudio"); } } Db.CaseStudies.Add(caseStudy); await Db.SaveChangesAsync(); Flash.Success("Ok", "El archivo Xml es correcto, se ha creado el caso de estudio"); return(RedirectToAction("Index")); } } else if (caseStudyViewModel.ChargeTypeName == "form") { caseStudyBL.ModelStateInForm(ModelState); if (ModelState.IsValid) { Guid caseStudyId = Guid.NewGuid(); List <InitialCharge> initialCharges = caseStudyBL.JsonToInitialChargeList(caseStudyViewModel.InitialCharges); foreach (var initialCharge in initialCharges) { InitialCharge auxInitialCharge = caseStudyBL.ChangeTimes(caseStudyViewModel, initialCharge); if (TryValidateModel(auxInitialCharge)) { auxInitialCharge.CaseStudyId = caseStudyId; } else { Flash.Error("Error", "Ha ocurrido un error agregando los datos de un producto"); throw new Exception(); } } CaseStudy caseStudy = new CaseStudy { Id = caseStudyId, Name = caseStudyViewModel.Name, Periods = caseStudyViewModel.Periods, Created = DateTime.Now, CourierCharges = caseStudyViewModel.CourierCharges, PurchaseOrderRecharge = caseStudyViewModel.PurchaseOrderRecharge, PreparationCost = caseStudyViewModel.PreparationCost, AnnualMaintenanceCost = caseStudyViewModel.AnnualMaintenanceCost, InitialCharges = initialCharges }; if (caseStudyViewModel.SectionId != null) { Section section = Db.Sections.Where(x => x.Id == caseStudyViewModel.SectionId && x.CaseStudy == null).FirstOrDefault(); if (section != null) { caseStudy.Sections.Add(section); } else { Flash.Warning("Advertencia", "No se ha podido asignar la sección"); } } Db.CaseStudies.Add(caseStudy); await Db.SaveChangesAsync(); Flash.Success("Ok", "El caso de estudio ha sido agregado exitosamente"); return(RedirectToAction("Index")); } else { throw new Exception("El caso de estudio no ha podido ser almacenado correctamente"); } } else { throw new Exception("Error Inesperado"); } } catch (Exception e) { Flash.Error("Error", e.Message); Db.Sections.Where(x => x.CaseStudy == null).Select(x => new { x.Id, x.Number, x.Semester.Description }); CaseStudyViewModel caseStudy = new CaseStudyViewModel(); ViewBag.Products = caseStudy.Products; ViewBag.ChargeTypes = caseStudy.ChargeTypes; ViewBag.FillTime = caseStudy.FillTimeRadio; ViewBag.DeliveryTime = caseStudy.DeliveryTimeRadio; ViewBag.PreparationTime = caseStudy.PreparationTimeRadio; } return(View()); }
public List<CaseStudy> UpdateCaseStudy(CaseStudy sTemperatureData) { AdministrationDataBase aDB = new AdministrationDataBase(); //aDB.caseBTFunction(); //if (int.Parse(aDB._StaffhaveRoles[2]) == 1) //{ return aDB.UpdateCaseStudy(sTemperatureData); //} //else //{ // return null; //} }
public ActionResult Edit(int id, int seminarId, CaseStudy caseStudy, HttpPostedFileBase file) { // load the case study var existing = _casestudyRepository.GetNullableById(id); if (existing == null) { Message = string.Format(Messages.NotFound, "Case Study", id); return this.RedirectToAction<SeminarController>(a => a.Edit(seminarId)); } if (file != null) { var reader = new BinaryReader(file.InputStream); var data = reader.ReadBytes(file.ContentLength); existing.File = data; existing.ContentType = file.ContentType; } // copy all the other fields existing.Name = caseStudy.Name; existing.Session = caseStudy.Session; existing.IsPublic = caseStudy.IsPublic; existing.Description = caseStudy.Description; existing.LastUpdate = DateTime.Now; ModelState.Clear(); existing.TransferValidationMessagesTo(ModelState); if (ModelState.IsValid) { _casestudyRepository.EnsurePersistent(existing); Message = string.Format(Messages.Saved, "Case Study"); return this.RedirectToAction<SeminarController>(a => a.Edit(existing.Seminar.Id)); } var viewModel = CaseStudyViewModel.Create(Repository, existing.Seminar, existing); return View(); }
public ActionResult Create(int seminarId, CaseStudy caseStudy, HttpPostedFileBase file) { var seminar = Repository.OfType<Seminar>().GetNullableById(seminarId); if (file != null) { var reader = new BinaryReader(file.InputStream); var data = reader.ReadBytes(file.ContentLength); caseStudy.File = data; caseStudy.ContentType = file.ContentType; } if (seminar == null) { Message = string.Format(Messages.NotFound, "Seminar", seminarId); return this.RedirectToAction<SeminarController>(a => a.Index()); } caseStudy.Seminar = seminar; ModelState.Clear(); caseStudy.TransferValidationMessagesTo(ModelState); if (ModelState.IsValid) { _casestudyRepository.EnsurePersistent(caseStudy); Message = string.Format(Messages.Saved, "Case Study"); return this.RedirectToAction<SeminarController>(a => a.Edit(seminarId)); } var viewModel = CaseStudyViewModel.Create(Repository, seminar, caseStudy); return View(viewModel); }
public void DeleteCaseStudy(CaseStudy model) { _context.CaseStudy.Remove(model); _context.SaveChanges(); }
public static CaseStudyViewModel Create(IRepository repository, Seminar seminar, CaseStudy caseStudy = null) { Check.Require(repository != null, "Repository must be supplied"); var viewModel = new CaseStudyViewModel { Seminar = seminar, CaseStudy = caseStudy ?? new CaseStudy() }; return(viewModel); }