Exemple #1
0
        public void TestDate()
        {
            CreateScheduleViewModel createScheduleViewModel = new CreateScheduleViewModel();

            //Assert.True(createScheduleViewModel.Date == new DateTime(01/01/0001));
            Assert.True(createScheduleViewModel.Date == default);
        }
        public async Task <ActionResult> Delete(int id)
        {
            if (id > 0)
            {
                controllerName = this.ControllerContext.RouteData.Values["controller"].ToString();
                string strUrl = APIProvider.APIGenerator(controllerName, APIConstant.ACTION_DELETE);

                var model = new CreateScheduleViewModel();
                model.Detail = string.Empty;
                model.Title  = string.Empty;
                model.UserId = string.Empty;
                model.Color  = string.Empty;
                model.Start  = DateTime.Now;
                model.End    = DateTime.Now;
                model.Id     = id;
                var result = await APIProvider.Authorize_DynamicTransaction <CreateScheduleViewModel, int>(model, _userSession.BearerToken, strUrl, APIConstant.API_Resource_CORE, ARS.IgnoredARS);

                if (result > 0)
                {
                    TempData["Alert"] = ApplicationGenerator.RenderResult(ApplicationGenerator.TypeResult.SUCCESS, ApplicationGenerator.GeneralActionMessage(APIConstant.ACTION_DELETE, ApplicationGenerator.TypeResult.SUCCESS));
                }
                else
                {
                    TempData["Alert"] = ApplicationGenerator.RenderResult(ApplicationGenerator.TypeResult.FAIL, ApplicationGenerator.GeneralActionMessage(APIConstant.ACTION_DELETE, ApplicationGenerator.TypeResult.FAIL));
                }
                return(RedirectToAction("Index"));
            }
            else
            {
                TempData["Alert"] = ApplicationGenerator.RenderResult(ApplicationGenerator.TypeResult.FAIL, ApplicationGenerator.GeneralActionMessage(APIConstant.ACTION_DELETE, ApplicationGenerator.TypeResult.FAIL));
                return(View("Index"));
            }
        }
Exemple #3
0
        /// <summary>
        /// Takes a Schedule and returns it for addition
        /// </summary>
        /// <param name="schedule"></param>
        /// <returns>The Schedule to be added</returns>
        public Schedule AddSchedule(CreateScheduleViewModel createScheduleView)
        {
            var existingSchedule = _repo.Find(null, d => d.Name.ToLower() == createScheduleView.Name.ToLower())?.Items?.FirstOrDefault();

            if (existingSchedule != null)
            {
                throw new EntityAlreadyExistsException("Schedule name already exists");
            }

            var timeZone = GetTimeZoneId(createScheduleView.CRONExpressionTimeZone);

            if (timeZone == null)
            {
                throw new EntityOperationException("Unable to find the specified TimeZoneId");
            }

            if (createScheduleView.IsDisabled == false && !createScheduleView.StartingType.ToLower().Equals("manual"))//if schedule is not a manual starting type
            {
                if (createScheduleView.StartDate == null)
                {
                    throw new EntityOperationException("StartDate value cannot be null");
                }
            }

            Schedule newSchedule = createScheduleView.Map(createScheduleView);     //assign request to schedule entity

            return(newSchedule);
        }
Exemple #4
0
        public void CorrectCreateScheduleViewModel(string date, int subId, string expected)
        {
            CreateScheduleViewModel createScheduleViewModel = new CreateScheduleViewModel();
            var expDate = DateTime.Parse(date);

            createScheduleViewModel.Date = expDate;
            createScheduleViewModel.SelectedSubjectId = subId;
            Assert.True(createScheduleViewModel.CreateScheduleConcate() == expected);
        }
 public static ScheduleDTO CreateScheduleVMtoDTO(CreateScheduleViewModel createSchedule)
 {
     return(new ScheduleDTO
     {
         PatientId = createSchedule.PatientId,
         UserId = createSchedule.UserId,
         StartTime = createSchedule.StartTime,
         EndTime = createSchedule.EndTime
     });
 }
        public ActionResult Create()
        {
            var viewModel = new CreateScheduleViewModel
            {
                Hours         = TrainerRepo.Hours,
                DaysOfWeek    = TrainerRepo.DaysOfWeek,
                TrainingTypes = TrainerRepo.TrainingTypes,
            };

            return(View(viewModel));
        }
