Esempio n. 1
0
        public IActionResult Update(int id, UpdateModel model)
        {
            //Finding who is logged in
            int logged_in_user = int.Parse(User.Identity.Name);

            // map model to entity and set id
            var user = _mapper.Map <User>(model);

            user.Id = id;

            //Rejecting access if the logged in user is not same as the user updating information
            if (logged_in_user != id)
            {
                return(BadRequest(new { message = "Access Denied" }));
            }

            try
            {
                // update user
                _userService.Update(user, model.CurrentPassword, model.NewPassword, model.ConfirmNewPassword);
                return(Ok());
            }
            catch (AppException ex)
            {
                // return error message if there was an exception
                return(BadRequest(new { message = ex.Message }));
            }
        }
Esempio n. 2
0
        private static async Task <int> GetRecordID(int domainID, UpdateModel um)
        {
            int recordID;
            var records = await RecordService.GetList(domainID, um.SubDomain);

            if (records.Status.Code != 1)
            {
                throw new APIException(records.Status);
            }


            var record = records.Records.FirstOrDefault(_ => _.Type == "A" && _.Enabled == 1);

            if (record == null)
            {
                var newRecord = await RecordService.CreateRecord(domainID, um.SubDomain, "A", um.LineName, "0.0.0.0", 0, 300);

                if (newRecord.Status.Code != 1)
                {
                    throw new APIException(newRecord.Status);
                }

                recordID = newRecord.Info.RecordID;
            }
            else
            {
                recordID = record.ID;
            }

            return(recordID);
        }
Esempio n. 3
0
        public void UpdateUser()
        {
            // Arrange
            Mock <IUserService> userService = new Mock <IUserService>();
            User user = new User()
            {
                Id        = 1,
                FirstName = "admin",
                LastName  = "admin",
                Username  = "******",
            };

            userService.Setup(m => m.Update(user, "admin"));
            ;
            Mock <ILogger <UserController> > logger = new Mock <ILogger <UserController> >();
            var mockMapper = new MapperConfiguration(cfg =>
            {
                cfg.AddProfile(new AutoMapperProfile());
            });
            var mapper      = mockMapper.CreateMapper();
            var updateModel = new UpdateModel()
            {
                FirstName = "admin2", LastName = "admin2", Username = "******", Password = "******"
            };
            var controller = new UserController(logger.Object, userService.Object, mapper);

            // Act
            var result = controller.Update(1, updateModel);

            // Assert
            Assert.True(result is OkResult);
            Assert.AreEqual(StatusCodes.Status200OK, ((OkResult)result).StatusCode);
        }
        public IActionResult Update(int id, [FromBody] UpdateModel model)
        {
            var currentUserId = int.Parse(User.Identity.Name);

            if (id != currentUserId)
            {
                return(Forbid());
            }
            // map model to entity and set id
            var user = _mapper.Map <User>(model);

            user.Id = id;

            try
            {
                // update user
                _userService.Update(user, model.Password);
                return(Ok());
            }
            catch (AppException ex)
            {
                // return error message if there was an exception
                return(BadRequest(new { message = ex.Message }));
            }
        }
 public ObservableCollectionMapper(ConstructModel constructModel, GetEntity getEntity, UpdateModel updateModel, Comparison <TViewModel> comparison)
 {
     this.constructModel = constructModel;
     this.getEntity      = getEntity;
     this.updateModel    = updateModel;
     this.comparison     = comparison;
 }
        public ValueGroup CalculateTotalFinishedShows(UpdateModel tvdbData)
        {
            var showList = GetAllSeries();
            var count    = 0;

            foreach (var show in showList)
            {
                var totalEpisodes = tvdbData.IdList.FirstOrDefault(x => x.ShowId == show.GetProviderId(MetadataProviders.Tvdb))?.Count ?? 0;
                var seenEpisodes  = GetPlayedEpisodeCount(show);

                if (seenEpisodes > totalEpisodes)
                {
                    totalEpisodes = seenEpisodes;
                }

                if (totalEpisodes > 0 && totalEpisodes == seenEpisodes)
                {
                    count++;
                }
            }

            return(new ValueGroup
            {
                Title = Constants.TotalShowsFinished,
                ValueLineOne = $"{count}",
                ValueLineTwo = "",
                ExtraInformation = User != null ? Constants.HelpUserTotalShowsFinished : null
            });
        }
        public void CheckVersionShowDifferencesTest()
        {
            var OldFilePath = CreateFiles("TestOld");
            var NewFilePath = CreateFiles("TestNew", true);

            var model = new UpdateModel
            {
                UserParams = new UserParams
                {
                    IntepubDirectory = new DirectoryInfo(OldFilePath)
                },
                UnZipDirectory = new DirectoryInfo(NewFilePath)
            };

            var result = new CheckVersionProcess(new ConfigurationBuilder()
                                                 .SetBasePath(Directory.GetCurrentDirectory())
                                                 .AddJsonFile("appsettings.json", optional: true).Build(), null).Process(model);

            try
            {
                Assert.Contains(Consts.ProcesEventResult.Successful, result.Result);
            }
            finally
            {
                Directory.Delete(OldFilePath, true);
                Directory.Delete(NewFilePath, true);
            }
        }
