public async Task <PartialViewResult> GetTraining(TrainingViewModel model)
        {
            IEnumerable <EmployeeTraining> trainings = await db.GetTraining(this.ActiveCustomer);

            model.Courses = trainings.Select <EmployeeTraining, Course>(x => new Course {
                EducationType = x.EducationType, Description = x.Description
            }).Distinct().OrderBy(y => y.Description);

            if (model.CoursesCheck != null)
            {
                trainings = trainings.Where(x => model.CoursesCheck.Contains(x.EducationType));
            }

            if (model.OverdueCheck != null)
            {
                trainings = trainings.Where(x => model.OverdueCheck.Contains(x.ValidityEnd > DateTime.Now ? "0" : "1"));
            }

            model.Trainings           = trainings;
            model.TotalTrainings      = trainings.Count();
            model.OverdueCheck        = model.OverdueCheck ?? new List <String>();
            model.CoursesCheck        = model.CoursesCheck ?? new List <String>();
            model.TrainingContactLink = (new OverviewDAL().GetRiwalCompany(this.ActiveCustomer.DatabaseName, this.ActiveCustomer.CompanyId)).TrainingContactLink;

            return(PartialView("_TrainingPartial", model));
        }
        public async Task <TrainingViewModel> GetTrainingViewModelAsync(VacancyRouteModel vrm, VacancyUser user)
        {
            var vacancyTask = Utility.GetAuthorisedVacancyForEditAsync(
                _client, _vacancyClient, vrm, RouteNames.Training_Get);
            var programmesTask = _vacancyClient.GetActiveApprenticeshipProgrammesAsync();

            await Task.WhenAll(vacancyTask, programmesTask);

            var vacancy    = vacancyTask.Result;
            var programmes = programmesTask.Result;

            var vm = new TrainingViewModel
            {
                VacancyId           = vacancy.Id,
                SelectedProgrammeId = vacancy.ProgrammeId,
                Programmes          = programmes.ToViewModel(),
                PageInfo            = Utility.GetPartOnePageInfo(vacancy),
            };

            if (vacancy.Status == VacancyStatus.Referred)
            {
                vm.Review = await _reviewSummaryService.GetReviewSummaryViewModelAsync(vacancy.VacancyReference.Value,
                                                                                       ReviewFieldMappingLookups.GetTrainingReviewFieldIndicators());
            }

            return(vm);
        }
Exemplo n.º 3
0
        public void Train()
        {
            new TestScheduler().With(
                async scheduler =>
            {
                viewModel      = new TrainingViewModel(dataHandler.Object, dataViewModel.Object, trainingManager.Object, manager);
                var collection = new ObservableCollection <TrainedTreeData>();
                var tree       = TrainedTreeData.ConstructFromDocuments(new DocumentSet {
                    Document = new[] { new DocumentDefinition {
                                           Labels = new[] { "test" }
                                       } }
                });
                collection.Add(tree);
                dataViewModel.Setup(item => item.Result).Returns(documentSet);
                dataViewModel.Setup(item => item.SelectedItems).Returns(collection);

                trainingManager.Setup(item => item.Train(It.IsAny <DocumentSet>(), It.IsAny <TrainingHeader>(), It.IsAny <CancellationToken>()))
                .Returns(Task.FromResult(training));
                TrainingResults result = null;
                viewModel.Perform.Subscribe(
                    results =>
                {
                    result = results;
                });

                scheduler.AdvanceByMs(500);
                await viewModel.Perform.Execute();
                scheduler.AdvanceByMs(500);
                Assert.AreEqual(training, result);
            });
        }
