private void simpleButtonSave_Click(object sender, EventArgs e) { try { var dto = new ProductTypeDto { Id = this.CurrentProductType.Id, Name = this.textEditName.Text, Brands = new List <BrandDto>(), Categories = new List <CategoryDto>() }; var brandIds = (from CheckedListBoxItem item in this.checkedComboBoxEditBrands.Properties.GetItems() where item.CheckState == System.Windows.Forms.CheckState.Checked select(int) item.Value).ToList <int>(); var categoryIds = (from CheckedListBoxItem item in this.checkedComboBoxEditCategories.Properties.GetItems() where item.CheckState == System.Windows.Forms.CheckState.Checked select(int) item.Value).ToList <int>(); brandIds.ForEach(b => dto.Brands.Add(new BrandDto { Id = b })); categoryIds.ForEach(c => dto.Categories.Add(new CategoryDto { Id = c })); var result = this.ServiceClient.SaveProductType(dto); } catch (Exception ex) { throw ex; } }
public async Task <IActionResult> AddProductType(int userId, ProductTypeDto productTypeDto) { if (userId != int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value)) { return(Unauthorized()); } var ptFromRepo = await _repo.GetTypes(); foreach (var pt in ptFromRepo) { if (pt.Title.Trim() == productTypeDto.Title.Trim()) { return(BadRequest($"type {productTypeDto.Title} already exists")); } } productTypeDto.Title = productTypeDto.Title.Trim(); var newPt = _mapper.Map <ProductType>(productTypeDto); _repo.Add(newPt); if (await _repo.SaveAll()) { var ptToReturn = _mapper.Map <ProductTypeDto>(newPt); return(CreatedAtRoute("GetProductType" , new { userId = userId, id = newPt.Id } , ptToReturn)); } return(BadRequest("Failed to add the type")); }
void ProductTypeForm_Load(object sender, EventArgs e) { try { this.checkedComboBoxEditCategories.Properties.DataSource = base.ServiceClient.GetAllCategories(); this.checkedComboBoxEditBrands.Properties.DataSource = base.ServiceClient.GetAllBrands(); if (this.CurrentProductType != null) { this.textEditName.Text = this.CurrentProductType.Name; var productCategories = base.ServiceClient.GetCategoriesByProductType(this.CurrentProductType.Id); var productBrands = base.ServiceClient.GetBrandsByProductType(this.CurrentProductType.Id); var selectedProductTypes = string.Join(",", productCategories.Select(s => s.Id.ToString())); var selectedBrands = string.Join(",", productBrands.Select(b => b.BrandId.ToString())); this.checkedComboBoxEditCategories.SetEditValue(selectedProductTypes); this.checkedComboBoxEditBrands.SetEditValue(selectedBrands); } else { this.CurrentProductType = new ProductTypeDto { Id = 0, Categories = new List <CategoryDto>(), Brands = new List <BrandDto>() }; } } catch (Exception) { throw; } }
public IActionResult Post([FromBody] ProductTypeDto productTypeDto) { try { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } var productType = Mapper.Map <ProductType>(productTypeDto); if (_productTypeRepository.ProductTypeExists(productType)) { return(StatusCode(500, "ProductType already exists.")); } var userId = User.FindFirstValue(ClaimTypes.NameIdentifier); var profile = _accountRepository.GetUserProfile(userId); var createdProductType = _productTypeRepository.CreateProductType(productType, profile.UserProfileId); if (createdProductType == null) { return(StatusCode(500, "A problem happened while handling your request.")); } var createdProductTypeToReturn = Mapper.Map <ProductTypeDto>(createdProductType); return(Created(createdProductTypeToReturn)); } catch (Exception ex) { _logger.LogError($"Failed in Post /ProductTypes: {ex}"); return(StatusCode(500, "A problem happened while handling your request.")); } }
// Actualizar elemento public ProductType Update(ProductTypeDto productTypeParam) { // Buscamos elemento a modificar var productType = _context.ProductType.Find(productTypeParam.idProductType); // verificamos q existe if (productType == null) { throw new AppException("Tipo de producto no existe."); } // Verificamos si los datos ya existen if (productTypeParam.description != productType.description) { // productTypeName has changed so check if the new productTypeName is already taken if (_context.ProductType.Any(x => x.description == productTypeParam.description)) { throw new AppException("El Tipo de producto " + productTypeParam.description + " ya existe"); } } // actualizamos dato productType.update(productTypeParam, _context); // Guardar cambios _context.ProductType.Update(productType); _context.SaveChanges(); return(productType); }
public bool Delete(ProductTypeDto unit) { var result = false; try { var delete = _unitOfWork.ProductTypeRepository.Find(u => u.Code == unit.Code); if (delete.Any()) { _unitOfWork.ProductTypeRepository.Remove(delete.First()); _unitOfWork.Save(); result = true; return(result); } return(result); } catch (Exception) { throw; } }
public IEnumerable <ProductTypeDto> GetAllProductType(ProductTypeDto request, int RequestUserId, string TokenKey) { try { CheckAuthentication(RequestUserId, TokenKey); var data = GetAllCachedData <ProductTypeEntity>().AsQueryable(); var predicate = PredicateBuilderHelper.True <ProductTypeEntity>(); if (request.Id.HasValue) { predicate = predicate.And(q => q.Id == request.Id); } if (request.ActivationStatus > 0) { predicate = predicate.And(q => q.ActivationStatus == request.ActivationStatus); } if (!request.Name.IsNullOrEmpty()) { predicate = predicate.And(q => q.Name.Contains(request.Name)); } var result = data.Where(predicate).AsEnumerable(); return(result.ConvertTo <IEnumerable <ProductTypeDto> >()); } catch (KnownException ex) { throw ex; } catch (Exception ex) { Logger.AddLog(LogTypeEnum.Error, "ProductManager.GetAllProductType", RequestUserId, ex.Message, request.ToJson(), ex); throw new KnownException(ErrorTypeEnum.UnexpectedExeption, ex.Message, ex); } }
public void Update(ProductTypeDto product) { var prod = new ProductType(); mapper.Map(product, prod); unitOfWork.ProductTypeRepository.Edit(prod); unitOfWork.Save(); }
public static ProductTypeModel FormDto(ProductTypeDto dto) { return(new ProductTypeModel { Active = dto.Active == 1, Description = dto.Description, Id = dto.Id }); }
public void Delete(ProductTypeDto item) { if (Unit != null) { Repository.Delete(item, false); } else { Repository.Delete(item); } }
public ProductTypeDto Insert(ProductTypeDto product) { var prod = new ProductType(); mapper.Map(product, prod); unitOfWork.ProductTypeRepository.Add(prod); unitOfWork.Save(); product.Id = prod.Id; return(product); }
public IActionResult Put(ProductTypeDto product) { try { _productTypeService.Update(product); return(NoContent()); } catch (Exception) { return(BadRequest()); } }
public ActionResult <ProductTypeDto> Post(ProductTypeDto product) { try { var result = _productTypeService.Insert(product); return(result); } catch (Exception) { return(BadRequest()); } }
public ProductTypeDto CreateOrUpdateProductType(ProductTypeDto dto, int RequestUserId, string TokenKey) { try { CheckAuthentication(RequestUserId, TokenKey); #region Empty Control if (dto.Name.IsNullOrEmpty()) { throw new RequestWarningException(ErrorTypeEnum.WarningException, ExceptionCodeHelper.CannotEmptyField, ExceptionMessageHelper.CannotEmptyField("Name")); } #endregion var data = GetAllCachedData <ProductTypeEntity>().ToList(); #region Field Control if (data != null) { if (data.Any(q => q.Name == dto.Name)) { throw new RequestWarningException(ErrorTypeEnum.WarningException, ExceptionCodeHelper.IsInUse, ExceptionMessageHelper.IsInUse("Name")); } } #endregion var entity = dto.ConvertTo <ProductTypeEntity>(); var conn = Db.CreateConnection(true); if (dto.Id > 0) { entity.UpdateUser = RequestUserId; entity.UpdateDate = DateTimeHelper.Now; conn.Update(entity, Db._DbTransaction); data.RemoveAt(data.FindIndex(q => q.Id == entity.Id)); } else { int Id = conn.Insert(entity, Db._DbTransaction).ToInt(); entity = conn.Get <ProductTypeEntity>(Id); } data.Add(entity); FillCacheData(data); return(entity.ConvertTo <ProductTypeDto>()); } catch (KnownException ex) { throw ex; } catch (Exception ex) { Logger.AddLog(LogTypeEnum.Error, "ProductManager.CreateOrUpdateProductType", RequestUserId, ex.Message, dto.ToJson(), ex); throw new KnownException(ErrorTypeEnum.UnexpectedExeption, ex.Message, ex); } }
public ProductTypeDto Create(ProductTypeDto dto) { try { var retVal = this.dal.Create(dto.Name, dto.Categories.Select(c => c.Id).ToList(), dto.Brands.Select(b => b.Id).ToList()).ToDto(); return(retVal); } catch (Exception ex) { throw ex; } }
public void Insert(ProductTypeDto item) { // if Unit is not null means that our service is called after another service. if (Unit != null) { this.Repository.Insert(item, false); // call data access insert } // if Unit is null means that our service is the first service that is calling repository. else { this.Repository.Insert(item); } }
public ProductTypeDto GetById(int id) { var item = unitOfWork.ProductTypeRepository.GetById(id); if (item == null) { throw new Exception("Not found"); } var dto = new ProductTypeDto(); mapper.Map(item, dto); return(dto); }
public void AddNewProduct(ProductTypeDto type, OwnerDto owner, ProductStatusDto status, ZoneDto zone, string description) { ProductDto productDto = new ProductDto { Description = description, Id = SelectedProduct.ProductId, Owner = owner, Status = status, Type = type, Zone = zone }; SaveOrUpdateProduct(productDto); }
public void SetDto(Products obj) { if (obj == null) { return; } this.ProductId = obj.ProductId; this.Productname = obj.Productname; if (obj.ProductTypes != null) { this.ProductTypes = new ProductTypeDto(); this.ProductTypes.SetDto(obj.City); } }
[HttpPut("actualizar")] // metodo PUT para actualizar elemento public IActionResult Update([FromBody] ProductTypeDto productTypeDto) { var productType = _mapper.Map <ProductType>(productTypeDto); // Mapear dto a entitidad try { productType = _productTypeRepository.Update(productTypeDto); // Actualizamos el elemento productTypeDto = _mapper.Map <ProductTypeDto>(productType); // Mapear entitidad a dto return(Ok(productTypeDto)); } catch (AppException ex) { return(BadRequest(new { message = ex.Message })); // Retornar mensaje de error } }
public async Task <int> AddProductType(ProductTypeDto testResultData) { try { var ProductType = _mapper.Map <ProductType>(testResultData); _dbContext.ProductTypes.Add(ProductType); await _dbContext.SaveChangesAsync(); return(ProductType.Id); } catch (Exception) { return(-1); } }
public async Task <int> UpdateProductType(ProductTypeDto model) { var productToUpdate = await _skinHubAppDbContext.ProductType.FindAsync(model.ID); if (productToUpdate != null) { productToUpdate.Name = model.Name; _skinHubAppDbContext.Entry(productToUpdate).State = EntityState.Modified; await _skinHubAppDbContext.SaveChangesAsync(); return(model.ID); } return(0); }
[HttpPost("agregar")] // metodo POST para agregar elementos public IActionResult Insert([FromBody] ProductTypeDto productTypeDto) { var productType = _mapper.Map <ProductType>(productTypeDto); // Mapear dto a entitidad try { productType = _productTypeRepository.Insert(productType); // Guardamos el elemento productTypeDto = _mapper.Map <ProductTypeDto>(productType); // Mapear entitidad a dto return(Ok(productTypeDto)); } catch (AppException ex) // Si ocurre un error... { return(BadRequest(new { message = ex.Message })); // Retornar mensaje de error } }
public IActionResult Post([FromBody] ProductTypeDto dto) { if (ModelState.IsValid) { var productType = _iMapper.Map <ProductType>(dto); bool isAdded = _productTypeManager.Add(productType); if (isAdded) { return(Ok(productType)); } return(BadRequest(new { error = "Failed To Add!" })); } return(BadRequest(new { error = "Model is not valid!!" })); }
public ProductTypeDto Save(ProductTypeDto dto) { try { var categoryLogic = new CategoryLogic(); var brandLogic = new BrandLogic(); var categories = categoryLogic.GetByNames(dto.Categories.Select(c => c.Name).ToList()); var brands = brandLogic.GetByNames(dto.Brands.Select(b => b.Name).ToList()); var retVal = this.dal.Save(dto.Id, dto.Name, categories.Select(c => c.Id).ToList(), brands.Select(b => b.Id).ToList()).ToDto(); return(retVal); } catch (Exception ex) { throw ex; } }
public async Task <ProductTypeDto> GetProductTypeByID(int id) { var productTypeByID = await _skinHubAppDbContext.ProductType.Include(c => c.ColorType).FirstOrDefaultAsync(g => g.ID == id); if (productTypeByID != null) { var model = new ProductTypeDto { ID = productTypeByID.ID, Name = productTypeByID.Name, ColorTypeID = productTypeByID.ColorTypeID, ColorType = productTypeByID.ColorType.Name, }; return(model); } return(null); }
ProductDto createProductDto(ProductWrapper productWrap) { ProductDto content = new ProductDto(); ConditionDto condition = new ConditionDto(); GenreDto genre = new GenreDto(); ProductTypeDto productType = new ProductTypeDto(); content.ConditionId = productWrap.ConditionId; content.GenreId = productWrap.GenreId; content.ProductTypeId = productWrap.ProductTypeId; content.Id = productWrap.Id; content.Name = productWrap.Name; content.ProductOwner = _authenticationUser.UserId; content.SoldCopies = 0; content.Stock = productWrap.Stock; return(content); }
public static ProductTypeDto ToDto(this DataAccess.Models.ProductType item) { ProductTypeDto dto = null; if (item != null) { dto = new ProductTypeDto { Id = item.Id, Name = item.Name, Brands = item.Brand == null ? null : item.Brand.ToBasicDto() as List <BrandDto>, Categories = item.Category != null?item.Category.ToBasicDto() as List <CategoryDto> : null }; } return(dto); }
public async Task <IActionResult> UpdateProductType(int id, int userId, ProductTypeDto productTypeDto) { if (userId != int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value)) { return(Unauthorized()); } var typeFromRepo = await _repo.GetType(id); _mapper.Map(productTypeDto, typeFromRepo); if (await _repo.SaveAll()) { return(NoContent()); } throw new Exception($"Updating type {id} failed on save"); }
public async Task <int> UpdateProductType(ProductTypeDto testResultData) { try { var savedProductType = _dbContext.ProductTypes.AsNoTracking().FirstOrDefault(p => p.Id == testResultData.Id); if (savedProductType == null) { return(-1); } _dbContext.Entry(_mapper.Map <ProductType>(testResultData)).State = EntityState.Modified; await _dbContext.SaveChangesAsync(); return(savedProductType.Id); } catch (Exception e) { return(-1); } }