Esempio n. 8
0
        /// <summary>
        /// API to update employee details
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        #region UpdateEmployeeDetails
        public int UpdateEmployeeDetails(UpdateModel data)
        {
            SqlConnection connection = DatabaseConnection();

            try
            {
                UpdateModel employee = new UpdateModel();

                SqlCommand command = StoreProcedureConnection("spUpdateEmployeeDetails", connection);
                command.Parameters.AddWithValue("@EmployeeId", data.EmployeeId);
                command.Parameters.AddWithValue("@FirstName", data.FirstName);
                command.Parameters.AddWithValue("@LastName", data.LastName);
                command.Parameters.AddWithValue("@Email", data.Email);
                command.Parameters.AddWithValue("@UserName", data.UserName);
                command.Parameters.AddWithValue("@Password", data.Password);
                command.Parameters.AddWithValue("@City", data.City);
                connection.Open();
                SqlDataReader reader = command.ExecuteReader();
                reader.Read();
                return((int)reader[0]);
            }
            catch (Exception e)
            {
                throw new Exception(e.Message);
            }
            finally
            {
                connection.Close();
            }
        }
Esempio n. 9
0
 public PluginConfiguration()
 {
     UserStats          = new List <UserStat>();
     GeneralStat        = new List <ValueGroup>();
     Charts             = new List <ChartModel>();
     TotalEpisodeCounts = new UpdateModel();
 }
Esempio n. 10
0
        public IActionResult Update(GetMemberDetailDto dto)
        {
            var getMemberDetailResult = _memberService.GetMemberDetail(dto);

            if (getMemberDetailResult.Code > 0)
            {
                return(Json(getMemberDetailResult));
            }

            var pagedQueryRolesResult = _roleService.PagedQueryRoles(new PagedQueryRoleDto
            {
                PageSize = 100
            });

            if (pagedQueryRolesResult.Code > 0)
            {
                return(Json(pagedQueryRolesResult));
            }

            var model = new UpdateModel
            {
                Member = getMemberDetailResult.Data,
                Roles  = pagedQueryRolesResult.Data.List
            };

            return(View("~/Administration/Views/Member/Update.cshtml", model));
        }