Exemplo n.º 4
0
        /// <summary>
        ///Save Training details
        /// </summary>
        /// <param name="model">Training View Model</param>
        /// <returns>training list view</returns>
        public ActionResult SaveTrainingDetails(TrainingViewModel model)
        {
            if (model != null)
            {
                var trainingDetails = this._manageClient.SaveTrainingDetails(model);

                if (trainingDetails.TrainingID == 0)
                {
                    this.TempData["SucessAlert"] = "1";
                }
                else
                {
                    this.TempData["SucessAlert"] = "2";
                }


                if (this.Session["UserType"] != null)
                {
                    if (this.Session["UserType"].ToString() != "ADMN")
                    {
                        return(this.RedirectToAction("ClientDashboard", "ClientDashboard", new { Area = "Client", userStatus = this.Session["UserStatus"].ToString() }));
                    }
                    else
                    {
                        return(this.RedirectToAction("AdminDashboard", "AdminDashboard", new { Area = "Admin" }));
                    }
                }
            }

            return(this.RedirectToAction("AdminDashboard", "AdminDashboard", new { Area = "Admin" }));
        }
        public async Task <TrainingViewModel> GetTrainingViewModelAsync(VacancyRouteModel vrm, VacancyUser user)
        {
            var vacancyTask             = _utility.GetAuthorisedVacancyForEditAsync(vrm, RouteNames.Training_Get);
            var programmesTask          = _vacancyClient.GetActiveApprenticeshipProgrammesAsync();
            var isUsersFirstVacancyTask = IsUsersFirstVacancy(user.UserId);
            var getEmployerDataTask     = _employerVacancyClient.GetEditVacancyInfoAsync(vrm.EmployerAccountId);

            await Task.WhenAll(vacancyTask, programmesTask, isUsersFirstVacancyTask, getEmployerDataTask);

            var vacancy    = vacancyTask.Result;
            var programmes = programmesTask.Result;

            var vm = new TrainingViewModel
            {
                VacancyId                 = vacancy.Id,
                SelectedProgrammeId       = vacancy.ProgrammeId,
                Programmes                = programmes.ToViewModel(),
                IsUsersFirstVacancy       = isUsersFirstVacancyTask.Result && vacancy.TrainingProvider == null,
                PageInfo                  = _utility.GetPartOnePageInfo(vacancy),
                HasMoreThanOneLegalEntity = getEmployerDataTask.Result.LegalEntities.Count() > 1
            };

            if (vacancy.Status == VacancyStatus.Referred)
            {
                vm.Review = await _reviewSummaryService.GetReviewSummaryViewModelAsync(vacancy.VacancyReference.Value,
                                                                                       ReviewFieldMappingLookups.GetTrainingReviewFieldIndicators());
            }

            return(vm);
        }
Exemplo n.º 6
0
        public IActionResult AddCardioTraining(TrainingViewModel trainingViewModel)
        {
            try
            {
                if (String.IsNullOrEmpty(trainingViewModel.Exercise.Name))
                {
                    ModelState.AddModelError("Exercise", "Please fill in an exercise");
                    return(View(trainingViewModel));
                }

                IUser             user              = UserFactory.GetUser();
                IUserCollection   userCollection    = UserCollectionFactory.GetUserCollection();
                ExerciseDTO       exerciseDTO       = userCollection.GetExercise(trainingViewModel.Exercise.Name);
                CardioTrainingDTO cardioTrainingDTO = new CardioTrainingDTO(exerciseDTO, trainingViewModel.Distance, new TimeSpan(0, trainingViewModel.Minutes, trainingViewModel.Seconds), Guid.Parse(User.FindFirst("Id").Value), DateTime.Now, TrainingTypeDTO.Cardio);
                user.AddCardioTraining(cardioTrainingDTO);
                TempData["JustAddedTraining"] = true;
                return(LocalRedirect("/Home/Index"));
            }

            catch
            {
                TempData["Error"] = true;
                return(LocalRedirect("/Training/AddCardioTraining"));
            }
        }