Exemple #7
0
        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            CreateScheduleViewModel model = (CreateScheduleViewModel)validationContext.ObjectInstance;

            if (model.StartDate.DayOfWeek != DayOfWeek.Sunday)
            {
                return(new ValidationResult(GetErrorMessage()));
            }

            return(ValidationResult.Success);
        }
        public async Task <ActionResult> ImportExcel()
        {
            var fileupload = Request.Files[0];

            if (fileupload != null)
            {
                var allowedExtensions = new[] { ".xls", ".xlsx", ".XLS", ".XLSX" };
                var extension         = Path.GetExtension(fileupload.FileName);
                if (allowedExtensions.Contains(extension))
                {
                    try
                    {
                        string filename = Path.GetFileName(fileupload.FileName);
                        string fullPath = Server.MapPath(ValueConstant.PATH_DOCS) + filename;
                        fileupload.SaveAs(fullPath);
                        var excel    = new ExcelQueryFactory(fullPath);
                        var schedule = from c in excel.Worksheet <ScheduleExcelViewModel>("Sheet1")
                                       select c;

                        controllerName = this.ControllerContext.RouteData.Values["controller"].ToString();
                        string strUrl = APIProvider.APIGenerator(controllerName, APIConstant.ACTION_INSERT);
                        if (schedule != null)
                        {
                            foreach (var item in schedule)
                            {
                                string apiUrl = "User?email=" + item.UserId;
                                var    userid = await APIProvider.Authorize_Get <string>(_userSession.BearerToken, apiUrl, APIConstant.API_Resource_CORE, ARS.Get);

                                var model = new CreateScheduleViewModel()
                                {
                                    Title     = item.Title,
                                    Priority  = item.Priority,
                                    Detail    = item.Detail,
                                    IsAlarm   = item.IsAlarm,
                                    Start     = item.Start,
                                    End       = item.End,
                                    Color     = item.Color,
                                    IsExamine = item.IsExamine,
                                    UserId    = userid
                                };
                                var result = await APIProvider.Authorize_DynamicTransaction <CreateScheduleViewModel, int>(model, _userSession.BearerToken, strUrl, APIConstant.API_Resource_CORE, ARS.Insert);
                            }
                            TempData["Alert"] = ApplicationGenerator.RenderResult(ApplicationGenerator.TypeResult.SUCCESS, ApplicationGenerator.GeneralActionMessage(APIConstant.ACTION_INSERT, ApplicationGenerator.TypeResult.SUCCESS));
                            return(RedirectToAction("Index"));
                        }
                    }
                    catch (Exception ex)
                    {
                        throw;
                    }
                }
            }
            return(RedirectToAction("Index"));
        }
Exemple #9
0
        // GET: Schedules/Create
        public ActionResult Create()
        {
            var listOfTrainingTypes = manager.ReturnTrainingTypesWithTrainers();



            var createViewModel = new CreateScheduleViewModel()
            {
                TrainingTypes = listOfTrainingTypes,
            };

            return(View(createViewModel));
        }
        public IActionResult CreateSchedule([FromBody] CreateScheduleViewModel createSchedule)
        {
            if (!_patientService.Exist(createSchedule.PatientId) && !_userService.Exist(createSchedule.UserId))
            {
                return(NotFound());
            }

            var scheduleDTO = ScheduleMapper.CreateScheduleVMtoDTO(createSchedule);

            _scheduleService.Create(scheduleDTO);

            return(Ok(ModelState));
        }
Exemple #11
0
        public ActionResult Index(int doctorId)
        {
            var doctor    = _doctorRepo.GetDoctorDetails(doctorId);
            var startDate = DateTime.Today;
            var endDate   = startDate.AddDays(7);
            var model     = new CreateScheduleViewModel
            {
                Doctor         = doctor,
                Schedules      = _scheduleRepo.GetSchedules(doctor.Id, startDate, endDate),
                AvailableDates = _scheduleService.GetAvailableDatesForNewSchedule(doctor, startDate, endDate)
            };

            return(View(model));
        }
        public CreateScheduleViewModel GetCreate(int Id)
        {
            var Store = this.service.FindById(Id);

            var Employees = this.service.GetEmployeesÍnStore(Store);

            var EmployeesInStore = new CreateScheduleViewModel();

            foreach (var employee in Employees)
            {
                EmployeesInStore.Users.Add(employee.UserId, employee.FullName);
            }

            return(EmployeesInStore);
        }