Esempio n. 11
0
        public ActionResult Edit([Bind(Include = "Message, Title")] UpdateModel model, int?id)
        {
            if (id == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }
            BlogPost blogPost = _uow.GetRepository <IBlogPostRepository>().GetOneByUserAndId(id.Value, User.Identity.GetUserId <int>());

            if (blogPost == null)
            {
                return(HttpNotFound());
            }

            if (ModelState.IsValid)
            {
                blogPost = model.UpdateBlogPost(blogPost);

                _uow.GetRepository <IBlogPostRepository>().Update(blogPost);
                _uow.Commit();
                this.FlashSuccess("You successfully edited a blogpost-");
                return(RedirectToAction("Edit", new { id = id.Value }));
            }
            this.FlashDanger("There were errors on form-");
            return(View(model));
        }
        private async Task GoTo(string itemPage, UpdateModel updateModel = null)
        {
            //construct parameters based on model
            string parameters = updateModel != null?JsonConvert.SerializeObject(updateModel) : "";

            //get current location
            string location = Shell.Current.CurrentState.Location.ToString();

            location = location.Replace("//", "");
            string[] path = location.Split('/');
            if (path[0] == "EntireItems")
            {
                await Shell.Current.GoToAsync($"///EntireItems?update={parameters}", false);

                await Shell.Current.GoToAsync($"///{itemPage}?update={parameters}", false);
            }
            else
            {
                await Task.WhenAll(Shell.Current.GoToAsync($"///{itemPage}?update={parameters}", false),
                                   Shell.Current.GoToAsync($"///EntireItems?update={parameters}", false),
                                   Shell.Current.GoToAsync($"///{itemPage}", false));
            }
            if (IsUwp)
            {
                await Task.WhenAll(Shell.Current.GoToAsync("///EntireItems", false), Shell.Current.GoToAsync($"///{itemPage}", false));
            }
        }
        public async Task <IActionResult> Update(int id, [FromBody] UpdateModel model)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            // map model to entity and set id
            var user = _mapper.Map <User>(model);

            user.Id = id;

            try
            {
                // update user
                user = await _userService.Update(user, model.Password);

                var view = _mapper.Map <UserModel>(user);

                return(Ok(view));
            }
            catch (AppException ex)
            {
                // return error message if there was an exception
                return(BadRequest(new { message = ex.Message }));
            }
        }
Esempio n. 14
0
        public ActionResult <UpdateModel <ContentModel> > MyContentUpdate(UpdateModel <ContentModel> updateModel)
        {
            try
            {
                return(Ok(_serviceContent.MyContentUpdate(updateModel)));
            }

            catch (ValidationException exception)
            {
                var validationResult = exception.ValidationResult;
                foreach (var t in validationResult)
                {
                    ModelState.AddModelError(t.PropertyName, t.ErrorMessage);
                }
                return(BadRequest(ModelState));
            }

            catch (NotFoundException ex)
            {
                ModelState.AddModelError("ErrorMessage", ex.ToString());
                return(BadRequest(ModelState));
            }

            catch (Exception exception)
            {
                ModelState.AddModelError("ErrorMessage", exception.Message);
                return(BadRequest(ModelState));
            }
        }
        public void CheckVersionNewerFileInOldApp()
        {
            var NewFilePath = CreateFiles("TestNew", true);
            var OldFilePath = CreateFiles("TestOld");


            var model = new UpdateModel
            {
                UserParams = new UserParams
                {
                    IntepubDirectory = new DirectoryInfo(OldFilePath)
                },
                UnZipDirectory = new DirectoryInfo(NewFilePath)
            };

            var result = new CheckVersionProcess(new ConfigurationBuilder()
                                                 .SetBasePath(Directory.GetCurrentDirectory())
                                                 .AddJsonFile("appsettings.json", optional: true).Build(), null);

            result.ProcessEvent += ResultProcessEventMockNewerFile;
            result.ConfirmEvent += ResultConfirmEventMockContinueConfirmation;

            try
            {
                result.Process(model);
            }
            finally
            {
                Directory.Delete(OldFilePath, true);
                Directory.Delete(NewFilePath, true);
            }
        }
