예제 #1
0
        public bool Create(BrandDTO brand)
        {
            try
            {
                using (SqlConnection connection = new SqlConnection(sqlConnectionString))
                {
                    string sql = "INSERT INTO Brands (Name, Origin) VALUES (@Name, @Origin)";
                    using (SqlCommand command = new SqlCommand(sql, connection))
                    {
                        connection.Open();
                        command.Parameters.AddWithValue("@Name", brand.Name);
                        command.Parameters.AddWithValue("@Origin", brand.Origin);
                        if (command.ExecuteNonQuery() < 1)
                        {
                            connection.Close();
                            return(false);
                        }
                        connection.Close();
                    }
                }
            }
            catch (SqlException e)
            {
                Console.WriteLine(e);
                return(false);
            }

            return(true);
        }
예제 #2
0
        public async Task Insert(BrandDTO brand)
        {
            SqlConnection connection = new SqlConnection();

            connection.ConnectionString = _options.ConnectionString;
            SqlCommand command = new SqlCommand();

            command.CommandText = "INSERT INTO BRANDS (NAME) VALUES (@NAME); select scope_identity()";
            command.Parameters.AddWithValue(@"NAME", brand.Name);
            command.Connection = connection;
            Response response = new Response();

            try
            {
                await connection.OpenAsync();

                int idGerado = Convert.ToInt32(command.ExecuteScalar());
            }
            catch (Exception ex)
            {
                response.Errors.Add("Erro no banco de dados, contate o administrador!");
                File.WriteAllText("log.txt", ex.Message);
            }
            finally
            {
                await connection.CloseAsync();
            }
        }
예제 #3
0
        public async Task <IActionResult> PutBrand([FromRoute] Guid id, [FromBody] BrandDTO brand)
        {
            if (id != brand.Id)
            {
                return(BadRequest());
            }

            _context.Entry(_mapper.Map <Brand>(brand)).State = EntityState.Modified;

            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!Exists(id))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }

            return(NoContent());
        }
예제 #4
0
        public async Task <IActionResult> PostBrand([FromBody] BrandDTO brand)
        {
            _context.Brands.Add(_mapper.Map <Brand>(brand));
            await _context.SaveChangesAsync();

            return(CreatedAtAction("GetBrand", new { id = brand.Id }, brand));
        }
예제 #5
0
        public async Task <Response> Update(BrandDTO brand)
        {
            Response         response = new Response();
            BrandValidator   validate = new BrandValidator();
            ValidationResult result   = validate.Validate(brand);

            if (!result.IsValid)
            {
                foreach (var failure in result.Errors)
                {
                    response.Errors.Add("Property " + failure.PropertyName + " failed validation. Error was: " + "(" + failure.ErrorMessage + ")");
                }

                return(response);
            }
            else
            {
                try
                {
                    return(response = await _iBrandRepository.Update(brand));
                }
                catch (Exception ex)
                {
                    _log.Error(ex + "\nStackTrace: " + ex.StackTrace);
                    response.Errors.Add("DataBase error, contact the system owner");
                    return(response);
                }
            }
        }
예제 #6
0
        public bool Update(BrandDTO brand)
        {
            try
            {
                using (SqlConnection connection = new SqlConnection(sqlConnectionString))
                {
                    string sql = "UPDATE Brands SET Name = (@Name), Origin = (@Origin) WHERE Id = (@Id)";
                    using (SqlCommand command = new SqlCommand(sql, connection))
                    {
                        connection.Open();
                        command.Parameters.AddWithValue("@Name", brand.Name);
                        command.Parameters.AddWithValue("@Origin", brand.Origin);
                        command.Parameters.AddWithValue("@Id", brand.Id);
                        command.ExecuteNonQuery();
                        connection.Close();
                    }
                }
            }
            catch (SqlException e)
            {
                Console.WriteLine(e);
                return(false);
            }

            return(true);
        }
예제 #7
0
        /// <summary>
        /// Updates an existing brand.
        /// </summary>
        /// <param name="brandUpdate">Brand to update</param>
        public void Update(BrandDTO brandUpdate)
        {
            // Throws an an exception for a null dto
            if (brandUpdate == null)
            {
                throw new ArgumentNullException("brandUpdate",
                                                "brandUpdate does not accept a null dot as an argument.");
            }

            using (var context = new openTillEntities())
            {
                var brand = context.Brands.SingleOrDefault(b => b.Id == brandUpdate.Id);

                // Throws an exception if the given brand doesn't exist
                if (brand == null)
                {
                    throw new InvalidOperationException("No entry matching the given brand was found.");
                }

                // Throws an exception if a brand with the given name already exists
                if (context.Brands.SingleOrDefault(b => b.Name == brandUpdate.Name) != null)
                {
                    throw new InvalidOperationException("A brand with the given brand name already exists.");
                }

                // Update existing brand
                brand.Name = brandUpdate.Name;

                context.SaveChanges();
            }
        }