Exemplo n.º 7
0
        public IActionResult TrainingDetail(string id)
        {
            User user = new User(null, Guid.Empty, null, null, null);
            TrainingViewModel trainingViewModel = new TrainingViewModel();
            Training          training          = ConvertTrainingDTO(user.GetTraining(id));

            if (training.TrainingType == TrainingType.Strength)
            {
                WeightTraining        weightTraining  = ConvertWeightTrainingDTO(user.GetWeightTraining(id));
                List <RoundViewModel> roundViewModels = new List <RoundViewModel>();
                foreach (var round in weightTraining.GetRounds())
                {
                    roundViewModels.Add(ConvertRoundVM(round));
                }
                trainingViewModel.Rounds       = roundViewModels;
                trainingViewModel.Date         = weightTraining.Date;
                trainingViewModel.TrainingID   = weightTraining.TrainingID;
                trainingViewModel.TrainingType = weightTraining.TrainingType;
            }
            else if (training.TrainingType == TrainingType.Cardio)
            {
                CardioTraining cardioTraining = ConvertCardioTrainingDTO(user.GetCardioTraining(id));
                trainingViewModel.Exercise     = ConvertExerciseToVM(cardioTraining.Exercise);
                trainingViewModel.Distance     = cardioTraining.Distance;
                trainingViewModel.Minutes      = cardioTraining.Time.Minutes;
                trainingViewModel.Seconds      = cardioTraining.Time.Seconds;
                trainingViewModel.TrainingID   = cardioTraining.TrainingID;
                trainingViewModel.TrainingType = cardioTraining.TrainingType;
            }
            return(View("../Training/TrainingDetail", trainingViewModel));
        }
Exemplo n.º 8
0
        public IActionResult EditTraining(TrainingViewModel model)
        {
            if (!ModelState.IsValid)
            {
                return(View(model));
            }

            //get training
            Training training = _trainingService.GetTrainingWithId(model.Id).FirstOrDefault();

            if (training == null)
            {
                ModelState.AddModelError("Error", "No such data!");
                return(View(model));
            }

            training.Title           = model.Title.ToCapital();
            training.TrainingPlaceId = model.PlaceId;
            training.DateTime        = model.Date.Add(model.Time.TimeOfDay);
            training.Description     = model.Description;
            training.Distance        = model.Distance;
            training.ModifiedDate    = DateTime.UtcNow;

            _trainingService.UpdateTraining(training);

            //delete old add new photo if any provided; else do not bother.
            if (model.Photo != null)
            {
                string fileName    = model.Photo.FileName;
                string contentType = model.Photo.ContentType;

                Stream       stream  = model.Photo.OpenReadStream();
                BinaryReader reader  = new BinaryReader(stream);
                byte[]       content = reader.ReadBytes((int)model.Photo.Length);

                //delete existing training photo
                TrainingPhoto photo = _trainingPhotoService.GetPhotoWithForeignKey(model.Id);
                if (photo != null)
                {
                    _trainingPhotoService.DeletePhoto(photo);
                }

                //add new
                photo = new TrainingPhoto
                {
                    Name         = model.Photo.FileName,
                    ContentType  = model.Photo.ContentType,
                    Content      = content,
                    AddedDate    = DateTime.UtcNow,
                    ModifiedDate = DateTime.UtcNow,
                    TrainingId   = model.Id
                };
                _trainingPhotoService.InsertPhoto(photo);
            }

            _trainingService.SaveTrainingChanges();
            _trainingPhotoService.SavePhotoChanges();

            return(RedirectToAction("Trainings"));
        }
        public ActionResult Edit(TrainingViewModel model)
        {
            var fileName  = Path.GetFileNameWithoutExtension(model.ImageFile.FileName);
            var extension = Path.GetExtension(model.ImageFile.FileName);

            fileName           = fileName + DateTime.Now.ToString("yymmssfff") + extension;
            model.ProjectPhoto = "~/Areas/production/images/" + fileName;
            fileName           = Path.Combine(Server.MapPath("~/Areas/production/images/"), fileName);
            model.ImageFile.SaveAs(fileName);

            TrainingDTO trainingDTO = new TrainingDTO
            {
                Id              = model.Id,
                Resource        = model.Resource.Trim(),
                Course          = model.Course.Trim(),
                Duration        = model.Duration.Trim(),
                FinalEvaluation = model.FinalEvaluation,
                ProjectPhoto    = model.ProjectPhoto.Trim(),
                CityId          = model.CityId,
                KnowledgeId     = model.KnowledgeId,
                UserId          = model.UserId
            };

            trainingService.Update(trainingDTO);

            return(RedirectToAction("Index"));
        }