Esempio n. 16
0
 private void OnUpdatesArrived(UpdateModel updates)
 {
     foreach (var u in updates.updates)
     {
         this.ParseUpdate(u);
     }
 }
        public void CheckVersionContinuationDisagreementTest()
        {
            var NewFilePath = CreateFiles("TestNew", true);
            var OldFilePath = CreateFiles("TestOld");

            var model = new UpdateModel
            {
                UserParams = new UserParams
                {
                    IntepubDirectory = new DirectoryInfo(OldFilePath)
                },
                UnZipDirectory = new DirectoryInfo(NewFilePath)
            };

            var environmentManagerMock = new EnvironmentManagerMock();

            var result = new CheckVersionProcess(new ConfigurationBuilder()
                                                 .SetBasePath(Directory.GetCurrentDirectory())
                                                 .AddJsonFile("appsettings.json", optional: true).Build(), environmentManagerMock);


            result.ProcessEvent += ResultProcessEventMockNewerFile;
            result.ConfirmEvent += ResultConfirmEventContinuingCancellation;

            try
            {
                result.Process(model);
                Assert.True(environmentManagerMock.Counter > 0);
            }
            finally
            {
                Directory.Delete(NewFilePath, true);
                Directory.Delete(OldFilePath, true);
            }
        }
Esempio n. 18
0
        public async Task <IActionResult> Edit(int id, [Bind("Id,Updated,UserId,Details")] UpdateModel updateModel)
        {
            if (id != updateModel.Id)
            {
                return(NotFound());
            }

            if (ModelState.IsValid)
            {
                try
                {
                    _context.Update(updateModel);
                    await _context.SaveChangesAsync();
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!UpdateModelExists(updateModel.Id))
                    {
                        return(NotFound());
                    }
                    else
                    {
                        throw;
                    }
                }
                return(RedirectToAction(nameof(Index)));
            }
            return(View(updateModel));
        }
        public void CheckVersionFilesNotFound()
        {
            var DirectoryWithoutFilesPath = CreateFiles("old", havingNoFiles: true);

            var model = new UpdateModel
            {
                UserParams = new UserParams
                {
                    IntepubDirectory = new DirectoryInfo(DirectoryWithoutFilesPath)
                },
                UnZipDirectory = new DirectoryInfo(DirectoryWithoutFilesPath)
            };

            var result = new CheckVersionProcess(new ConfigurationBuilder()
                                                 .SetBasePath(Directory.GetCurrentDirectory())
                                                 .AddJsonFile("appsettings.json", optional: true).Build(), null);

            try
            {
                Assert.Throws <Exception>(() => result.Process(model));
            }
            finally
            {
                Directory.Delete(DirectoryWithoutFilesPath);
            }
        }
Esempio n. 20
0
        public ActionResult <UpdateModel <PartModel> > Update(UpdateModel <PartModel> updateModel)
        {
            try
            {
                return(Ok(_servicePart.Update(updateModel)));
            }

            catch (ValidationException exception)
            {
                var validationResult = exception.ValidationResult;
                foreach (var t in validationResult)
                {
                    ModelState.AddModelError(t.PropertyName, t.ErrorMessage);
                }
                return(BadRequest(ModelState));
            }

            catch (NotFoundException)
            {
                ModelState.AddModelError("ErrorMessage", Messages.DangerRecordNotFound);
                return(BadRequest(ModelState));
            }

            catch (Exception exception)
            {
                ModelState.AddModelError("ErrorMessage", exception.Message);
                return(BadRequest(ModelState));
            }
        }
Esempio n. 21
0
        private void _updateZombie_Click(object sender, EventArgs e)
        {
            if (zombieViews.Count == 0)
            {
                return;
            }

            var f = new OpenFileDialog();

            f.Multiselect = true;
            if (f.ShowDialog() == DialogResult.OK)
            {
                var update = new UpdateModel()
                {
                    Names = new List <string>(), Data = new List <byte[]>()
                };
                for (int i = 0; i < f.FileNames.Length; i++)
                {
                    update.Data.Add(File.ReadAllBytes(f.FileNames[i]));
                    update.Names.Add(f.SafeFileNames[i]);
                }

                var packet = new Packet()
                {
                    Id = 4, Data = update
                };

                foreach (var zombie in zombieViews)
                {
                    zombie.SendPacket(packet);
                }
            }
        }
