public async Task <IActionResult> PutSubgroup(int id, Subgroup subgroup) { if (id != subgroup.Id) { return(BadRequest()); } _context.Entry(subgroup).State = EntityState.Modified; try { await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!SubgroupExists(id)) { return(NotFound()); } else { throw; } } return(NoContent()); }
public async Task <ActionResult <Subgroup> > PostSubgroup(Subgroup subgroup) { _context.Subgroups.Add(subgroup); await _context.SaveChangesAsync(); return(CreatedAtAction("GetSubgroup", new { id = subgroup.Id }, subgroup)); }
private IEnumerable <Group> PrepareCatalogGeneral(int?groupId, int?subgroupId, int?merchandiseId, string searchText) { #region Извлечь из веб-запроса необходимые параметры var sortField = RequestParametersHandler.GetRequestParameter <String>(this.Request.Params, WebRequestParamNames.SortField) ?? String.Empty; var sortOrder = RequestParametersHandler.GetRequestParameter <String>(this.Request.Params, WebRequestParamNames.SortOrder) ?? String.Empty; var page = String.IsNullOrWhiteSpace(searchText) ? RequestParametersHandler.GetRequestParameter <int>(this.Request.Params, WebRequestParamNames.Page) : 1; #endregion // Извлечь из хранилища товар в соответствии с выбранной категорией (и с учетом поиска) Group group = null; Subgroup subgroup = null; IEnumerable <Merchandise> merchandises = String.IsNullOrWhiteSpace(searchText) ? this.service.GetMerchandises(groupId, subgroupId, merchandiseId, out group, out subgroup) : this.service.GetMerchandisesBySearch(groupId, subgroupId, searchText); // Сортировка this.service.Sort(ref merchandises, sortField, sortOrder); // Paging ApplyPagging(merchandises, page); // Построение строки навигации BuildNavigatioinPath(group, subgroup, sortField, sortOrder, searchText); // Подготовка информации по скидкам и ценам PrepareDiscountsInformation(); // Инициализация параметров View SetViewParams(groupId, subgroupId, merchandiseId, sortField, sortOrder, searchText); return(this.service.Groups); }
public async Task <Subgroup> UpdateSubgroup(Subgroup subgroup) { var tokenResponse = await _tokenService.GetToken("groupsapi.read"); _httpClient .SetBearerToken(tokenResponse.AccessToken); _httpClient.BaseAddress = new Uri("https://localhost:5446/"); var request = new HttpRequestMessage(HttpMethod.Put, $"Subgroups/{subgroup}"); request.Content = JsonContent.Create <Subgroup>(subgroup); var response = await _httpClient.SendAsync(request); if (response.IsSuccessStatusCode) { var readTask = response.Content.ReadAsAsync <Subgroup>(); readTask.Wait(); return(readTask.Result); } else { throw new Exception("Unable to get content"); } }
public async Task <Subgroup> CreateSubgroup(Subgroup subgroup) { var tokenResponse = await _tokenService.GetToken("groupsapi.read"); _httpClient .SetBearerToken(tokenResponse.AccessToken); _httpClient.BaseAddress = new Uri("https://localhost:5446/"); var request = new HttpRequestMessage(HttpMethod.Post, $"Subgroups"); request.Content = new StringContent(JsonConvert.SerializeObject(subgroup), System.Text.Encoding.UTF8, "application/json"); var response = await _httpClient.SendAsync(request); if (response.IsSuccessStatusCode) { var readTask = response.Content.ReadAsAsync <Subgroup>(); readTask.Wait(); return(readTask.Result); } else { throw new Exception("Unable to get content"); } }
public ActionResult AddSubgroup(int group_id) { var group = UnitOfWork.Groups.Get(group_id); var subgroup = new Subgroup(group); return(View(subgroup)); }
public static Subgroup Create(Group parent, int arg) { Subgroup sub = new Subgroup(arg); //use private ctor parent.AddSubgroup(sub); return(sub); }
/// <summary> /// Handles the Click event of the btnSave control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param> private void btnSave_Click(object sender, EventArgs e) { SubGroupDataContext sdc = new SubGroupDataContext( ConfigurationManager.ConnectionStrings["hamwicConnectionString"].ConnectionString); Subgroup newSubgroup = new Subgroup { Name = txtSubgroupName.Text }; sdc.Subgroups.InsertOnSubmit(newSubgroup); try { sdc.SubmitChanges(); MessageBox.Show("Changes saved successfully", "The database has been updated.", MessageBoxButtons.OK, MessageBoxIcon.Information); this.Close(); } catch (Exception) { MessageBox.Show("Failed to save Changes", "Problem committing to database", MessageBoxButtons.OK, MessageBoxIcon.Error); } }
public async Task <IActionResult> Create() { Subgroup subgroup = new Subgroup(); subgroup.Groups = await groupClient.GetAllGroups(); return(View(subgroup)); }
public void AddOrUpdateSubgroup(Subgroup s) { if (s == null) { return; } this.db.Subgroups.AddOrUpdate(p => p.ID, new Subgroup[] { s }); }
public IActionResult PostSubgroup([FromBody] Subgroup subgroup) { using (var scope = new TransactionScope()) { _subgroupRepository.Add(subgroup); scope.Complete(); return(CreatedAtAction(nameof(GetSubgroup), new { id = subgroup.SubgroupId }, subgroup)); } }
public async Task <IActionResult> Create(Subgroup subgroup) { if (ModelState.IsValid) { await apiClient.CreateSubgroup(subgroup); return(RedirectToAction("Index")); } return(View(subgroup)); }
public ActionResult Create(Subgroup model) { //authorization if (!ModelState.IsValid) { return(View(model)); } var id = _subgroupCommandService.Create(model); return(RedirectToAction("Details", new { id })); }
public ActionResult DeleteSubgroup(Subgroup subgroup) { try { UnitOfWork.Subgroups.Delete(subgroup); return(RedirectToAction("Subgroups", new { group_id = subgroup.GroupId })); } catch (Exception) { ModelState.AddModelError("subgroup_number", "Не удалось удалить подгруппу"); return(View(subgroup)); } }
public IEnumerable <User> GetMembersForSubgroup(Subgroup subgroup) { var userToSubgroupList = FindByCondition(uts => uts.SubgroupId == subgroup.Id).ToList(); var userList = new List <User>(); foreach (var uts in userToSubgroupList) { var currentUser = RepositoryContext.Users.Find(uts.UserId); userList.Add(currentUser); } return(userList); }
public ActionResult AddSubgroup(Subgroup subgroup) { try { UnitOfWork.Subgroups.Create(subgroup); return(RedirectToAction("Subgroups", new { group_id = subgroup.GroupId })); } catch { ModelState.AddModelError(string.Empty, "Не удалось создать подгруппу"); return(View(subgroup)); } }
public IActionResult CreateSubgroup([FromBody] Subgroup subgroup) { if (subgroup == null) { _logger.LogError("Invalid object: subgroup was null"); return(BadRequest("Invalid client request")); } if (!ModelState.IsValid) { _logger.LogError("Invalid subgroup object sent from client."); return(BadRequest("Invalid subgroup object sent from client.")); } if (!subgroup.ValidateCreateSubgroup()) { return(BadRequest("Sent object was not valid!")); } try { var userMail = AuthControllerExtensions.JwtNameExtractor(Request.Headers["Authorization"]); var dbUser = _repository.User.GetUserByEmail(userMail); var mainGroup = _repository.Group.GetGroupById(subgroup.Main_group); if (mainGroup.AdminUserId.Equals(dbUser.Id)) { _repository.Subgroup.Create(subgroup); _repository.Save(); var adminMemberShip = new UserToSubgroup { UserId = dbUser.Id, SubgroupId = subgroup.Id }; _repository.UserToSubgroup.AddMembership(adminMemberShip); _repository.Save(); return(Ok(_repository.Subgroup.GetSubgroupById(subgroup.Id))); } return(BadRequest("Only admin can add a subgroup to a group!")); } catch (Exception e) { _logger.LogError($"Something went wrong inside CreateSubgroup: {e.Message}"); return(StatusCode(500, "Something went wrong during creating subgroup")); } }
public void Update(Subgroup subgroup) { var update = _dbContext.Subgroups .Where(update => update.SubgroupId.Equals(subgroup.SubgroupId)) .SingleOrDefault(); if (update != default(Subgroup)) { update.Name = subgroup.Name; update.GroupName = subgroup.GroupName; } Save(); }
static void Test_Narrows() { Debug.WriteLine("Test_Narrows"); Rational[] rs = Rational.ParseRationals( "2.3.5" ); Debug.WriteLine("Subgroup: " + Rational.FormatRationals(rs, ".")); Subgroup subgroup = new Subgroup(rs); Debug.WriteLine("Narrows: " + Rational.FormatRationals(subgroup.GetNarrows())); }
public ActionResult Save(Subgroup model) { if (!ModelState.IsValid) { return(View("Edit", model)); } if (ModelState.IsValid) { _subgroupCommandService.UpdateSubgroup(model); } return(RedirectToAction("Details", new { @id = model.Id })); }
public async Task <ActionResult> DeleteSubgroups([FromQuery] int[] ids) { foreach (int id in ids) { Subgroup subgroup = await unitOfWork.Subgroups.Get(id); unitOfWork.Subgroups.Remove(subgroup); } await unitOfWork.Save(); return(Ok()); }
public IActionResult PutSubgroup([FromBody] Subgroup subgroup) { if (subgroup != null) { using (var scope = new TransactionScope()) { _subgroupRepository.Update(subgroup); scope.Complete(); return(new OkResult()); } } return(new NoContentResult()); }
private static void UpdateSubgroup(IDbGeneralContext db, Subgroup s) { if (db == null) { throw new ArgumentNullException("db"); } if (s == null) { return; } // save subgroup to DB db.Subgroups.AddOrUpdate(p => p.ID, new Subgroup[] { s }); }
public bool DeleteSubgroup(int id) { Subgroup entity = new Subgroup(); entity = unitofwork.Subgroup.Get(id); entity.IsDeleted = true; try { unitofwork.SaveChanges(); return(true); } catch { return(false); } }
public bool UpdateSubgroup(SubgroupDTO obj) { Subgroup model = new Subgroup(); model = Mapper.Map <SubgroupDTO, Subgroup>(obj); unitofwork.Subgroup.Update(model); try { unitofwork.SaveChanges(); return(true); } catch { return(false); } }
public ActionResult Edit(Guid id) { //authorization var subGroup = _subgroupQueryService.GetSubgroupById(id); var vm = new Subgroup { Id = subGroup.Id, Name = subGroup.Name, Description = subGroup.Description, LastUpdatedBy = subGroup.LastUpdatedBy, LastUpdateDate = subGroup.LastUpdateDate }; return(View(vm)); }
public void CreateSubgroup(SubgroupDTO subgroupDTO) { if (subgroupDTO == null) { throw new ValidationException("Введите данные", ""); } Subgroup subgroup = new Subgroup { GroupNumber = subgroupDTO.GroupNumber, GroupNumber2 = subgroupDTO.GroupNumber2, NumberOfStudents = subgroupDTO.NumberOfStudents, LectureFlowId = subgroupDTO.LectureFlowId }; Database.Subgroups.Create(subgroup); Database.Save(); }
public JsonResult AddEmployeeToSubgroup(int departmentId, string lastName, string firstName, string patronymic) { using (CommonContext db = new CommonContext()) { Subgroup subgroup = db.Subgroups.Where(s => s.Id == departmentId).ToArray().FirstOrDefault(); subgroup.Employees.Add(new Employee() { LastName = lastName, FirstName = firstName, Patronymic = patronymic, Subgroup = subgroup }); db.SaveChanges(); lastEmployeeId = subgroup.Employees.Max(e => e.Id); } return(Json(new { lastEmployeeId = lastEmployeeId }, JsonRequestBehavior.AllowGet)); }
public void UpdateSubgroup(Subgroup input) { var user = _userService.GetCurrentUser(); var subgroup = _subgroupQueryService.GetSubgroupById(input.Id); subgroup.Name = input.Name; subgroup.Description = input.Description; subgroup.LastUpdateDate = DateTime.Now; subgroup.LastUpdatedBy = user.Identity.Name; using (var dbContextScope = _dbContextScopeFactory.Create()) { var dbContext = dbContextScope.DbContexts.Get <EntityManagerDbContext>(); dbContext.Set <Subgroup>().AddOrUpdate(subgroup); dbContext.SaveChanges(); } }
public IActionResult UpdateSubgroup([FromBody] Subgroup subgroup) { if (subgroup == null) { _logger.LogError("Invalid request: Subgroup object was null"); return(BadRequest("Invalid request: Subgroup object was null")); } if (!ModelState.IsValid) { _logger.LogError("Invalid user object sent from client"); return(BadRequest("Invalid user object sent from client")); } if (!subgroup.ValidateUpdateSubgroup()) { return(BadRequest("Sent object was not valid!")); } try { var dbSubgroup = _repository.Subgroup.GetSubgroupById(subgroup.Id); var mainGroup = _repository.Group.GetGroupById(subgroup.Main_group); var userMail = AuthControllerExtensions.JwtNameExtractor(Request.Headers["Authorization"]); var dbUser = _repository.User.GetUserByEmail(userMail); if (dbUser.Id.Equals(mainGroup.AdminUserId)) { dbSubgroup.Map(subgroup); _repository.Subgroup.Update(dbSubgroup); _repository.Save(); return(Accepted()); } _logger.LogError("Only admin can change subgroup"); return(BadRequest("Only admin can change subgroup")); } catch (Exception e) { _logger.LogError($"Something went wrong inside UpdateSubgroup: {e.Message}"); return(StatusCode(500, "Something went wrong during update subgroup")); } }