Exemplo n.º 10
0
        public ActionResult Create(TrainingViewModel model)
        {
            if (model != null)
            {
                var fileName  = Path.GetFileNameWithoutExtension(model.ImageFile.FileName);
                var extension = Path.GetExtension(model.ImageFile.FileName);
                fileName           = fileName + DateTime.Now.ToString("yymmssfff") + extension;
                model.ProjectPhoto = "~/Areas/production/images/" + fileName;
                fileName           = Path.Combine(Server.MapPath("~/Areas/production/images/"), fileName);
                model.ImageFile.SaveAs(fileName);

                TrainingDTO training = new TrainingDTO
                {
                    Resource        = model.Resource,
                    Course          = model.Course,
                    Duration        = model.Duration,
                    FinalEvaluation = model.FinalEvaluation,
                    ProjectPhoto    = model.ProjectPhoto,
                    CityId          = model.CityId,
                    KnowledgeId     = model.KnowledgeId,
                    UserId          = model.UserId
                };

                trainingService.Create(training);

                ModelState.Clear();
                return(RedirectToAction("Index"));
            }

            return(View(model));
        }
Exemplo n.º 11
0
        /// <summary>
        /// save training item details
        /// </summary>
        /// <param name="trainingViewModel">training view model</param>
        /// <returns>Return training detail</returns>
        public TrainingViewModel SaveTrainingDetails(TrainingViewModel trainingViewModel)
        {
            Training trainingInstance;

            if (trainingViewModel.TrainingID == 0)
            {
                trainingInstance = new Training();
            }
            else
            {
                trainingInstance = this.unitOfWork.TrainingRepository.GetByID(trainingViewModel.TrainingID);
            }

            trainingInstance.TrainingName = trainingViewModel.TrainingName;

            trainingInstance.StartDate = DateTime.ParseExact(trainingViewModel.StartDate, "mm/dd/yyyy", CultureInfo.InvariantCulture);
            trainingInstance.EndDate   = DateTime.ParseExact(trainingViewModel.EndDate, "mm/dd/yyyy", CultureInfo.InvariantCulture);

            if (trainingViewModel.TrainingID == 0)
            {
                this.unitOfWork.TrainingRepository.Insert(trainingInstance);
            }
            else
            {
                this.unitOfWork.TrainingRepository.Update(trainingInstance);
            }

            this.unitOfWork.Save();
            return(trainingViewModel);
        }
Exemplo n.º 12
0
        // GET: Trainings/Create
        public IActionResult Create()
        {
            TrainingViewModel vm;

            vm = new TrainingViewModel(_context);
            return(View(vm));
        }
Exemplo n.º 13
0
        public async Task <IActionResult> Edit(int id, TrainingViewModel training)
        {
            if (id != training.Id)
            {
                return(NotFound());
            }

            if (ModelState.IsValid)
            {
                try
                {
                    _context.Update(training.GetModel());
                    await _context.SaveChangesAsync();
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!TrainingExists(training.Id))
                    {
                        return(NotFound());
                    }
                    else
                    {
                        throw;
                    }
                }
                return(RedirectToAction(nameof(Index)));
            }
            training.loadLists(_context);
            return(View(training));
        }
Exemplo n.º 14
0
        public int AddUpdateTraining(TrainingViewModel model, int userid, int OrganizationId)
        {
            Training training = Mapper.Map <TrainingViewModel, Training>(model);

            if (model.TrainingId == 0)
            {
                training.Active         = true;
                training.CreatedBy      = userid;
                training.CreatedOn      = DateTime.Now;
                training.OrganisationID = OrganizationId;
                base.Insert(training);
                this._unitOfWork.Save();
            }
            else
            {
                training = GetSingle(model.TrainingId, OrganizationId);
                training.TrainingNeed         = model.TrainingNeed;
                training.TrainerRequired      = model.TrainerRequired;
                training.TrainingType         = model.TrainingType;
                training.TrainingEventID      = model.TrainingEventID;
                training.IsAssignmentRequired = model.IsAssignmentRequired;
                training.AssignmentID         = model.AssignmentID;
                base.Update(training);
            }
            if (!string.IsNullOrWhiteSpace(model.YouTubeLink))
            {
                TrainingMaterial material = new TrainingMaterial();
                material.YouTubeLink    = model.YouTubeLink;
                material.TrainingId     = training.TrainingId;
                material.OrganizationId = OrganizationId;
                this._ITrainingMaterialRepository.Add(material, OrganizationId);
            }
            this._unitOfWork.Save();
            return(training.TrainingId);
        }