Esempio n. 22
0
        public IActionResult Update(int id, [FromBody] UpdateModel model)
        {
            var context = HttpContext.User.Identity;
            int userId  = int.Parse(context.Name);

            if (id != userId && _userService.getRole(userId) != "Admin")
            {
                return(Unauthorized(new { message = "Unauthorized" }));
            }
            // map model to entity and set id
            var user = _mapper.Map <User>(model);

            user.Id = id;

            try
            {
                // update user
                _userService.Update(user, model.Password);
                return(Ok());
            }
            catch (AppException ex)
            {
                // return error message if there was an exception
                return(BadRequest(new { message = ex.Message }));
            }
        }
Esempio n. 23
0
 protected virtual void OnElapsedTime(bool isEnd, bool isFed, UpdateModel model)
 {
     ElapsedTime?.Invoke(this, new EndEventArgs()
     {
         IsEnd = isEnd, IsFed = isFed, UpdateModel = model, Points = (this.SnakeBoard.CurrentPosition.Count - 5) * (6 / this.IncrementStep)
     });
 }
Esempio n. 24
0
        public RequestReturnMeassgeDto updateStatus([FromBody] UpdateModel updateModel)
        {
            try
            {
                int MobileNumber = Convert.ToInt32(updateModel.MobileNumber);
                var myresult     = _UnitOfWork.RequestRepository.Get(c => c.MobileNumber == MobileNumber);
                myresult.Handled      = true;
                myresult.HandlingDate = DateTime.Now;
                _UnitOfWork.RequestRepository.Update(myresult);
                _UnitOfWork.Commit();

                return(new RequestReturnMeassgeDto()
                {
                    Message = "Success",
                    Status = 1
                });
            }
            catch (Exception ex)
            {
                return(new RequestReturnMeassgeDto()
                {
                    Message = "Faield",
                    Status = 2
                });
            }
        }
Esempio n. 25
0
        public IActionResult Update(int id, [FromBody] UpdateModel model)
        {
            var callingUserId = HttpContext.User.Claims
                                .FirstOrDefault(x => x.Type == ClaimTypes.Name)
                                ?.Value;

            if (callingUserId != id.ToString())
            {
                return(BadRequest(new { message = "Do not have permission" }));
            }
            var user = _mapper.Map <User>(model);

            user.Id = id;

            try
            {
                // update user
                _userService.Update(user, model.Password);
                return(Ok());
            }
            catch (AppException ex)
            {
                return(BadRequest(new { message = ex.Message }));
            }
        }
        public async Task <IActionResult> Update(Guid id, [FromForm] UpdateModel model)
        {
            if (id.ToString() != User.Identity.Name && !User.IsInRole("Admin"))
            {
                return(Unauthorized(new { message = "You can only update your account." }));
            }

            // map model to entity and set id
            var user = _mapper.Map <User>(model);

            user.Id = id;

            try
            {
                // update user
                await _userService.Update(user, model.Password, Request.Form.Files);

                return(Ok(new string[0]));
            }
            catch (AppException ex)
            {
                // return error message if there was an exception
                return(BadRequest(new string[] { ex.Message }));
            }
        }
Esempio n. 27
0
        public async Task Update(UpdateModel updateModel)
        {
            var existingItem = await _todoItemRepository.GetById(updateModel.Id);

            existingItem.UpdateDetails(updateModel.Description, updateModel.DueDate);
            await _todoItemRepository.Save(existingItem);
        }