Exemple #13
0
        public IActionResult Create()
        {
            // Create a view model to hold data required to render the view
            CreateScheduleViewModel viewModel = new CreateScheduleViewModel();

            List <Student> stundetList = _context.Students.ToList <Student>();
            List <Tutor>   tutorList   = _context.Tutors.ToList <Tutor>();
            List <Subject> subjectList = _context.Subjects.ToList <Subject>();

            viewModel.Students = stundetList;
            viewModel.Tutors   = tutorList;
            viewModel.Subjects = subjectList;
            viewModel.Date     = DateTime.Now;

            return(View(viewModel));
        }
        public IActionResult CreateSchedule(CreateScheduleViewModel model)
        {
            if (!ModelState.IsValid)
            {
                return(View(model));
            }
            Schedule newSchedule = new Schedule
            {
                StartDate = model.StartDate,
                IsPosted  = false
            };

            context.Schedules.Add(newSchedule);
            context.SaveChanges();

            return(Redirect($"/admin/editschedule/{newSchedule.ID}"));
        }
        public void CreateSchedule(CreateScheduleViewModel create, string UsersTemplate)
        {
            var User         = UsersTemplate.Split(", ");
            var userfullname = User[1].Remove(User[1].Length - 1, 1);
            var UserId       = User[0].Remove(0, 1);
            var Schedule     = new EmployeeSchedule
            {
                StartDate        = create.StartDate,
                EndDate          = create.EndDate,
                EmployeeFullName = userfullname,
                User             = this.db.Users.FirstOrDefault(x => x.Id == UserId),
                UserId           = UserId
            };

            this.db.EmployeesSchedules.Add(Schedule);
            this.db.SaveChanges();
        }
Exemple #16
0
        public async Task <IActionResult> CreateSchedule(string SpecId)
        {
            var spec = await(from sp in DBContext.Specialities.Include(d => d.Disciplines)
                             where sp.Id.ToString() == SpecId
                             select sp).FirstOrDefaultAsync();
            var discs = await(from di in DBContext.Disciplines.Include(t => t.Teacher)
                              where spec.Disciplines.Contains(di)
                              select di).ToListAsync();
            var model = new CreateScheduleViewModel()
            {
                SpecialityId         = SpecId,
                AvailableDisciplines = discs,
                userGrants           = await checkService.getUserGrants(User)
            };

            model.init();
            return(View(model));
        }
        public ActionResult Edit(int?id)
        {
            Schedule schedule  = TrainerRepo.Schedules.Single(x => x.Id == id);
            var      viewModel = new CreateScheduleViewModel
            {
                Hours         = TrainerRepo.Hours,
                DaysOfWeek    = TrainerRepo.DaysOfWeek,
                TrainingTypes = TrainerRepo.TrainingTypes,
                Schedule      = schedule
            };

            if (id == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }

            return(View("Edit", viewModel));
        }