Exemplo n.º 15
0
        public Training(TrainingViewModel viewModel)
        {
            InitializeComponent();

            _viewModel  = viewModel;
            DataContext = viewModel;

            Loaded += delegate
            {
                App.ServiceCollection.Resolve <KeyboardHandler>().OnKeyDown += key =>
                {
                    if (!Keyboard.IsKeyDown(Key.LeftCtrl))
                    {
                        return;
                    }
                    if (key == Key.Right)
                    {
                        viewModel.CurrentStep++;
                    }
                    else if (key == Key.Left)
                    {
                        viewModel.CurrentStep--;
                    }
                };
            };
        }
        // PUT: api/Trainings
        public IHttpActionResult PutTraining(TrainingViewModel trainingModel)
        {
            if (!this.ModelState.IsValid)
            {
                return(this.Json(new { error = "Invalid model state." }));
            }

            var training = this.db.GetById(trainingModel.Id);

            if (training == null)
            {
                return(this.Json(new { error = "Training with provided Id not found." }));
            }

            if (training.UserId != this.User.Identity.GetUserId())
            {
                return(this.Json(new { error = "Cannot edit trainings you do not own" }));
            }

            this.Mapper.Map(trainingModel, training);

            db.Save();

            return(StatusCode(HttpStatusCode.NoContent));
        }
Exemplo n.º 17
0
        public ActionResult AdminCourse(int employeeid)
        {
            List <TrainingViewModel> Trainingviewmodellist = new List <TrainingViewModel>();

            List <Training> employeetraininglist = TrainingService.GetByEmployee(employeeid);

            using var context = new SqlLiteContext();
            List <Training> traininglist = context.Trainings.Where(a => a.IsDegree == false).ToList();

            foreach (Training t in traininglist)
            {
                TrainingViewModel tvm = new TrainingViewModel();
                tvm.TrainingId = t.TrainingId;
                tvm.EmployeeId = employeeid;
                tvm.Name       = t.Name;
                tvm.IsDegree   = t.IsDegree;
                foreach (Training te in employeetraininglist)
                {
                    if (t.TrainingId == te.TrainingId)
                    {
                        tvm.Connected = true;
                    }
                }
                Trainingviewmodellist.Add(tvm);
            }
            var sortedlist = Trainingviewmodellist.OrderBy(foo => foo.Name).ToList();
            var arv        = new BindEmployeeTrainingViewModel(sortedlist);

            return(View(arv));
        }
Exemplo n.º 18
0
        public IEnumerable <TrainingViewModel> GetAllTrainingsViewModel()
        {
            var trainings = this.trainingRepository.All()
                            .OrderBy(x => x.Name)
                            .ToList();

            var trainingsListModel = new List <TrainingViewModel>();

            foreach (var training in trainings)
            {
                var exercisesCount = this.db.Exercises.Where(x => x.TrainingsExercises.Any(x => x.TrainingId == training.Id)).Count();

                var usersCount = this.db.Users.Where(x => x.UsersTrainings.Any(x => x.TrainingId == training.Id)).Count();

                var trainingModel = new TrainingViewModel
                {
                    Id             = training.Id,
                    Name           = training.Name,
                    Description    = training.Description,
                    TrainingTime   = training.TrainingTime,
                    ExercisesCount = exercisesCount,
                    UsersCount     = usersCount,
                };

                trainingsListModel.Add(trainingModel);
            }

            return(trainingsListModel);
        }