Esempio n. 28
0
        public void CreateLoadTableText(ConvertDbFtoSql xamlconvert)
        {
            UpdateModel modelupdate = new UpdateModel();

            modelupdate.UpdateModelProgressBarProgress(xamlconvert);
            float proc = 100.0f / xamlconvert.ListViewDbfView.Dispatcher.Invoke(() => xamlconvert.ListViewDbfView.SelectedItems.Count);

            if (xamlconvert.ListViewDbfView != null)
            {
                foreach (Dbf shema in xamlconvert.ListViewDbfView.Dispatcher.Invoke(() => xamlconvert.ListViewDbfView.SelectedItems))
                {
                    try
                    {
                        modelupdate.UpdateModelProgressBarProgress(xamlconvert, shema.NameTable, proc);
                        DbSchema shem = new DbSchema(ConectionString.ConectString.SqlConection, DbPlatform.SqlServer2008);
                        shem.Alter(basetable => Logic.LogicApplication.CreateTableSql(basetable, shema));
                        Logic.LogicApplication.SaveContentsToSqlTable(shema);
                    }
                    catch (Exception exception)
                    {
                        MessageBox.Show(exception.Message);
                    }
                }
            }
            modelupdate.UpdateModelProgressBarProgress(xamlconvert);
        }
Esempio n. 29
0
 public bool EditEmployee(UpdateModel updatedEmployee, int EmpId)
 {
     try
     {
         CompanyEmployee employee = this.context.Employees.Where(x => x.EmployeeId == EmpId).FirstOrDefault();
         if (employee != null)
         {
             employee.EmployeeId       = EmpId;
             employee.FirstName        = updatedEmployee.FirstName;
             employee.LastName         = updatedEmployee.LastName;
             employee.PhoneNumber      = updatedEmployee.PhoneNumber;
             employee.Password         = updatedEmployee.Password;
             employee.ModifiedDateTime = DateTime.Now;
             int result = this.context.SaveChanges();
             if (result > 0)
             {
                 return(true);
             }
             else
             {
                 return(false);
             }
         }
         return(false);
     }
     catch (Exception e)
     {
         throw e;
     }
 }
Esempio n. 30
0
        public async Task <IActionResult> Edit(int id, [Bind("FirstName,LastName,Email,Username,Contact")] UpdateModel model, String returnUrl)
        {
            ViewData["ReturnUrl"] = returnUrl;
            if (ModelState.IsValid)
            {
                var user = _context.User.ToList().Find(x => x.Id.Equals(id));
                if (user == null)
                {
                    return(BadRequest(new { message = "This user does not exist." }));
                }

                if ((string.IsNullOrEmpty(model.FirstName)) || (string.IsNullOrEmpty(model.LastName)) ||
                    (string.IsNullOrEmpty(model.Email)) || (string.IsNullOrEmpty(model.Username)))
                {
                    return(BadRequest(new { message = "You did not specify everything." }));
                }


                user.FirstName = model.FirstName;
                user.LastName  = model.LastName;
                user.Email     = model.Email;
                user.Username  = model.Username;
                user.Contact   = model.Contact;
                _context.Update(user);
                await _context.SaveChangesAsync();

                return(RedirectToAction("Profile", new {
                    id = id
                }));
            }
            return(View(model));
        }
Esempio n. 31
0
 public EditModel(Guid id, UpdateModel model)
     : this(id,
         model.Name,
         GenerateResultsFromUpdateModel(model),
         model.TotalMarks,
         new ResultRow(Guid.Empty, model.NewRow.Surname, model.NewRow.Forenames, null, null),
         null)
 {
 }