Exemple #18
0
        /// <summary>
        /// Updates a Schedule entity
        /// </summary>
        /// <param name="id"></param>
        /// <param name="request"></param>
        /// <returns></returns>
        public Schedule UpdateSchedule(string id, CreateScheduleViewModel request)
        {
            Guid entityId = new Guid(id);

            var existingSchedule = _repo.GetOne(entityId);

            if (existingSchedule == null)
            {
                throw new EntityDoesNotExistException("No Schedule exists for the specified id");
            }

            var namedSchedule = _repo.Find(null, d => d.Name.ToLower() == request.Name.ToLower() && d.Id != entityId)?.Items?.FirstOrDefault();

            if (namedSchedule != null && namedSchedule.Id != entityId)
            {
                throw new EntityAlreadyExistsException("Schedule already exists");
            }

            var timeZone = GetTimeZoneId(request.CRONExpressionTimeZone);

            if (timeZone == null)
            {
                throw new EntityOperationException("Unable to find the specified TimeZoneId");
            }

            existingSchedule.Name                   = request.Name;
            existingSchedule.AgentId                = request.AgentId;
            existingSchedule.AgentGroupId           = request.AgentGroupId;
            existingSchedule.CRONExpression         = request.CRONExpression;
            existingSchedule.CRONExpressionTimeZone = request.CRONExpressionTimeZone;
            existingSchedule.LastExecution          = request.LastExecution;
            existingSchedule.NextExecution          = request.NextExecution;
            existingSchedule.IsDisabled             = request.IsDisabled;
            existingSchedule.ProjectId              = request.ProjectId;
            existingSchedule.StartingType           = request.StartingType;
            existingSchedule.Status                 = request.Status;
            existingSchedule.ExpiryDate             = request.ExpiryDate;
            existingSchedule.StartDate              = request.StartDate;
            existingSchedule.AutomationId           = request.AutomationId;
            existingSchedule.MaxRunningJobs         = request.MaxRunningJobs;
            existingSchedule.QueueId                = request.QueueId;

            return(existingSchedule);
        }
 public ActionResult Create(Schedule schedule)
 {
     if (!ModelState.IsValid)
     {
         var viewModel = new CreateScheduleViewModel
         {
             Hours         = TrainerRepo.Hours,
             DaysOfWeek    = TrainerRepo.DaysOfWeek,
             TrainingTypes = TrainerRepo.TrainingTypes,
             Schedule      = schedule
         };
         return(View(viewModel));
     }
     else
     {
         TrainerRepo.Schedules.Add(schedule);
         return(RedirectToAction("ListAll"));
     }
 }
        public IActionResult CreateSchedule(CreateScheduleViewModel create, [FromForm] string UsersTemplate, int Id)
        {
            this.ViewBag.StoreId = Id;
            var UserId = UsersTemplate.Split(", ");

            if (!this.ModelState.IsValid)
            {
            }
            else
            {
                if (create.StartDate < DateTime.Today)
                {
                    ModelState.AddModelError("StartDate", "StartDate Must be Bigger Than The CurrenDate");
                }
                else if (create.EndDate < create.StartDate)
                {
                    ModelState.AddModelError("EndDate", "EndDate Must be Bigger Than The StartDate");
                }
                else if (string.IsNullOrEmpty(UsersTemplate))
                {
                    ModelState.AddModelError("UsersTemplate", "Please Select Employee");
                }
                else if (this.service.ISShiftAvailable(create.StartDate, create.EndDate))
                {
                    ModelState.AddModelError("StartDate", "This Shift Is Already Occupied");
                }
                else if (this.service.IsEmployeeInShift(UserId[0].Remove(0, 1)) != null)
                {
                    return(this.RedirectToAction("Edit", new { Id = this.service.IsEmployeeInShift(UserId[0].Remove(0, 1)) }));
                }
                else
                {
                    this.service.CreateSchedule(create, UsersTemplate);
                    return(this.RedirectToAction("Schedule", new { Id = Id }));
                }
                create = this.service.GetCreate(Id);
            }
            return(this.View(create));
        }
Exemple #21
0
        public async Task <IActionResult> Create([Bind("SelectedStudentId,SelectedTutorId,SelectedSubjectId,Date")] CreateScheduleViewModel scheduleDetails)
        {
            Schedule schedule = new Schedule();

            if (ModelState.IsValid)
            {
                schedule.Date = scheduleDetails.Date;

                schedule.Student = _context.Students.Find(scheduleDetails.SelectedStudentId);

                schedule.Tutor = _context.Tutors.Find(scheduleDetails.SelectedTutorId);

                schedule.Subject = _context.Subjects.Find(scheduleDetails.SelectedSubjectId);

                _context.Add(schedule);
                await _context.SaveChangesAsync();

                return(RedirectToAction(nameof(Index)));
            }

            return(View(schedule));
        }
Exemple #22
0
        // GET: Schedules/Edit/5
        public ActionResult Edit(int?id)
        {
            var listOfTrainingTypes = manager.ReturnTrainingTypesWithTrainers();

            Schedule schedule = manager.ReturnSchedule(id.Value);

            var createViewModel = new CreateScheduleViewModel()
            {
                TrainingTypes = listOfTrainingTypes,
                Schedule      = schedule
            };


            if (id == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }
            if (schedule == null)
            {
                return(HttpNotFound());
            }
            return(View(createViewModel));
        }
        public ActionResult Edit(CreateScheduleViewModel viewModel)
        {
            if (!ModelState.IsValid)
            {
                Schedule schedule     = TrainerRepo.Schedules.Single(x => x.Id == viewModel.Schedule.Id);
                var      newViewModel = new CreateScheduleViewModel
                {
                    Hours         = TrainerRepo.Hours,
                    DaysOfWeek    = TrainerRepo.DaysOfWeek,
                    TrainingTypes = TrainerRepo.TrainingTypes,
                    Schedule      = schedule
                };
                return(View(newViewModel));
            }

            int      index       = TrainerRepo.Schedules.FindIndex(t => t.Id == viewModel.Schedule.Id);
            Schedule newSchedule = viewModel.Schedule;

            TrainerRepo.Schedules.RemoveAt(index);
            TrainerRepo.Schedules.Insert(index, newSchedule);

            return(RedirectToAction("ListAll"));
        }
        public IActionResult CreateSchedule()
        {
            CreateScheduleViewModel model = new CreateScheduleViewModel();

            return(View());
        }