Exemplo n.º 19
0
        public ActionResult Training()
        {
            var viewModel = new TrainingViewModel();

            viewModel.NewWords = db.Words.Find(x => x.ProcessDate == null).Take(5).ToArray();
            viewModel.OldWords = db.Words.Find(x => x.ProcessDate != null).OrderBy(x => x.ProcessDate).Take(5).ToArray();
            return(View(viewModel));
        }
Exemplo n.º 20
0
        public IHttpActionResult Post(TrainingViewModel model)
        {

            var training = _serviceTraining.Create(model.TrainingTypeId, model.RatePerHour);
            model.Id = training.Id;
            model.TrainingTypeName = training.TrainingType.Name;
            return Created<TrainingViewModel>(Request.RequestUri + training.Id.ToString(), model);
        }
Exemplo n.º 21
0
        public async Task <ActionResult> StartTraining()
        {
            var user = await UserManager.FindByIdAsync(User.Identity.GetUserId());

            TrainingViewModel training = repository.GetTrainings(user.Id);

            return(View(training));
        }
Exemplo n.º 22
0
        public async Task <ActionResult <int> > Create([FromBody] TrainingViewModel model)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            return(await trainingRepository.Create(model));
        }
Exemplo n.º 23
0
 public IActionResult Create(TrainingViewModel trainingVM)
 {
     if (ModelState.IsValid)
     {
         trainingManager.Add(Mapper.Map <TrainingViewModel, Training>(trainingVM));
         return(RedirectToAction(nameof(Index)));
     }
     return(View(trainingVM));
 }
Exemplo n.º 24
0
        /// <summary>
        /// get training details
        /// </summary>
        /// <param name="trainingID"> trainingID</param>
        /// <returns>Return training detail</returns>
        public TrainingViewModel GetTrainingDetailsById(int trainingID)
        {
            var trainingDetails = this.unitOfWork.TrainingRepository.GetByID(trainingID);
            TrainingViewModel trainingViewModel = new TrainingViewModel();

            trainingViewModel.TrainingID   = trainingDetails.TrainingID;
            trainingViewModel.TrainingName = trainingDetails.TrainingName;
            trainingViewModel.StartDate    = String.Format("{0:d}", trainingDetails.StartDate).Replace("-", "/");
            trainingViewModel.EndDate      = String.Format("{0:d}", trainingDetails.EndDate).Replace("-", "/");
            return(trainingViewModel);
        }
Exemplo n.º 25
0
        private TrainingViewModel ConvertTrainingDTO(TrainingDTO trainingDTO)
        {
            TrainingViewModel training = new TrainingViewModel
            {
                Date         = trainingDTO.Date,
                TrainingID   = trainingDTO.TrainingID,
                TrainingType = (TrainingType)trainingDTO.TrainingType
            };

            return(training);
        }
Exemplo n.º 26
0
        public async Task <IActionResult> Create(TrainingViewModel training)
        {
            if (ModelState.IsValid)
            {
                _context.Add(training.GetModel());
                await _context.SaveChangesAsync();

                return(RedirectToAction(nameof(Index)));
            }
            training.loadLists(_context);
            return(View(training));
        }
Exemplo n.º 27
0
        public DefinitionPage(TrainingViewModel parent, CharDef[] list)
        {
            InitializeComponent();
            Parent = parent;
            DefinitionScrollList.ItemsSource = items;
            foreach (CharDef cd in list)
            {
                items.Add(cd);
            }

            BindingContext = DefinitionViewModel = new DefinitionViewModel(parent);
        }
Exemplo n.º 28
0
 public void ChangeVisibility()
 {
     new TestScheduler().With(
         scheduler =>
     {
         viewModel = new TrainingViewModel(dataHandler.Object, dataViewModel.Object, trainingManager.Object, manager);
         Assert.AreEqual(Visibility.Collapsed, viewModel.Visibility);
         dataViewModel.Setup(item => item.Result).Returns(documentSet);
         dataViewModel.Raise(item => item.PropertyChanged += null, new PropertyChangedEventArgs("Result"));
         scheduler.AdvanceByMs(500);
         Assert.AreEqual(Visibility.Visible, viewModel.Visibility);
     });
 }