예제 #8
0
        private void Ekle()
        {
            string message = "";

            if (string.IsNullOrWhiteSpace(txtBrand.Text))
            {
                message += "Marka adı boş geçilemez \n";
            }


            if (message != "")
            {
                MessageBox.Show(message);
                return;
            }
            //dto map
            var dto = new BrandDTO()
            {
                BrandName = txtBrand.Text
            };
            //bll şut
            var result = _bc.AddBrand(dto);

            //gelen cevaba göre mesaj ve işlem.
            result.NotificationShow();

            if (result.State == ResultState.Success)
            {
                txtBrand.Text = "";
                BranAdded.Raise();
            }
        }
 public IActionResult AddBrand([FromBody] BrandDTO brandDTO)
 {
     _logger?.LogInformation($"Inicio del servicio: [Post] https://localhost:5001/api/brands ");
     try {
         BrandMapper brandMapper = MapperFactory.CreateBrandMapper();
         Entity      entity      = brandMapper.CreateEntity(brandDTO);
         _logger?.LogInformation($" Se transformó de DTO a Entity ");
         AddBrandCommand command = CommandFactory.CreateAddBrandCommand((Brand)entity);
         _logger?.LogInformation($" Ejecución del comando ");
         command.Execute();
         return(Ok("ok " + command.GetResult()));
     } catch (RequiredAttributeException ex) {
         _logger?.LogWarning("Atributo requerido: " + ex.Message);
         return(StatusCode(400, ex.Message));
     } catch (UniqueAttributeException ex) {
         _logger?.LogWarning(ex.Message);
         return(StatusCode(500, ex.Message));
     } catch (InternalServerErrorException ex) {
         _logger?.LogError("Error: " + ex.Ex.Message);
         return(StatusCode(500, ex.Message));
     } catch (Exception) {
         _logger?.LogError("Error inesperado");
         return(StatusCode(400));
     }
 }
        public async Task <Response> Update(BrandDTO brand)
        {
            Response response = new Response();

            try
            {
                using (var context = _context)
                {
                    context.Update(brand);
                    int nAffectedRows = await context.SaveChangesAsync();

                    if (nAffectedRows == 1)
                    {
                        response.Success = true;
                        return(response);
                    }
                    else
                    {
                        response.Errors.Add("Edição não executada");
                        return(response);
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
예제 #11
0
        public static BrandDTO CreateBrandDTO(this Brand brand)
        {
            var dto = new BrandDTO();

            brand.CopyToBrandDTO(dto);
            return(dto);
        }
예제 #12
0
        public ServiceResult AddBrand(BrandDTO dto)
        {
            Brand brand = new Brand()
            {
                BrandName   = dto.BrandName,
                Id          = Guid.NewGuid(),
                CreatedDate = DateTime.Today,
                CreatedUser = Session.CurrentUser.Id,
                UpdatedUser = Session.CurrentUser.Id,
            };
            ServiceResult result;

            try
            {
                bool islemYapildiMi = Singleton.Uow.GetRepository <Brand>().Add(brand);;
                if (islemYapildiMi)
                {
                    result = new ServiceResult("İşlem başarılı", ResultState.Success);
                }
                else
                {
                    result = new ServiceResult("Yapılacak bir işlem kaydına rastlanmadı.", ResultState.Error);
                }
            }
            catch (Exception ex)
            {
                result = new ServiceResult("Hata: 4-34", ResultState.Error);
            }

            return(result);
        }
예제 #13
0
        public static Brand CreateBrand(this BrandDTO dto)
        {
            var brand = new Brand();

            dto.CopyToBrand(brand);
            return(brand);
        }
예제 #14
0
 private static void CopyToBrandDTO(this Brand brand, BrandDTO dto)
 {
     dto.Id       = brand.Id;
     dto.Name     = brand.Name;
     dto.Order    = brand.Order;
     dto.Products = brand.Products.Select(p => p.CreateProductDTO()).ToList();
 }
예제 #15
0
 public static Brand FromDTO(this BrandDTO Brand) => Brand is null
     ? null
     : new Brand
 {
     Id   = Brand.Id,
     Name = Brand.Name,
 };
        public async Task <ActionResult> Delete(BrandInsertViewModel viewModel)
        {
            Response response = new Response();

            var configuration = new MapperConfiguration(cfg =>
            {
                cfg.CreateMap <BrandInsertViewModel, BrandDTO>();
            });

            IMapper mapper = configuration.CreateMapper();

            BrandDTO dto = mapper.Map <BrandDTO>(viewModel);

            response = await _service.Delete(dto.ID);

            //Se funcionou, redireciona pra página inicial
            if (response.Success)
            {
                return(RedirectToAction("Index", "Brand"));
            }
            else
            {
                ViewBag.ErrorMessage = response.Errors;
                return(this.View());
            }
        }
 public IActionResult UpdateBrand([FromBody] BrandDTO brandDTO)
 {
     _logger?.LogInformation($"Inicio del servicio: [PUT] https://localhost:5001/api/brands/brandId ");
     try{
         BrandMapper brandMapper = MapperFactory.CreateBrandMapper();
         Entity      entity      = brandMapper.CreateEntity(brandDTO);
         _logger?.LogInformation($" Se transformó de DTO a Entity ");
         UpdateBrandCommand command = CommandFactory.CreateUpdateBrandCommand((Brand)entity);
         _logger?.LogInformation($" Ejecución del comando ");
         command.Execute();
         if (command.GetResult())
         {
             return(Ok("La modificación fue realizada exitosamente"));
         }
         else
         {
             return(StatusCode(400));
         }
     } catch (RequiredAttributeException ex) {
         _logger?.LogWarning("Atributo requerido: " + ex.Message);
         return(StatusCode(400, ex.Message));
     } catch (UniqueAttributeException ex) {
         _logger?.LogWarning(ex.Message);
         return(StatusCode(500, ex.Message));
     } catch (BrandNotFoundException ex) {
         _logger?.LogWarning("La marca con Id : " + ex.BrandId + "no encontrado");
         return(StatusCode(404, ex.Message + ex.BrandId));
     } catch (InternalServerErrorException ex) {
         _logger?.LogError("Error: " + ex.Ex.Message);
         return(StatusCode(500, ex.Message));
     } catch (Exception) {
         _logger?.LogError("Error inesperado");
         return(StatusCode(400));
     }
 }
예제 #18
0
 private static void CopyToBrand(this BrandDTO dto, Brand brand)
 {
     brand.Id       = dto.Id;
     brand.Name     = dto.Name;
     brand.Order    = dto.Order;
     brand.Products = dto.Products.Select(p => p.CreateProduct()).ToList();
 }
예제 #19
0
        public BrandDTO Get(int brandId)
        {
            BrandDTO brand = new BrandDTO();

            try
            {
                using (SqlConnection connection = new SqlConnection(sqlConnectionString))
                {
                    string sql = "SELECT * FROM Brands WHERE Id = (@Id)";
                    using (SqlCommand command = new SqlCommand(sql, connection))
                    {
                        connection.Open();
                        command.Parameters.AddWithValue("@Id", brandId);
                        using (SqlDataReader reader = command.ExecuteReader())
                        {
                            reader.Read();
                            brand.Id     = reader.GetInt32(0);
                            brand.Name   = reader.GetString(1);
                            brand.Origin = reader.GetString(2);
                        }
                        connection.Close();
                    }
                }
            }
            catch (SqlException e)
            {
                Console.WriteLine(e);
            }

            return(brand);
        }
예제 #20
0
 public List <BrandDTO> GetAll()
 {
     try
     {
         using (SqlConnection connection = new SqlConnection(sqlConnectionString))
         {
             string sql = "SELECT * FROM Brands ORDER BY Name";
             using (SqlCommand command = new SqlCommand(sql, connection))
             {
                 connection.Open();
                 using (SqlDataReader reader = command.ExecuteReader())
                 {
                     List <BrandDTO> brands = new List <BrandDTO>();
                     while (reader.Read())
                     {
                         BrandDTO brand = new BrandDTO
                         {
                             Id     = reader.GetInt32(0),
                             Name   = reader.GetString(1),
                             Origin = reader.GetString(2)
                         };
                         brands.Add(brand);
                     }
                     connection.Close();
                     return(brands);
                 }
             }
         }
     }
     catch (SqlException e)
     {
         Console.WriteLine(e);
         return(null);
     }
 }
예제 #21
0
        public JsonResult SaveNew(BrandDTO dto)
        {
            bool succeeded = false;

            try
            {
                var model = new tbl_brand();

                model.brand_name     = dto.brand_name;
                model.brand_address1 = dto.brand_address1;
                model.brand_address2 = dto.brand_address2;
                model.brand_city     = dto.brand_city;
                model.brand_state    = dto.brand_state;
                model.brand_zip      = dto.brand_zip;
                model.brand_tel      = dto.brand_tel;

                UnitOfWork.TblBrand.Add(model);

                UnitOfWork.Save();
                dto.id = model.id;
            }
            catch (Exception ex)
            {
                dto.id = 0;
            }
            return(Json(dto, JsonRequestBehavior.AllowGet));
        }
예제 #22
0
        public JsonResult Update(BrandDTO dto)
        {
            bool succeeded = false;

            try
            {
                var model = UnitOfWork.TblBrand.Get(dto.id);

                if (model != null)
                {
                    model.brand_name     = dto.brand_name;
                    model.brand_address1 = dto.brand_address1;
                    model.brand_address2 = dto.brand_address2;
                    model.brand_city     = dto.brand_city;
                    model.brand_state    = dto.brand_state;
                    model.brand_zip      = dto.brand_zip;
                    model.brand_tel      = dto.brand_tel;
                    model.brand_deleted  = dto.brand_deleted;

                    UnitOfWork.Save();
                    succeeded = true;
                }
            }
            catch (Exception ex)
            {
                succeeded = false;
            }
            return(Json(succeeded, JsonRequestBehavior.AllowGet));
        }
예제 #23
0
 public static Brand FromDTO(this BrandDTO brand) => brand is null
     ? null
     : new Brand()
 {
     Id    = brand.Id,
     Name  = brand.Name,
     Order = brand.Order,
 };
        public async Task Add(BrandDTO AddDTO)
        {
            await _brandRepository.Add(_Mapper.Map <Brands>(AddDTO));

            await _brandRepository.Commit();

            await _brandRepository.DisposeAsync();
        }
예제 #25
0
 public static Brand FromDTO(this BrandDTO Brand) => Brand is null
     ? null
     : new Brand
 {
     Id    = Brand.id,
     Name  = Brand.Name,
     Order = Brand.Order,
 };
예제 #26
0
 public static Brand FromDTO(this BrandDTO BrandDTO) => BrandDTO is null
     ? null
     : new Brand
 {
     Id    = BrandDTO.Id,
     Name  = BrandDTO.Name,
     Order = BrandDTO.Order,
 };
예제 #27
0
 public async Task Insert(BrandDTO brand)
 {
     using (MarketContext context = new MarketContext())
     {
         context.Brands.Add(brand);
         await context.SaveChangesAsync();
     }
 }
예제 #28
0
        public ActionResult <BrandDTO> PostBrand(BrandDTO brandDTO)
        {
            Brand brand = new Brand(brandDTO.Name);

            _brandRepository.Add(brand);
            _brandRepository.SaveChanges();

            return(CreatedAtAction(nameof(GetBrand), new { id = brand.Id }, brand));
        }
예제 #29
0
 private void ViewEditData()
 {
     brand = BrandDataAccess.GetBrandById(brandId);
     if (brand != null)
     {
         txtBrand.Text     = brand.BrandName;
         chkActive.Checked = brand.IsActive;
     }
 }
예제 #30
0
        public BrandDTO GetBrandById(Guid brandId)
        {
            var brand    = _brandRepository.FindById(brandId);
            var brandDTO = new BrandDTO();

            brandDTO.Id   = brand.Id;
            brandDTO.Name = brand.Name;
            return(brandDTO);
        }
예제 #31
0
        public void IntegraMarca()
        {
            try
            {
                Console.WriteLine("Início do exemplo de integração de Marca");

                int idMarca = 100;
                //Instanciando um objeto do tipo BrandDTO
                BrandDTO objBrand = this.vtexService.BrandGet(idMarca);

                if (objBrand == null)
                {
                    //Instanciamos um objeto do tipo BrandDTO caso esta Marca não exista na VTEX
                    objBrand = new BrandDTO();
                }

                objBrand.Id = idMarca;
                objBrand.Name = "Nome da Marca";
                objBrand.Title = "Titulo da marca";
                objBrand.Description = "Descrição";
                objBrand.IsActive = true;

                //Enviando os dados para serem inseridos ou atualizados pelo WebService
                this.vtexService.BrandInsertUpdate(objBrand);

                //Mensagem de sucesso	
                Console.WriteLine("Marca inserida com sucesso");
            }
            catch (Exception ex)
            {
                //Mensagem de erro
                Console.WriteLine(ex.ToString());
            }
            finally
            {
                Console.WriteLine("Fim do exemplo de integração de Marca");
                Console.ReadKey();
            }
        }