Exemple #25
0
        public async Task <IActionResult> Put(string id, [FromBody] CreateScheduleViewModel request)
        {
            try
            {
                //validate the cron expression
                if (!string.IsNullOrWhiteSpace(request.CRONExpression))
                {
                    try
                    {
                        CronExpression expression = CronExpression.Parse(request.CRONExpression, CronFormat.Standard);
                    }
                    catch (Exception ex)
                    {
                        ModelState.AddModelError("Save", string.Concat("Invalid cron expression, ", ex.Message));
                        return(BadRequest(ModelState));
                    }
                }

                Guid entityId = new Guid(id);

                var existingSchedule = repository.GetOne(entityId);
                if (existingSchedule == null)
                {
                    return(NotFound());
                }

                existingSchedule.Name           = request.Name;
                existingSchedule.AgentId        = request.AgentId;
                existingSchedule.CRONExpression = request.CRONExpression;
                existingSchedule.LastExecution  = request.LastExecution;
                existingSchedule.NextExecution  = request.NextExecution;
                existingSchedule.IsDisabled     = request.IsDisabled;
                existingSchedule.ProjectId      = request.ProjectId;
                existingSchedule.StartingType   = request.StartingType;
                existingSchedule.Status         = request.Status;
                existingSchedule.ExpiryDate     = request.ExpiryDate;
                existingSchedule.StartDate      = request.StartDate;
                existingSchedule.AutomationId   = request.AutomationId;

                var response = await base.PutEntity(id, existingSchedule);

                manager.DeleteExistingParameters(entityId);

                var set = new HashSet <string>();
                foreach (var parameter in request.Parameters ?? Enumerable.Empty <ParametersViewModel>())
                {
                    if (!set.Add(parameter.Name))
                    {
                        ModelState.AddModelError("ScheduleParameter", "ScheduleParameter Name Already Exists");
                        return(BadRequest(ModelState));
                    }

                    ScheduleParameter scheduleParameter = new ScheduleParameter
                    {
                        Name       = parameter.Name,
                        DataType   = parameter.DataType,
                        Value      = parameter.Value,
                        ScheduleId = entityId,
                        CreatedBy  = applicationUser?.UserName,
                        CreatedOn  = DateTime.UtcNow,
                        Id         = Guid.NewGuid()
                    };
                    scheduleParameterRepository.Add(scheduleParameter);
                }

                recurringJobManager.RemoveIfExists(existingSchedule.Id?.ToString());

                if (request.IsDisabled == false && !request.StartingType.ToLower().Equals("manual"))
                {
                    var jsonScheduleObj = JsonSerializer.Serialize <Schedule>(existingSchedule);

                    backgroundJobClient.Schedule(() => hubManager.ScheduleNewJob(jsonScheduleObj),
                                                 new DateTimeOffset(existingSchedule.StartDate.Value));
                }

                return(response);
            }
            catch (Exception ex)
            {
                ModelState.AddModelError("Schedule", ex.Message);
                return(BadRequest(ModelState));
            }
        }
Exemple #26
0
        public async Task <IActionResult> Post([FromBody] CreateScheduleViewModel request)
        {
            if (request == null)
            {
                ModelState.AddModelError("Save", "No data passed");
                return(BadRequest(ModelState));
            }

            //validate the cron expression
            if (!string.IsNullOrWhiteSpace(request.CRONExpression))
            {
                try
                {
                    CronExpression expression = CronExpression.Parse(request.CRONExpression, CronFormat.Standard);
                }
                catch (Exception ex)
                {
                    ModelState.AddModelError("Save", string.Concat("Invalid cron expression, ", ex.Message));
                    return(BadRequest(ModelState));
                }
            }

            Guid entityId = Guid.NewGuid();

            if (request.Id == null || !request.Id.HasValue || request.Id.Equals(Guid.Empty))
            {
                request.Id = entityId;
            }

            try
            {
                Schedule requestObj = request.Map(request); //assign request to schedule entity

                foreach (var parameter in request.Parameters ?? Enumerable.Empty <ParametersViewModel>())
                {
                    ScheduleParameter scheduleParameter = new ScheduleParameter
                    {
                        Name       = parameter.Name,
                        DataType   = parameter.DataType,
                        Value      = parameter.Value,
                        ScheduleId = entityId,
                        CreatedBy  = applicationUser?.UserName,
                        CreatedOn  = DateTime.UtcNow,
                        Id         = Guid.NewGuid()
                    };
                    scheduleParameterRepository.Add(scheduleParameter);
                }

                var response = await base.PostEntity(requestObj);

                recurringJobManager.RemoveIfExists(requestObj.Id?.ToString());

                if (request.IsDisabled == false && !request.StartingType.ToLower().Equals("manual"))
                {
                    var jsonScheduleObj = JsonSerializer.Serialize <Schedule>(requestObj);

                    backgroundJobClient.Schedule(() => hubManager.ScheduleNewJob(jsonScheduleObj),
                                                 new DateTimeOffset(requestObj.StartDate.Value));
                }

                return(response);
            }
            catch (Exception ex)
            {
                return(ex.GetActionResult());
            }
        }