Exemplo n.º 29
0
            public ViewModel(List <CarWithTyres> cars)
            {
                OutputKeys     = new BetterObservableCollection <SettingEntry>();
                OutputKeysView = new BetterListCollectionView(OutputKeys)
                {
                    GroupDescriptions = { new PropertyGroupDescription(nameof(SettingEntry.Tag)) },
                    CustomSort        = KeyComparer.Instance
                };

                TrainingModel    = new TrainingViewModel();
                ExampleCarsModel = new ExampleCarsViewModel(cars);
                ExampleCarsModel.InvalidatePlotModel += OnInvalidatePlotModel;
            }
Exemplo n.º 30
0
        public IActionResult AddTraining(TrainingViewModel model)
        {
            if (!ModelState.IsValid)
            {
                return(View(model));
            }

            //add training
            Training training = new Training
            {
                Title           = model.Title.ToCapital(),
                TrainingPlaceId = model.PlaceId,
                DateTime        = model.Date.Add(model.Time.TimeOfDay),
                Description     = model.Description,
                Distance        = model.Distance,
                AddedDate       = DateTime.UtcNow,
                ModifiedDate    = DateTime.UtcNow
            };

            long trainingId = _trainingService.InsertTraining(training);

            //add related image if any; else do not bother now.
            //TODO: Later give an error
            if (model.Photo != null)
            {
                string fileName    = model.Photo.FileName;
                string contentType = model.Photo.ContentType;

                Stream       stream  = model.Photo.OpenReadStream();
                BinaryReader reader  = new BinaryReader(stream);
                byte[]       content = reader.ReadBytes((int)model.Photo.Length);

                TrainingPhoto photo = new TrainingPhoto
                {
                    Name         = model.Photo.FileName,
                    ContentType  = model.Photo.ContentType,
                    Content      = content,
                    AddedDate    = DateTime.UtcNow,
                    ModifiedDate = DateTime.UtcNow,
                    TrainingId   = trainingId
                };

                _trainingPhotoService.InsertPhoto(photo);
            }

            _trainingService.SaveTrainingChanges();
            _trainingPhotoService.SavePhotoChanges();

            return(RedirectToAction("Trainings"));
        }
        // POST: api/Trainings
        public IHttpActionResult PostTraining(TrainingViewModel model)
        {
            if (!ModelState.IsValid)
            {
                return this.Json(new { error = "Invalid model state." });
            }

            var training = Mapper.Map<Training>(model);
            training.UserId = User.Identity.GetUserId();

            db.Add(training);
            db.Save();

            return Ok(training.Id);
        }
        // POST: api/prognosis/training
        public IHttpActionResult PostTraining(TrainingViewModel model)
        {
            if (!ModelState.IsValid)
            {
                return this.Json(new { error = "Invalid model state." });
            }

            var training = Mapper.Map<Training>(model);
            // id needed for caching
            training.UserId = User.Identity.GetUserId();
            var prognosedTraining = this.trainingPrediction.Predict(training);
            var prognosisViewModel = Mapper.Map<TrainingPrognosisViewModel>(prognosedTraining);

            return Json(prognosisViewModel);
        }
        // PUT: api/Trainings
        public IHttpActionResult PutTraining(TrainingViewModel trainingModel)
        {
            if (!this.ModelState.IsValid)
            {
                return this.Json(new { error = "Invalid model state." });
            }

            var training = this.db.GetById(trainingModel.Id);
            if (training == null)
            {
                return this.Json(new { error = "Training with provided Id not found." });
            }

            if (training.UserId != this.User.Identity.GetUserId())
            {
                return this.Json(new { error = "Cannot edit trainings you do not own" });
            }

            this.Mapper.Map(trainingModel, training);

            db.Save();

            return StatusCode(HttpStatusCode.NoContent);
        }