public void SetTermination(Termination termination, int countIteration) { switch (termination) { case Termination.GenerationNumberTermination: _termination = new GeneticSharp.Domain.Terminations.GenerationNumberTermination(countIteration); break; case Termination.FitnessStagnationTermination: _termination = new GeneticSharp.Domain.Terminations.FitnessStagnationTermination(countIteration); break; case Termination.FitnessThresholdTermination: _termination = new GeneticSharp.Domain.Terminations.FitnessThresholdTermination(countIteration); break; case Termination.TimeEvolvingTermination: _termination = new GeneticSharp.Domain.Terminations.TimeEvolvingTermination(new TimeSpan(0, 0, countIteration)); break; default: throw new Exception("Не існує такого методу ітерації!"); break; } }
/// <summary> /// Ends the current generation. /// </summary> /// <returns><c>true</c>, if current generation was ended, <c>false</c> otherwise.</returns> private bool EndCurrentGeneration() { EvaluateFitness(); Population.EndCurrentGeneration(); var handler = GenerationRan; if (handler != null) { handler(this, EventArgs.Empty); } if (Termination.HasReached(this)) { State = GeneticAlgorithmState.TerminationReached; handler = TerminationReached; if (handler != null) { handler(this, EventArgs.Empty); } return(true); } if (m_stopRequested) { TaskExecutor.Stop(); State = GeneticAlgorithmState.Stopped; } return(false); }
// Start is called before the first frame update void Start() { if (removeBuff == null) { removeBuff = doNothing; } }
public void CannotBeGeneratedWithNull() { Assert.Throws <ArgumentNullException>(() => { var termination = Termination.Of(null); }); }
public async Task Drive() { logger.Info("Message Pipeline Started"); var messageHandler = await Entrance.FetchMessage(); if (messageHandler != null) { var message = messageHandler.MessageObject; if (message.Command.CommandCode == Commands.CommandCode.Configure) { logger.Info("Recesived the delay command"); int delay = BitConverter.ToInt32(message.MessageData); await Task.Delay(delay); logger.Info("Completed the delay command"); } else { logger.Info("Message Get:" + message.Command.CommandType.ToString()); await Termination.Terminate(message); logger.Info("Message Terminated"); } await messageHandler.Complete(); BusyCollector.Increase(1); logger.Info("Message Pipline Completed"); } else { IdleCollector.Increase(1); logger.Info("Message get nothing from Queue"); Thread.Sleep(1000); } }
public override float SpawnChance(NPCSpawnInfo spawnInfo) { int x = spawnInfo.spawnTileX; int y = spawnInfo.spawnTileY; int tile = (int)Main.tile[x, y].type; return((Termination.NoZoneAllowWater(spawnInfo)) && NPC.downedMechBossAny && !Main.dayTime && spawnInfo.spawnTileY < Main.worldSurface ? 0.1f : 0f); }
protected void dgTermination_RowCommand(object sender, GridViewCommandEventArgs e) { if (e.CommandName == "Select") { int Row = Convert.ToInt32(e.CommandArgument); int TEMPChid = Convert.ToInt32(dgTermination.DataKeys[Row].Value); // int TEMPChid = Convert.ToInt32(dgContractDetail.DataKeys[dgContractDetail.SelectedRow.RowIndex].Value.ToString()); if (TEMPChid > 0) { Session["chan"] = _presenter.CurrentEmployee.GetTerminations(TEMPChid); } else { Session["chan"] = _presenter.CurrentEmployee.Terminations[dgTermination.SelectedRow.DataItemIndex]; } Termination term = _presenter.CurrentEmployee.GetTerminations(TEMPChid); txtTerminationDate.Text = term.TerminationDate.ToShortDateString(); txtLastDate.Text = term.LastDateOfEmployee.ToShortDateString(); ddlRecommendation.SelectedItem.Text = term.ReccomendationForRehire; txtTerminationReason.Text = term.TerminationReason; btnAddTerm.Text = "Update Terminations"; } else if (e.CommandName == "Delete") { int Row = Convert.ToInt32(e.CommandArgument); int TEMPChid = Convert.ToInt32(dgTermination.DataKeys[Row].Value); try { if (TEMPChid > 0) { _presenter.CurrentEmployee.RemoveTermination(TEMPChid); _presenter.SaveOrUpdateEmployeeActivity(_presenter.CurrentEmployee); dgTermination.DataSource = _presenter.CurrentEmployee.Terminations; dgTermination.DataBind(); Master.ShowMessage(new AppMessage("Termination Is Successfully Deleted!", RMessageType.Info)); } } catch (Exception ex) { Master.ShowMessage(new AppMessage("Error: Unable to Delete Termination. ", RMessageType.Error)); ExceptionUtility.LogException(ex, ex.Source); ExceptionUtility.NotifySystemOps(ex, _presenter.CurrentEmployee.AppUser.FullName); } } }
public async Task <ActionResult> DeleteConfirmed(int id) { Termination termination = await db.Terminations.FindAsync(id); db.Terminations.Remove(termination); await db.SaveChangesAsync(); return(RedirectToAction("Index")); }
protected void dgTermination_SelectedIndexChanged(object sender, EventArgs e) { int id = Convert.ToInt32(dgTermination.SelectedDataKey[0]); Termination termination = _presenter.CurrentEmployee.GetTerminations(id); txtTerminationDate.Text = termination.TerminationDate.ToShortDateString(); txtLastDate.Text = termination.LastDateOfEmployee.ToShortDateString(); ddlRecommendation.SelectedValue = termination.ReccomendationForRehire.ToString(); txtTerminationReason.Text = termination.TerminationReason; btnAddTerm.Text = "Update Termination"; }
public void ShouldExecuteActionWhenHasTerminated() { var expected = false; var termination = Termination.Of(() => { expected = true; }); termination.Terminate(); Assert.IsTrue(expected); }
public async Task <ActionResult> Edit([Bind(Include = "TerminationId,TerminationEmp,TerminationDate,Reason,NoticeDate,Department,EmployeeID")] Termination termination) { if (ModelState.IsValid) { db.Entry(termination).State = EntityState.Modified; await db.SaveChangesAsync(); return(RedirectToAction("Index")); } ViewBag.EmployeeID = new SelectList(db.Employees, "EmployeeID", "Name", termination.EmployeeID); return(View(termination)); }
/// <summary> /// Resumes the last evolution of the genetic algorithm. /// <remarks> /// If genetic algorithm was not explicit Stop (calling Stop method), you will need provide a new extended Termination. /// </remarks> /// </summary> public void Resume() { try { lock (m_lock) { m_stopRequested = false; } if (Population.GenerationsNumber == 0) { throw new InvalidOperationException("Attempt to resume a genetic algorithm which was not yet started."); } if (Population.GenerationsNumber > 1) { if (Termination.HasReached(this)) { throw new InvalidOperationException("Attempt to resume a genetic algorithm with a termination ({0}) already reached. Please, specify a new termination or extend the current one.".With(Termination)); } State = GeneticAlgorithmState.Resumed; } if (EndCurrentGeneration()) { return; } bool terminationConditionReached = false; DateTime startDateTime; do { if (m_stopRequested) { break; } startDateTime = DateTime.Now; terminationConditionReached = EvolveOneGeneration(); TimeEvolving += DateTime.Now - startDateTime; }while (!terminationConditionReached); } catch { State = GeneticAlgorithmState.Stopped; throw; } }
// GET: Terminations/Details/5 public async Task <ActionResult> Details(int?id) { if (id == null) { return(new HttpStatusCodeResult(HttpStatusCode.BadRequest)); } Termination termination = await db.Terminations.FindAsync(id); if (termination == null) { return(HttpNotFound()); } return(View(termination)); }
public virtual bool Handle(ref Page page, ISpider spider) { if (page == null || string.IsNullOrEmpty(page.Content)) { return(true); } if (Termination == null || !Termination.IsTermination(page, this)) { page.AddTargetRequests(GenerateRequests(page)); page.SkipExtractedTargetUrls = true; } return(true); }
// GET: Terminations/Edit/5 public async Task <ActionResult> Edit(int?id) { if (id == null) { return(new HttpStatusCodeResult(HttpStatusCode.BadRequest)); } Termination termination = await db.Terminations.FindAsync(id); if (termination == null) { return(HttpNotFound()); } ViewBag.EmployeeID = new SelectList(db.Employees, "EmployeeID", "Name", termination.EmployeeID); return(View(termination)); }
public ActionResult Edit(int id, FormCollection collection) { try { // TODO: Add update logic here var model = Termination.GetById(id); TryUpdateModel(model); model.SaveOrUpDate(); return(RedirectToAction("Index")); } catch { return(View()); } }
public void AddTermination() { if (btnAddTerm.Text == "Update Termination") { var id = Convert.ToInt32(dgTermination.SelectedDataKey[0]) != 0 ? Convert.ToInt32(dgTermination.SelectedDataKey[0]) : 0; if (id != 0) { var TermDate = txtTerminationDate.Text != "" ? txtTerminationDate.Text : ""; var LastDate = txtLastDate.Text != "" ? txtLastDate.Text : " "; Termination term = _presenter.CurrentEmployee.GetTerminations(id); term.TerminationDate = Convert.ToDateTime(TermDate); term.LastDateOfEmployee = Convert.ToDateTime(LastDate); term.Employee = _presenter.CurrentEmployee; term.ReccomendationForRehire = ddlRecommendation.Text; term.TerminationReason = txtTerminationReason.Text; _presenter.SaveOrUpdateEmployeeActivity(_presenter.CurrentEmployee); dgTermination.EditIndex = -1; dgTermination.DataSource = _presenter.CurrentEmployee.Terminations; dgTermination.DataBind(); _presenter.CurrentEmployee.GetActiveContract().Status = "In Active"; _presenter.CurrentEmployee.AppUser.IsActive = false; } PrintTransactionTermination(); ClearTerminationFormFields(); } else if (btnAddTerm.Text == "Add Termination") { var TermDate = txtTerminationDate.Text != "" ? txtTerminationDate.Text : ""; var LastDate = txtLastDate.Text != "" ? txtLastDate.Text : " "; Termination term = new Termination(); term.TerminationDate = Convert.ToDateTime(TermDate); term.LastDateOfEmployee = Convert.ToDateTime(LastDate); term.Employee = _presenter.CurrentEmployee; term.ReccomendationForRehire = ddlRecommendation.Text; term.TerminationReason = txtTerminationReason.Text; _presenter.CurrentEmployee.GetActiveContract().Status = "In Active"; _presenter.CurrentEmployee.AppUser.IsActive = false; _presenter.CurrentEmployee.Terminations.Add(term); _presenter.SaveOrUpdateEmployeeActivity(_presenter.CurrentEmployee); dgTermination.EditIndex = -1; dgTermination.DataSource = _presenter.CurrentEmployee.Terminations; dgTermination.DataBind(); } ClearTerminationFormFields(); }
public void EvolveNextGeneration() { try { lock (m_lock) { m_stopRequested = false; } if (Population.GenerationsNumber == 0) { throw new InvalidOperationException("Attempt to resume a genetic algorithm which was not yet started."); } if (Population.GenerationsNumber > 1) { if (Termination.HasReached(this)) { throw new InvalidOperationException("Attempt to resume a genetic algorithm with a termination ({0}) already reached. Please, specify a new termination or extend the current one.".With(Termination)); } State = GeneticAlgorithmState.Resumed; } if (EndCurrentGeneration()) { return; } bool terminationConditionReached = false; DateTime startDateTime; startDateTime = DateTime.Now; var parents = SelectParents(); var offspring = Cross(parents); Mutate(offspring); var newGenerationChromosomes = Reinsert(offspring, parents); Population.CreateNewGeneration(newGenerationChromosomes); TimeEvolving += DateTime.Now - startDateTime; } catch { State = GeneticAlgorithmState.Stopped; throw; } }
public ActionResult SendTo(int Id, byte?Send) { Termination Term = _hrUnitOfWork.TerminationRepository.Find(a => a.Id == Id).FirstOrDefault(); string error = ""; if (Send == 3) { _hrUnitOfWork.TrainingRepository.AddTrail(new AddTrailViewModel() { ColumnName = "ApprovalStatus", CompanyId = CompanyId, ObjectName = "EmpTermFollowUp", SourceId = Id.ToString(), UserName = UserName, ValueAfter = MsgUtils.Instance.Trls("EmployeeReview"), ValueBefore = MsgUtils.Instance.Trls("Submit") }); Term.ApprovalStatus = 3; error = AddWFTrans(Term, null, true); } else { _hrUnitOfWork.TrainingRepository.AddTrail(new AddTrailViewModel() { ColumnName = "ApprovalStatus", CompanyId = CompanyId, ObjectName = "EmpTermFollowUp", SourceId = Id.ToString(), UserName = UserName, ValueAfter = MsgUtils.Instance.Trls("ManagerReview"), ValueBefore = MsgUtils.Instance.Trls("Submit") }); Term.ApprovalStatus = 4; error = AddWFTrans(Term, null, null); } if (error.Length > 0) { return(Json(error)); } _hrUnitOfWork.TerminationRepository.Attach(Term); _hrUnitOfWork.TerminationRepository.Entry(Term).State = EntityState.Modified; try { _hrUnitOfWork.Save(); } catch (Exception ex) { var msg = _hrUnitOfWork.HandleDbExceptions(ex, Language); if (msg.Length > 0) { return(Json(msg)); } } return(Json("Ok")); }
public ActionResult Create(FormCollection collection) { try { // TODO: Add insert logic here var model = new Termination(); TryUpdateModel(model); model.CreatedAt = DateTime.Now; model.CreatedBy = SessionItems.CurrentUser.UserID; model.Insert(); return(RedirectToAction("Index")); } catch { return(View()); } }
public ExecutionResult Run() { ExecutionResult result = new ExecutionResult(); Chromosome oldBest = new Chromosome(ProblemParameters.Dimension); bool Continue = true; int uselessIterations = 0; CreateInitialPopulation(); result.NumberOfGenerations = 1; result.BestChromosomes.Add(_bestOfCurrentPopulation.Clone()); while (Continue) { _bestOfCurrentPopulation.CopyTo(oldBest); GenerateNextPopulation(); result.NumberOfGenerations++; result.BestChromosomes.Add(_bestOfCurrentPopulation.Clone()); // Check Termination Criteria if (result.NumberOfGenerations == Termination.MaxNumberOfGenerations) { Continue = false; } if (Termination.AreUselessIterations(oldBest, _bestOfCurrentPopulation)) { uselessIterations++; if (uselessIterations == Termination.MaxUselessIterations) { Continue = false; } } else { uselessIterations = 0; } } return(result); }
/// <summary>Assigns fitness function value to offsprings and registers new generation in a population.</summary> /// <param name="parents">Parents obtained form the ProduceOffsprings node.</param> /// <param name="offsprings">Offsprings obtained form the ProduceOffsprings node.</param> /// <param name="offspringsFitness">A list of fitness function results for offsprings.</param> /// <returns name="algorithm">A genetic algorithm instance supplemented with a new generation.</returns> public void ProduceNewGeneration(List <object> parents, List <object> offsprings, List <double> offspringsFitness) { if (State == GeneticAlgorithmState.TerminationReached) { return; } IList <IChromosome> parentsChromosomes = new List <IChromosome>(); foreach (object parent in parents) { parentsChromosomes.Add((IChromosome)parent); } IList <IChromosome> offspringsChromosomes = new List <IChromosome>(); foreach (object offspring in offsprings) { offspringsChromosomes.Add((IChromosome)offspring); offspringsChromosomes.Last().Fitness = offspringsFitness[offsprings.IndexOf(offspring)]; } Population.MinSize = Population.MaxSize; var newGenerationChromosomes = Reinsert(offspringsChromosomes, parentsChromosomes); while (newGenerationChromosomes.Count < Population.CurrentGeneration.Chromosomes.Count()) { newGenerationChromosomes = Reinsert(newGenerationChromosomes, parentsChromosomes); } Population.CreateNewGeneration(newGenerationChromosomes); Population.EndCurrentGeneration(); if (Termination.HasReached(this) || (Population.GenerationsNumber >= maxNumberOfIterations)) { State = GeneticAlgorithmState.TerminationReached; TimeEvolving = Timer.Elapsed; Timer.Stop(); } }
private string AddWFTrans(Termination request, int?ManagerId, bool?backToEmp, TerminationFormVM model) { var UserName = HttpContext.Current.User.Identity.Name; WfViewModel wf = new WfViewModel() { Source = "Termination", SourceId = model.CompanyId, DocumentId = request.Id, RequesterEmpId = request.EmpId, ApprovalStatus = request.ApprovalStatus, CreatedUser = UserName }; if (ManagerId != null) { wf.ManagerId = ManagerId; } else if (backToEmp != null) { wf.BackToEmployee = backToEmp.Value; } var wfTrans = hrUnitOfWork.LeaveRepository.AddWorkFlow(wf, model.Culture); request.WFlowId = wf.WFlowId; if (wfTrans == null && wf.WorkFlowStatus != "Success") { return(wf.WorkFlowStatus); } else if (wfTrans == null && wf.WorkFlowStatus == "Success") { request.ApprovalStatus = 6; } else if (wfTrans != null) { hrUnitOfWork.LeaveRepository.Add(wfTrans); } return(""); }
private string AddWFTrans(Termination request, int?ManagerId, bool?backToEmp) { WfViewModel wf = new WfViewModel() { Source = "Termination", SourceId = CompanyId, DocumentId = request.Id, RequesterEmpId = request.EmpId, ApprovalStatus = request.ApprovalStatus, CreatedUser = UserName }; if (ManagerId != null) { wf.ManagerId = ManagerId; } else if (backToEmp != null) { wf.BackToEmployee = backToEmp.Value; } var wfTrans = _hrUnitOfWork.LeaveRepository.AddWorkFlow(wf, Language); request.WFlowId = wf.WFlowId; if (wfTrans == null && wf.WorkFlowStatus != "Success") { return(wf.WorkFlowStatus); } else if (wfTrans == null && wf.WorkFlowStatus == "Success") { request.ApprovalStatus = 6; } else if (wfTrans != null) { _hrUnitOfWork.LeaveRepository.Add(wfTrans); } return(""); }
/// <summary> /// Create a transition between the given activity instances for the provided exit point /// </summary> public static void AddTermination(Workflow wf, WfActivity from, ExitPoint fromExitPoint, ExitPoint wfExitPoint) { // remove exiting conflicting transitions var toRemove = @from.ForwardTransitions.Where(t => t.FromExitPoint.Id == fromExitPoint.Id).ToList(); @from.ForwardTransitions.RemoveRange(toRemove); Entity.Delete(toRemove.Select(t => t.Id)); // remove existing conflicting terminations var toRemoveTerm = wf.Terminations.Where(t => t.FromActivity.Id == from.Id && t.FromExitPoint.Id == fromExitPoint.Id).ToList(); wf.Terminations.RemoveRange(toRemoveTerm); Entity.Delete(toRemoveTerm.Select(t => t.Id)); var term = new Termination() { Name = fromExitPoint.Name, FromActivity = @from, FromExitPoint = fromExitPoint, WorkflowExitPoint = wfExitPoint }; @from.ForwardTransitions.Add(term.As <TransitionStart>()); wf.Terminations.Add(term); }
/// <summary> /// Ends the current generation. /// </summary> /// <returns><c>true</c>, if current generation was ended, <c>false</c> otherwise.</returns> private bool EndCurrentGeneration() { EvaluateFitness(); Population.EndCurrentGeneration(); if (GenerationRan != null) { GenerationRan(this, EventArgs.Empty); } if (Termination.HasReached(this)) { State = GeneticAlgorithmState.TerminationReached; if (TerminationReached != null) { TerminationReached(this, EventArgs.Empty); } //Console.ForegroundColor = ConsoleColor.DarkGreen; //Console.WriteLine("Pick List Genetic Algorithm termination criteria are met."); //Console.ResetColor(); return(true); } if (m_stopRequested) { TaskExecutor.Stop(); State = GeneticAlgorithmState.Stopped; } //Console.ForegroundColor = ConsoleColor.Cyan; //Console.WriteLine("Pick List Genetic Algorithm will continue to evolve..."); //Console.ResetColor(); //Console.WriteLine(); return(false); }
public void SaveOrUpdateTermination(Termination termination) { _controller.SaveOrUpdateEntity(termination); }
public ActionResult CancelReq(int Id, short?Reason, string Desc) { Termination Term = _hrUnitOfWork.TerminationRepository.Find(a => a.Id == Id).FirstOrDefault(); _hrUnitOfWork.TrainingRepository.AddTrail(new AddTrailViewModel() { ColumnName = "CancelReason", CompanyId = CompanyId, ObjectName = "EmpTermFollowUp", SourceId = Id.ToString(), UserName = UserName, Version = 0, ValueAfter = _hrUnitOfWork.LookUpRepository.GetLookUpCodes("CancelReason", Language).Where(a => a.CodeId == Reason).Select(b => b.Title).FirstOrDefault(), ValueBefore = _hrUnitOfWork.LookUpRepository.GetLookUpUserCodes("CancelReason", Language).Where(a => a.CodeId == Term.CancelReason).Select(b => b.Title).FirstOrDefault() }); _hrUnitOfWork.TrainingRepository.AddTrail(new AddTrailViewModel() { ColumnName = "CancelDesc", CompanyId = CompanyId, ObjectName = "EmpTermFollowUp", SourceId = Id.ToString(), UserName = UserName, Version = Convert.ToByte(Request.Form["Version"]), ValueAfter = Desc, ValueBefore = Term.CancelDesc }); _hrUnitOfWork.TrainingRepository.AddTrail(new AddTrailViewModel() { ColumnName = "ApprovalStatus", CompanyId = CompanyId, ObjectName = "EmpTermFollowUp", SourceId = Id.ToString(), UserName = UserName, Version = Convert.ToByte(Request.Form["Version"]), ValueAfter = MsgUtils.Instance.Trls("Cancel before accepted"), ValueBefore = MsgUtils.Instance.Trls("Submit") }); Term.CancelDesc = Desc; Term.CancelReason = Reason; Term.ApprovalStatus = 7; string error = AddWFTrans(Term, null, null); if (error.Length > 0) { return(Json(error)); } _hrUnitOfWork.TerminationRepository.Attach(Term); _hrUnitOfWork.TerminationRepository.Entry(Term).State = EntityState.Modified; try { _hrUnitOfWork.Save(); } catch (Exception ex) { var msg = _hrUnitOfWork.HandleDbExceptions(ex, Language); if (msg.Length > 0) { return(Json(msg)); } } return(Json("Ok")); }
public ActionResult Details(TerminationFormViewModel model, OptionsViewModel moreInfo) { List <Error> errors = new List <Error>(); var message = "OK"; var Term = _hrUnitOfWork.TerminationRepository.Get(model.Id); if (ModelState.IsValid) { if (ServerValidationEnabled) { errors = _hrUnitOfWork.TerminationRepository.CheckForm(new CheckParm { CompanyId = CompanyId, ObjectName = "TermRequestForm", TableName = "Terminations", Columns = Models.Utils.GetColumnViews(ModelState.Where(a => !a.Key.Contains('.'))), ParentColumn = "CompanyId", Culture = Language }); if (errors.Count() > 0) { foreach (var e in errors) { foreach (var errorMsg in e.errors) { ModelState.AddModelError(errorMsg.field, errorMsg.message); } } return(Json(Models.Utils.ParseFormErrors(ModelState))); } } } else { return(Json(Models.Utils.ParseFormErrors(ModelState))); } if (Term == null) // New { Term = new Termination(); AutoMapper(new Models.AutoMapperParm { Destination = Term, Source = model, ObjectName = "TermRequestForm", Options = moreInfo, Transtype = TransType.Insert }); Term.CompanyId = CompanyId; Term.CreatedTime = DateTime.Now; Term.CreatedUser = UserName; Term.RequestDate = DateTime.Now; _hrUnitOfWork.TerminationRepository.Add(Term); } else // Edit { AutoMapper(new Models.AutoMapperParm { Destination = Term, Source = model, ObjectName = "TermRequestForm", Options = moreInfo, Transtype = TransType.Update }); Term.ModifiedTime = DateTime.Now; Term.ModifiedUser = UserName; Term.CompanyId = CompanyId; _hrUnitOfWork.TerminationRepository.Attach(Term); _hrUnitOfWork.TerminationRepository.Entry(Term).State = EntityState.Modified; } //Use 2 SaveChanges in same action to get Id of request to use it in Workflow Transation (WFTrans) errors = SaveChanges(Language); if (errors.Count > 0) { message = errors.First().errors.First().message; return(Json(message)); } if (Term.ApprovalStatus == 2) { string error = AddWFTrans(Term, null, null); if (error.Length > 0) { return(Json(error)); } var checklist = _hrUnitOfWork.CheckListRepository.GetTermCheckLists(CompanyId); if (checklist != null) { EmpChkList EmpList = _hrUnitOfWork.CheckListRepository.AddEmpChlst(checklist, UserName, Term.EmpId, CompanyId); _hrUnitOfWork.CheckListRepository.Add(EmpList); var checkTask = _hrUnitOfWork.CheckListRepository.ReadCheckListTask(checklist.Id).ToList(); if (checkTask.Count > 0) { _hrUnitOfWork.CheckListRepository.AddEmpTask(checkTask, UserName, EmpList); } } } errors = SaveChanges(Language); if (errors.Count > 0) { message = errors.First().errors.First().message; } return(Json(message)); }
public ActionResult TLHD(string selectedList) { QuangHanhManufacturingEntities db = new QuangHanhManufacturingEntities(); using (DbContextTransaction dbct = db.Database.BeginTransaction()) { try { Decision qd = new Decision(); var js = new JavaScriptSerializer(); var result = JsonConvert.DeserializeObject <List <GetListEmployees_Result> >(selectedList); //string[] date = result[0].terminate_date.Split('/'); var emp = new Employee(); if (result[0].decision_number.Equals("")) { qd.number = ""; foreach (var item in result) { emp = db.Employees.Where(x => x.employee_id == item.employee_id).FirstOrDefault(); emp.current_status_id = 4; } } else { string decision_number = result[0].decision_number + ""; List <Decision> check_list = db.Decisions.Where(x => x.number.Equals(decision_number)).ToList(); if (check_list.Count > 0) { return(Json(new { success = false, message = "Số quyết định trùng" }, JsonRequestBehavior.AllowGet)); } else { qd.number = decision_number; foreach (var item in result) { emp = db.Employees.Where(x => x.employee_id == item.employee_id).FirstOrDefault(); emp.current_status_id = 2; } } } qd.date = DateTime.ParseExact(result[0].terminate_date + "", "dd/MM/yyyy", null); db.Entry(emp).State = EntityState.Modified; db.Decisions.Add(qd); db.SaveChanges(); int maqd = db.Decisions.Select(n => n.decision_id).DefaultIfEmpty(0).Max(); foreach (var item in result) { Termination tlhd = new Termination(); tlhd.employee_id = item.employee_id; tlhd.decision_id = maqd; tlhd.terminate_date = DateTime.ParseExact(result[0].terminate_date + "", "dd/MM/yyyy", null); tlhd.termination_type_id = item.termination_type_id; db.Terminations.Add(tlhd); } db.SaveChanges(); dbct.Commit(); return(Json(new { success = true, message = "Tạo quyết định thành công" }, JsonRequestBehavior.AllowGet)); } catch (Exception e) { dbct.Rollback(); return(Json(new { success = false, message = "Lỗi" }, JsonRequestBehavior.AllowGet)); } } }