Exemple #27
0
        public async Task <IActionResult> CreateSchedule(CreateScheduleViewModel model)
        {
            var spec = await(from sp in DBContext.Specialities.Include(s => s.Schedules)
                             where sp.Id.ToString() == model.SpecialityId select sp).FirstOrDefaultAsync();

            if (model.WeekScheduleName == null)
            {
                model.WeekScheduleName = "Без названия";
            }
            var NewWeekSchedule = new EWeekSchedule()
            {
                Name       = model.WeekScheduleName,
                Speciality = spec,
                Schedule   = new List <EDaySchedule>(6)
            };

            // DBContext.WeekSchedules.Add(NewWeekSchedule);

            NewWeekSchedule.Schedule.Add(new EDaySchedule()//mon
            {
                WeekSchedule      = NewWeekSchedule,
                DayNumber         = 0,
                DisciplinesForDay = new List <EScheduleItem>(8)
            });
            //DBContext.DaySchedules.Add(NewWeekSchedule.Schedule[0]);
            for (int i = 0; i < 8; i++)
            {
                var discipline = model.mon[i];
                discipline.DaySchedule = NewWeekSchedule.Schedule[0];
                if (discipline.DisciplineId.ToString() == "-1")
                {
                    discipline.Name       = "Нет пары";
                    discipline.TeacherFIO = "";
                    discipline.Type       = "";
                }
                else
                {
                    var disc = await(from di in DBContext.Disciplines.Include(t => t.Teacher)
                                     where di.Id == discipline.DisciplineId
                                     select di).FirstOrDefaultAsync();
                    discipline.Name       = disc.Name;
                    discipline.TeacherFIO = disc.Teacher.FIO;
                }
                if (discipline.Classroom == null)
                {
                    discipline.Classroom = "";
                }

                NewWeekSchedule.Schedule[0].DisciplinesForDay.Add(discipline);
            }

            NewWeekSchedule.Schedule.Add(new EDaySchedule() //tue
            {
                WeekSchedule      = NewWeekSchedule,
                DayNumber         = 1,
                DisciplinesForDay = new List <EScheduleItem>(8)
            });
            //DBContext.DaySchedules.Add(NewWeekSchedule.Schedule[0]);
            for (int i = 0; i < 8; i++)
            {
                var discipline = model.tue[i];
                discipline.DaySchedule = NewWeekSchedule.Schedule[1];
                if (discipline.DisciplineId.ToString() == "-1")
                {
                    discipline.Name       = "Нет пары";
                    discipline.TeacherFIO = "";
                    discipline.Type       = "";
                }
                else
                {
                    var disc = await(from di in DBContext.Disciplines.Include(t => t.Teacher)
                                     where di.Id == discipline.DisciplineId
                                     select di).FirstOrDefaultAsync();
                    discipline.Name       = disc.Name;
                    discipline.TeacherFIO = disc.Teacher.FIO;
                }
                if (discipline.Classroom == null)
                {
                    discipline.Classroom = "";
                }
                NewWeekSchedule.Schedule[1].DisciplinesForDay.Add(discipline);
            }

            NewWeekSchedule.Schedule.Add(new EDaySchedule()  //wed
            {
                WeekSchedule      = NewWeekSchedule,
                DayNumber         = 2,
                DisciplinesForDay = new List <EScheduleItem>(8)
            });
            //DBContext.DaySchedules.Add(NewWeekSchedule.Schedule[0]);
            for (int i = 0; i < 8; i++)
            {
                var discipline = model.wed[i];
                discipline.DaySchedule = NewWeekSchedule.Schedule[2];
                if (discipline.DisciplineId.ToString() == "-1")
                {
                    discipline.Name       = "Нет пары";
                    discipline.TeacherFIO = "";
                    discipline.Type       = "";
                }
                else
                {
                    var disc = await(from di in DBContext.Disciplines.Include(t => t.Teacher)
                                     where di.Id == discipline.DisciplineId
                                     select di).FirstOrDefaultAsync();
                    discipline.Name       = disc.Name;
                    discipline.TeacherFIO = disc.Teacher.FIO;
                }
                if (discipline.Classroom == null)
                {
                    discipline.Classroom = "";
                }
                NewWeekSchedule.Schedule[2].DisciplinesForDay.Add(discipline);
            }

            NewWeekSchedule.Schedule.Add(new EDaySchedule() //thu
            {
                WeekSchedule      = NewWeekSchedule,
                DayNumber         = 3,
                DisciplinesForDay = new List <EScheduleItem>(8)
            });
            //DBContext.DaySchedules.Add(NewWeekSchedule.Schedule[0]);
            for (int i = 0; i < 8; i++)
            {
                var discipline = model.thu[i];
                discipline.DaySchedule = NewWeekSchedule.Schedule[3];
                if (discipline.DisciplineId.ToString() == "-1")
                {
                    discipline.Name       = "Нет пары";
                    discipline.TeacherFIO = "";
                    discipline.Type       = "";
                }
                else
                {
                    var disc = await(from di in DBContext.Disciplines.Include(t => t.Teacher)
                                     where di.Id == discipline.DisciplineId
                                     select di).FirstOrDefaultAsync();
                    discipline.Name       = disc.Name;
                    discipline.TeacherFIO = disc.Teacher.FIO;
                }
                if (discipline.Classroom == null)
                {
                    discipline.Classroom = "";
                }
                NewWeekSchedule.Schedule[3].DisciplinesForDay.Add(discipline);
            }

            NewWeekSchedule.Schedule.Add(new EDaySchedule() //fri
            {
                WeekSchedule      = NewWeekSchedule,
                DayNumber         = 4,
                DisciplinesForDay = new List <EScheduleItem>(8)
            });
            //DBContext.DaySchedules.Add(NewWeekSchedule.Schedule[0]);
            for (int i = 0; i < 8; i++)
            {
                var discipline = model.fri[i];
                discipline.DaySchedule = NewWeekSchedule.Schedule[4];
                if (discipline.DisciplineId.ToString() == "-1")
                {
                    discipline.Name       = "Нет пары";
                    discipline.TeacherFIO = "";
                    discipline.Type       = "";
                }
                else
                {
                    var disc = await(from di in DBContext.Disciplines.Include(t => t.Teacher)
                                     where di.Id == discipline.DisciplineId
                                     select di).FirstOrDefaultAsync();
                    discipline.Name       = disc.Name;
                    discipline.TeacherFIO = disc.Teacher.FIO;
                }
                if (discipline.Classroom == null)
                {
                    discipline.Classroom = "";
                }
                NewWeekSchedule.Schedule[4].DisciplinesForDay.Add(discipline);
            }

            NewWeekSchedule.Schedule.Add(new EDaySchedule() //sat
            {
                WeekSchedule      = NewWeekSchedule,
                DayNumber         = 5,
                DisciplinesForDay = new List <EScheduleItem>(8)
            });
            //DBContext.DaySchedules.Add(NewWeekSchedule.Schedule[0]);
            for (int i = 0; i < 8; i++)
            {
                var discipline = model.sat[i];
                discipline.DaySchedule = NewWeekSchedule.Schedule[5];
                if (discipline.DisciplineId.ToString() == "-1")
                {
                    discipline.Name       = "Нет пары";
                    discipline.TeacherFIO = "";
                    discipline.Type       = "";
                }
                else
                {
                    var disc = await(from di in DBContext.Disciplines.Include(t => t.Teacher)
                                     where di.Id == discipline.DisciplineId
                                     select di).FirstOrDefaultAsync();
                    discipline.Name       = disc.Name;
                    discipline.TeacherFIO = disc.Teacher.FIO;
                }
                if (discipline.Classroom == null)
                {
                    discipline.Classroom = "";
                }
                NewWeekSchedule.Schedule[5].DisciplinesForDay.Add(discipline);
            }
            spec.Schedules.Add(NewWeekSchedule);
            DBContext.Add(NewWeekSchedule);
            await DBContext.SaveChangesAsync();

            return(RedirectToAction("Index", new { SpecId = spec.Id }));
        }