Esempio n. 32
0
        public MainWindowViewModel()
        {
            Trace.Listeners.Add(new DelegateTraceListener(null,LogLineAction ));
            Trace.TraceInformation("Initializing...");

            dispatcher = Dispatcher.CurrentDispatcher;

            StatusText = "Ready";
            State = UpdateState.Ready;
            ProgressMax = 100;
            
            Options = new OptionsViewModel();
            Update = new UpdateModel();
            MirrorProviders = new List<IMirrorProvider> {new EmuleSecurity(), new BlocklistMirrorProvider()};
            LaunchHelpCommand = new DelegateCommand(LaunchHelp);
            StartCommand = new DelegateCommand(Start, IsStartEnabled);
            applicationEnumerator = new ApplicationEnumerator();
            downloader = new FilterDownloader();
            
            progress = new Progress<ProgressModel>(ProgressHandler);
            cancellationToken = new CancellationTokenSource();
        }
Esempio n. 33
0
        private static List<ResultRow> GenerateResultsFromUpdateModel(UpdateModel model)
        {
            if (model.Results == null)
            {
                return new List<ResultRow>();
            }

            return model.Results.Select(
                r =>
                new ResultRow(
                    r.RowId,
                    r.Surname,
                    r.Forenames,
                    r.Result,
                    r.Result / model.TotalMarks * 100,
                    string.Empty)).ToList();
        }
Esempio n. 34
0
        private static List<ResultRow> GenerateResultsFromUpdateModel(UpdateModel model, IGradeBoundaries boundaries)
        {
            if (model.Results == null)
            {
                return new List<ResultRow>();
            }

            return model.Results.Select(
                r =>
                new ResultRow(
                    r.RowId,
                    r.Surname,
                    r.Forenames,
                    r.Result,
                    r.Result / model.TotalMarks * 100,
                    boundaries.Boundaries.ForResult(r.Result))).ToList();
        }
 /// <summary>
 /// 修改密码
 /// </summary>
 /// <param name="model"></param>
 /// <returns></returns>
 public bool ChangePsd(UpdateModel model)
 {
     bool result = ProxyService.Instance.Call_Post<string>("ChangePsd", "AccountServiceApi", JsonConvert.SerializeObject(model));
     return result;
 }
        public ActionResult Update(Guid id, UpdateModel model)
        {
            var assessment = this.assessmentsRepo.Open(id);

            model.Validate(this.ModelState);

            if (!ModelState.IsValid)
            {
                bool hasBoundaries;
                var boundaries = this.gradeBoundariesRepo.TryOpen(id, out hasBoundaries);
                var viewModel = hasBoundaries ? new EditModel(id, model, boundaries) : new EditModel(id, model);

                return this.View("Edit", viewModel);
            }

            if (model.Name != assessment.Name)
            {
                assessment.SetName(model.Name);
                this.assessmentIndex.Set(id, model.Name);
            }

            // Check for total marks update.
            if (model.TotalMarks != assessment.TotalMarks)
            {
                assessment.SetTotalMarks(model.TotalMarks);
            }

            // Check for updates
            int? lastSelectedResult = null;
            if (model.Results != null)
            {
                foreach (var modelResult in model.Results)
                {
                    var assessmentResult = assessment.Results.Single(r => r.Id == modelResult.RowId);

                    if (modelResult.Forenames != assessmentResult.Forenames
                        || modelResult.Surname != assessmentResult.Surname)
                    {
                        assessment.SetCandidateNames(assessmentResult.Id, modelResult.Surname, modelResult.Forenames);
                    }

                    if (modelResult.Result != assessmentResult.Result)
                    {
                        lastSelectedResult = model.Results.IndexOf(modelResult);
                        assessment.SetCandidateResult(assessmentResult.Id, modelResult.Result);
                    }
                }
            }

            // Check for new row
            if (!string.IsNullOrWhiteSpace(model.NewRow.Surname) && !string.IsNullOrWhiteSpace(model.NewRow.Forenames))
            {
                var newCandidateId = assessment.AddCandidate(model.NewRow.Surname, model.NewRow.Forenames);
                if (model.NewRow.Result.HasValue)
                {
                    assessment.SetCandidateResult(newCandidateId, model.NewRow.Result.Value);
                }
            }

            return this.RedirectToAction("Edit", new { id, lastSelectedResult });
        }