Exemple #28
0
        public async Task <IActionResult> Put(string id, [FromBody] CreateScheduleViewModel request)
        {
            try
            {
                ParametersViewModel.VerifyParameterNameAvailability(request.Parameters);
                //validate the cron expression
                if (!string.IsNullOrWhiteSpace(request.CRONExpression))
                {
                    if (string.IsNullOrWhiteSpace(request.CRONExpressionTimeZone))
                    {
                        request.CRONExpressionTimeZone = "UTC";
                    }
                    try
                    {
                        CronExpression expression = CronExpression.Parse(request.CRONExpression, CronFormat.Standard);
                    }
                    catch (Exception ex)
                    {
                        ModelState.AddModelError("Save", string.Concat("Invalid cron expression, ", ex.Message));
                        return(BadRequest(ModelState));
                    }
                }

                Schedule existingSchedule = _manager.UpdateSchedule(id, request);
                var      response         = await base.PutEntity(id, existingSchedule);

                _manager.DeleteExistingParameters(id);

                var set = new HashSet <string>();
                foreach (var parameter in request.Parameters ?? Enumerable.Empty <ParametersViewModel>())
                {
                    if (!set.Add(parameter.Name))
                    {
                        ModelState.AddModelError("ScheduleParameter", "ScheduleParameter Name Already Exists");
                        return(BadRequest(ModelState));
                    }

                    ScheduleParameter scheduleParameter = new ScheduleParameter
                    {
                        Name       = parameter.Name,
                        DataType   = parameter.DataType,
                        Value      = parameter.Value,
                        ScheduleId = existingSchedule.Id.Value,
                        CreatedBy  = applicationUser?.UserName,
                        CreatedOn  = DateTime.UtcNow,
                        Id         = Guid.NewGuid()
                    };
                    _scheduleParameterRepository.Add(scheduleParameter);
                }

                _recurringJobManager.RemoveIfExists(existingSchedule.Id?.ToString());

                if (request.IsDisabled == false && !request.StartingType.ToLower().Equals("manual"))
                {
                    var jsonScheduleObj = JsonSerializer.Serialize <Schedule>(existingSchedule);

                    _backgroundJobClient.Schedule(() => _hubManager.ScheduleNewJob(jsonScheduleObj),
                                                  new DateTimeOffset(existingSchedule.StartDate.Value));
                }

                return(response);
            }
            catch (Exception ex)
            {
                return(ex.GetActionResult());
            }
        }
Exemple #29
0
        public async Task <IActionResult> Post([FromBody] CreateScheduleViewModel request)
        {
            ParametersViewModel.VerifyParameterNameAvailability(request.Parameters);
            if (request == null)
            {
                ModelState.AddModelError("Save", "No data passed");
                return(BadRequest(ModelState));
            }

            //validate the cron expression
            if (!string.IsNullOrWhiteSpace(request.CRONExpression))
            {
                if (string.IsNullOrWhiteSpace(request.CRONExpressionTimeZone))
                {
                    request.CRONExpressionTimeZone = "UTC";
                }
                try
                {
                    CronExpression expression = CronExpression.Parse(request.CRONExpression, CronFormat.Standard);
                }
                catch (Exception ex)
                {
                    ModelState.AddModelError("Save", string.Concat("Invalid cron expression, ", ex.Message));
                    return(BadRequest(ModelState));
                }
            }

            Guid entityId = Guid.NewGuid();

            if (request.Id == null || !request.Id.HasValue || request.Id.Equals(Guid.Empty))
            {
                request.Id = entityId;
            }

            try
            {
                if (request.StartingType.ToLower() == "queuearrival")
                {
                    if (request.QueueId == null)
                    {
                        throw new EntityOperationException("Schedule of starting type \"QueueArrival\" must contain a Queue id");
                    }
                }

                Schedule newSchedule = _manager.AddSchedule(request);

                foreach (var parameter in request.Parameters ?? Enumerable.Empty <ParametersViewModel>())
                {
                    ScheduleParameter scheduleParameter = new ScheduleParameter
                    {
                        Name       = parameter.Name,
                        DataType   = parameter.DataType,
                        Value      = parameter.Value,
                        ScheduleId = entityId,
                        CreatedBy  = applicationUser?.UserName,
                        CreatedOn  = DateTime.UtcNow,
                        Id         = Guid.NewGuid()
                    };
                    _scheduleParameterRepository.Add(scheduleParameter);
                }

                var response = await base.PostEntity(newSchedule);

                _recurringJobManager.RemoveIfExists(newSchedule.Id?.ToString());

                if (request.IsDisabled == false && !request.StartingType.ToLower().Equals("manual"))//if schedule is not a manual starting type
                {
                    var jsonScheduleObj = JsonSerializer.Serialize <Schedule>(newSchedule);

                    _backgroundJobClient.Schedule(() => _hubManager.ScheduleNewJob(jsonScheduleObj),
                                                  new DateTimeOffset(newSchedule.StartDate.Value));
                }

                return(response);
            }
            catch (Exception ex)
            {
                return(ex.GetActionResult());
            }
        }