Ejemplo n.º 1
0
        private void EliminarToolStripMenuItem_Click(object sender, EventArgs e)
        {
            DialogResult result = MessageBox.Show("Seguro que desea Eliminar la Categoria?", "Salir", MessageBoxButtons.YesNoCancel);

            if (result == DialogResult.Yes)
            {
                CategoriaBusiness ctr   = new CategoriaBusiness();
                CategoriaModel    model = new CategoriaModel();

                int id = Convert.ToInt32(DRG_Categoria.CurrentRow.Cells["Id_Categoria"].Value.ToString());
                model.Id_Categoria = id;
                ClassResult cr = ctr.Categoria_Elim(model);
                if (cr.HuboError)
                {
                    MessageBox.Show("error :" + cr.ErrorMsj);
                }
                else
                {
                    Listar();
                }
            }
            else if (result == DialogResult.No)
            {
                return;
            }
            else if (result == DialogResult.Cancel)
            {
                return;
            }
        }
Ejemplo n.º 2
0
        public ActionResult Categoria()
        {
            var model = new CategoriaModel();

            model.Categorias = categoriaService.Consultar().Select(ConverterCategoria).ToList();
            return(View(model));
        }
Ejemplo n.º 3
0
 public CadastrarCategoria(CategoriaModel _categoria)
 {
     InitializeComponent();
     CenterToParent();
     categoria        = _categoria;
     tbNomeCateg.Text = categoria.NomeCategoria;
 }
Ejemplo n.º 4
0
        public ActionResult GETCategoriaDataTable()
        {
            CategoriaCollection categoriaCollection = new CategoriaCollection();
            CategoriaModel      model = new CategoriaModel();

            categoriaCollection = model.GetCategoria();

            foreach (var item in categoriaCollection)
            {
                IList <string> dataRow = new List <string>();
                dataRow.Add(item.IdCategoria.ToString());
                dataRow.Add(item.DcCategoria);

                string botaoAcaoHtmlExluir  = "";
                string botaoAcaoHtmlAlterar = "";
                botaoAcaoHtmlAlterar = "<button onclick =\"abrirModalCadastrarCategoria('A','" + item.IdCategoria.ToString() + "','" + item.DcCategoria + "','0')\" class=\"btn btn-flat btn-sm btn-light texto_escuro text-center\" data-toggle=\"tooltip\" data-placement=\"top\" title=\"Alterar Categoria\"><i class=\"fa fa-edit\"></i></button>";
                botaoAcaoHtmlExluir  = "<button onclick=\"excluirCategoria(" + item.IdCategoria.ToString() + ")\" class=\"btn btn-flat btn-sm btn-danger text-white text-center margem_botao_acao\" data-toggle=\"tooltip\" data-placement=\"top\" title=\"Excluir Categoria\"><i class=\"fa fa-trash\"></i></button>";

                dataRow.Add(botaoAcaoHtmlAlterar);
                dataRow.Add(botaoAcaoHtmlExluir);

                mdlAjaxDataTable.aaData.Add(dataRow);
            }

            return(Json(mdlAjaxDataTable, JsonRequestBehavior.AllowGet));
        }
Ejemplo n.º 5
0
        public async Task <CategoriaModel> Put(CategoriaModel categoria)
        {
            context.Entry(categoria).State = EntityState.Modified;
            await context.SaveChangesAsync();

            return(categoria);
        }
        public void GetCategoriaIdOk()
        {
            var logicMock = new Mock <ICategoria>(MockBehavior.Strict);
            CategoriasController controller = new CategoriasController(logicMock.Object);
            CategoriaModel       catModel   = new CategoriaModel()
            {
                Nombre = "Playa",
            };
            Categoria cat = new Categoria()
            {
                Nombre = catModel.Nombre,
                Id     = 0,
            };

            logicMock.Setup(x => x.Categoria(catModel.Nombre)).Returns(cat);
            logicMock.Setup(x => x.AgregarCategoria(cat));

            logicMock.Setup(x => x.ObtenerCategoriaId(1)).Returns(cat);

            controller.Post(1, catModel);

            var result   = controller.Get(1);
            var okResult = result as OkObjectResult;
            var retorno  = okResult.Value as Categoria;

            logicMock.VerifyAll();
            Assert.AreEqual(catModel.Nombre, retorno.Nombre);
        }
        public void PutCategoriaOk()
        {
            var logicMock = new Mock <ICategoria>(MockBehavior.Strict);
            CategoriasController controller = new CategoriasController(logicMock.Object);
            CategoriaModel       catModel   = new CategoriaModel()
            {
                Nombre = "Playa",
            };
            Categoria cat = new Categoria()
            {
                Nombre = catModel.Nombre,
                Id     = 0,
            };

            logicMock.Setup(x => x.Categoria(catModel.Nombre)).Returns(cat);
            logicMock.Setup(x => x.AgregarCategoria(cat));

            controller.Post(0, catModel);
            cat.Nombre = "prueba";
            logicMock.Setup(x => x.ActualizarCategoria(cat.Id, cat));

            var result   = controller.Put(cat.Id, cat);
            var okResult = result as OkObjectResult;

            logicMock.VerifyAll();
            Assert.AreEqual("prueba", cat.Nombre);
        }
Ejemplo n.º 8
0
        public async Task CrearCategoria()
        {
            try
            {
                CategoriaModel categoria = new CategoriaModel()
                {
                    Categoria = NombreCategoria.Value
                };
                APIResponse response = await CreateCategoria.EjecutarEstrategia(categoria);

                if (response.IsSuccess)
                {
                    ((MessageViewModel)PopUp.BindingContext).Message = "Categoría creada exitosamente";
                    await PopupNavigation.Instance.PushAsync(PopUp);
                }
                else
                {
                    ((MessageViewModel)PopUp.BindingContext).Message = "Error al crear la categoría";
                    await PopupNavigation.Instance.PushAsync(PopUp);
                }
            }
            catch (Exception e)
            {
            }
        }
Ejemplo n.º 9
0
        public async Task UpdateCategoria()
        {
            try
            {
                CategoriaModel categoria = new CategoriaModel()
                {
                    IdCategoria = Categoria.IdCategoria,
                    Categoria   = NombreCategoria.Value
                };
                ParametersRequest parametros = new ParametersRequest();
                parametros.Parametros.Add(categoria.IdCategoria.ToString());
                APIResponse response = await EditarCategoria.EjecutarEstrategia(categoria, parametros);

                if (response.IsSuccess)
                {
                    ((MessageViewModel)PopUp.BindingContext).Message = "Categoría actualizada exitosamente";
                    await PopupNavigation.Instance.PushAsync(PopUp);
                }
                else
                {
                    ((MessageViewModel)PopUp.BindingContext).Message = "Error al actualizar la categoría";
                    await PopupNavigation.Instance.PushAsync(PopUp);
                }
            }
            catch (Exception e)
            {
            }
        }
        public IHttpActionResult CategoriaCreate(CategoriaModel categoriaModel)
        {
            if (UsuarioModel.Instance.rol != Rol.ADMINISTRADOR && UsuarioModel.Instance.rol != Rol.DEV)
            {
                return(Json(Mensaje <Domain.Entities.Producto.Categoria> .MensajeJson(Constants.IS_ERROR, "No esta autorizado para realizar esta operacion", Constants.NO_AUTH)));
            }

            if (categoriaModel.Categoria == null)
            {
                return(Json(Mensaje <Domain.Entities.Producto.Categoria> .MensajeJson(Constants.IS_ERROR, "Objecto no puede estar vacio", Constants.CATEGORIA_FAIL)));
            }

            var categoria = categoriaModel.GetByName(categoriaModel.Categoria.Nombre);

            if (categoria == null)
            {
                var c = categoriaModel.Create(BuilderFactories.Categoria(categoriaModel.Categoria.Nombre, categoriaModel.Categoria.Descripción, (categoriaModel.Categoria.FechaCreacion.Year < DateTime.Now.Year) ? DateTime.Now : categoriaModel.Categoria.FechaCreacion));
                if (c != null)
                {
                    return(Json(Mensaje <Domain.Entities.Producto.Categoria> .MensajeJson(Constants.NO_ERROR, "Categoria creada con exito", Constants.CATEGORIA_SUCCES)));
                }
                else
                {
                    return(Json(Mensaje <Domain.Entities.Producto.Categoria> .MensajeJson(Constants.IS_ERROR, "Error al crear la categoria", Constants.CATEGORIA_FAIL)));
                }
            }
            else
            {
                return(Json(Mensaje <Domain.Entities.Producto.Categoria> .MensajeJson(Constants.IS_ERROR, "Categoria ya existe", Constants.CATEGORIA_FAIL)));
            }
        }
Ejemplo n.º 11
0
        public IActionResult AtaualizarCategoria([FromBody] CategoriaModel model)
        {
            var entidade = _categoriaRepositorio.Find(model.Id);

            if (entidade == null)
            {
                return(BadRequest(
                           new HandlerMessage(
                               HttpStatusCode.BadRequest,
                               $"Erro ao atualizar categoria"
                               )));
            }

            try
            {
                entidade.Nome = model.Nome;
                _categoriaRepositorio.Update(entidade);
                _categoriaRepositorio.SaveChanges();
                return(Ok(new HandlerMessage(HttpStatusCode.OK, "Categoria Atualiza com sucesso!")));
            }
            catch (Exception ex)
            {
                return(BadRequest(
                           new HandlerMessage(
                               HttpStatusCode.BadRequest,
                               $"Erro ao atualizar categoria {ex.Message}"
                               )));
            }
        }
Ejemplo n.º 12
0
        public IHttpActionResult GetAllCategoria()
        {
            var categorias = new CategoriaModel().GetAll().ToList();

            if (categorias != null)
            {
                categorias.ForEach(x =>
                {
                    x.Productos = ProductoModel.Instance._repository.FindBy(y => y.Categoria_Id == x.Id).ToList();
                    if (x.Productos != null)
                    {
                        x.Productos.ToList().ForEach(y =>
                        {
                            y.ProductoDescuentos = ProductoDescuentoModel.Instance._repository.FindBy(z => z.Producto_Id == y.Id).ToList();

                            if (y.ProductoDescuentos != null)
                            {
                                y.ProductoDescuentos.ToList().ForEach(r =>
                                {
                                    r.Descuento = DescuentoModel.Instance._repository.FindBy(t => t.Id == r.Descuento_Id).FirstOrDefault();
                                    if (r.Descuento != null)
                                    {
                                        y.Descuento += r.Descuento.Descu;
                                    }
                                });
                            }
                        });
                    }
                });
            }
            return(Json(categorias));
        }
 public IEnumerable <KeyValuePair <int, string> > Get(CategoriaModel categoria)
 {
     return(_categoria
            .Listar(categoria)
            .OrderBy(o => o.Descricao)
            .Select(s => new KeyValuePair <int, string>(s.Id, s.Descricao)));
 }
Ejemplo n.º 14
0
        private void GuardarBtn_Clicked(object sender, EventArgs e)
        {
            CRUD Database = new CRUD();

            CategoriaModel NewCategory = new CategoriaModel();

            NewCategory.NameC        = EntryCategoria.Text;
            NewCategory.DescriptionC = EntryDescripcion.Text;

            int IdCategoria = Database.InsertarCategoria(NewCategory);

            if (IdCategoria != -1)
            {
                foreach (ProductosModel ProductoAInsertar in productos_)
                {
                    ProductoAInsertar.IdCategoria = NewCategory.IdC;
                    Database.InsertProduct(ProductoAInsertar);
                }
                Navigation.PushAsync(new RegistroView());
            }
            else
            {
                DisplayAlert("Error", "No se ha podido realizar el registro", "Ok");
            }
        }
Ejemplo n.º 15
0
        public RetornoModel <CategoriaModel> Salvar(CategoriaModel model)
        {
            RetornoModel <CategoriaModel> result = new RetornoModel <CategoriaModel> {
                Mensagem = "OK"
            };

            try
            {
                if (model.ID > 0)
                {
                    result.Sucesso = _ado.Atualizar(model.MapTo <Categoria>());
                    result.Retorno = model;

                    if (!result.Sucesso)
                    {
                        result.Mensagem = "Registro não localizado para modificação. Verifique se o ID informado está correto";
                    }
                }
                else
                {
                    result.Retorno = _ado.Inserir(model.MapTo <Categoria>()).MapTo <CategoriaModel>();
                    result.Sucesso = true;
                }
            }
            catch (Exception ex)
            {
                LogUtil.Error(ex);
                throw;
            }

            return(result);
        }
Ejemplo n.º 16
0
        public IActionResult Edit(int id, [Bind("Id,Nome")] CategoriaModel categoriaModel)
        {
            if (id != categoriaModel.Id)
            {
                return(NotFound());
            }

            if (ModelState.IsValid)
            {
                try
                {
                    repositorio.Update(categoriaModel);
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!CategoriaModelExists(categoriaModel.Id))
                    {
                        return(NotFound());
                    }
                    else
                    {
                        throw;
                    }
                }
                return(RedirectToAction("Index"));
            }
            return(View(categoriaModel));
        }
Ejemplo n.º 17
0
        public IActionResult Index()
        {
            CategoriaModel        objCategoria     = new CategoriaModel();
            List <CategoriaModel> _ListaCategorias = objCategoria.ListarCategorias();

            return(View(_ListaCategorias));
        }
Ejemplo n.º 18
0
 public CategoriaEditViewModel(INavigation navigation)
 {
     Navigation      = navigation;
     CancelarCommand = new Command(cancelar);
     Category        = new CategoriaModel();
     GuardarCommand  = new Command(async() => await Guardar());
 }
        public void DeleteCategoriaOk()
        {
            var logicMock = new Mock <ICategoria>(MockBehavior.Strict);
            CategoriasController controller = new CategoriasController(logicMock.Object);
            CategoriaModel       catModel   = new CategoriaModel()
            {
                Nombre = "Playa",
            };
            Categoria cat = new Categoria()
            {
                Nombre = catModel.Nombre,
                Id     = 0,
            };

            logicMock.Setup(x => x.Categoria(catModel.Nombre)).Returns(cat);
            logicMock.Setup(x => x.AgregarCategoria(cat));

            controller.Post(1, catModel);

            logicMock.Setup(x => x.BorrarCategoriaId(1));

            var result   = controller.Delete(1);
            var okResult = result as OkObjectResult;

            logicMock.VerifyAll();
        }
Ejemplo n.º 20
0
            public async Task <Unit> Handle(RunPut request, CancellationToken cancellationToken)
            {
                var categoria = await _categoriaRepository.Get(request.CategoriaId);

                if (categoria == null)
                {
                    throw new ManejadorError(HttpStatusCode.NoContent, new { mensaje = "La categoria no existe" });
                }

                var categoriaModel = new CategoriaModel
                {
                    CategoriaId     = request.CategoriaId,
                    NombreCategoria = request.NombreCategoria ?? categoria.NombreCategoria,
                    Descripcion     = request.Descripcion ?? categoria.Descripcion
                };

                var result = await _categoriaRepository.Put(categoriaModel);

                if (result > 0)
                {
                    return(Unit.Value);
                }

                throw new Exception("No se pudo actualizar la categoria");
            }
        public void GetCategoriasConElementoOk()
        {
            var logicMock = new Mock <ICategoria>(MockBehavior.Strict);
            CategoriasController controller = new CategoriasController(logicMock.Object);
            CategoriaModel       catModel   = new CategoriaModel()
            {
                Nombre = "Playa",
            };
            Categoria cat = new Categoria()
            {
                Nombre = catModel.Nombre,
                Id     = 0,
            };

            logicMock.Setup(x => x.Categoria(catModel.Nombre)).Returns(cat);
            logicMock.Setup(x => x.AgregarCategoria(cat));

            List <Categoria> lista = new List <Categoria>();

            lista.Add(cat);

            logicMock.Setup(x => x.ObtenerTodas()).Returns(lista);

            controller.Post(1, catModel);

            var result   = controller.Get();
            var okResult = result as OkObjectResult;
            var retorno  = okResult.Value as List <Categoria>;

            logicMock.VerifyAll();
            Assert.AreEqual(1, retorno.Count);
        }
        // GET: CategoriaModels/Delete/5
        public ActionResult Delete(int id)
        {
            CategoriaModel categoriaModel = new CategoriaModel();

            categoriaModel.id = id;
            if (id == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }
            Mapper.Initialize(cfg => cfg.CreateMap <CategoriaModel, Categoria>()
                              .ForMember("Nombre", opt => opt.MapFrom(c => c.Nombre)));

            // Выполняем сопоставление
            Categoria categoria = Mapper.Map <CategoriaModel, Categoria>(categoriaModel);

            // db.Add(user);

            categoria = _CategoriaRepository.FindById(id);

            //CategoriaModel categoriaModel = db.CategoriaModels.Find(id);
            if (categoria == null)
            {
                return(HttpNotFound());
            }
            return(View(categoria));
        }
        public void Testar_Cadastrar_Categoria_Nao_Repetida()
        {
            // arrange
            var categoria = new CategoriaModel()
            {
                nome = "Supermercado"
            };

            var categorias = new List <CategoriaModel>();

            categorias.Add(new CategoriaModel()
            {
                nome = "Restaurante"
            });
            categorias.Add(new CategoriaModel()
            {
                nome = "Borracharia"
            });
            categorias.Add(new CategoriaModel()
            {
                nome = "Posto"
            });
            categorias.Add(new CategoriaModel()
            {
                nome = "Oficina"
            });

            repositoryMock.Setup(x => x.FindByName(categoria.nome)).Returns(categorias.Where(x => x.nome == categoria.nome).FirstOrDefault());

            var result = controller.Create(categoria) as RedirectToRouteResult;

            // assert
            repositoryMock.Verify(x => x.Create(categoria), Times.Once());
            Assert.AreEqual("Index", result.RouteValues["action"]);
        }
Ejemplo n.º 24
0
        public async Task <IActionResult> Crear([FromBody] CategoriaModel model)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    var result = await _service.Crear(CategoriaConvert.toEntity(model));

                    if (result != null)
                    {
                        return(Ok(CategoriaConvert.toModel(result)));
                    }
                    else
                    {
                        return(BadRequest("Error creando la Categoria!!"));
                    }
                }
                else
                {
                    return(BadRequest(ModelState));
                }
            }
            catch (Exception e)
            {
                return(BadRequest(e.Message));

                throw e;
            }
        }
Ejemplo n.º 25
0
        public async Task <CategoriaModel> Delete(CategoriaModel categoria)
        {
            context.Categoria.Remove(categoria);
            await context.SaveChangesAsync();

            return(categoria);
        }
        public bool guardarCategoria(CategoriaModel categoriaModel)
        {
            SqlCommand cmd = null;
            bool       prueba;

            cmd = new SqlCommand(" insert into Categoria(nombreCategoria)" +
                                 " values (@nombreCategoria)", conectar.conn);

            cmd.CommandType = CommandType.Text;

            cmd.Parameters.Add(new SqlParameter("@nombreCategoria", categoriaModel.NombreCategoria));

            conectar.abrir();
            int resultado = cmd.ExecuteNonQuery();

            cmd = null;
            conectar.cerrar();
            if (resultado > 0)
            {
                prueba = true;
            }
            else
            {
                prueba = false;
            }



            return(prueba);
        }
Ejemplo n.º 27
0
        public void Testar_Nao_Cadastrar_Estabelecimento_Categoria_Supermercado_Sem_Informar_Telefone()
        {
            // arrange
            var estabelecimentoVM = new EstabelecimentoViewModel()
            {
                razao_social  = "Estabelecimento 1",
                cnpj          = "94.335.598/0001-13",
                cod_categoria = 1,
                telefone      = ""
            };

            var categoria = new CategoriaModel()
            {
                id = 1, nome = "Supermercado"
            };

            repositoryMockCategoria.Setup(x => x.GetSingle(categoria.id)).Returns(categoria);

            var estabelecimento = Mapper.Map <EstabelecimentoViewModel, EstabelecimentoModel>(estabelecimentoVM);

            // act
            var result = controller.Create(estabelecimentoVM) as ViewResult;

            // assert
            repositoryMock.Verify(x => x.Create(estabelecimento), Times.Never());

            var model = result.ViewData.Model as EstabelecimentoViewModel;

            Assert.AreEqual(estabelecimentoVM, model);

            Assert.AreEqual("Create", result.ViewName);
        }
        public bool EditarCategoria(CategoriaModel categoriaModel)
        {
            SqlCommand cmd = null;
            bool       prueba;

            cmd = new SqlCommand("update Categoria set nombreCategoria=@nombreCategoria" +
                                 " where codigo= @codigo", conectar.conn);

            cmd.CommandType = CommandType.Text;

            cmd.Parameters.Add(new SqlParameter("@codigo", categoriaModel.Codigo));
            cmd.Parameters.Add(new SqlParameter("@nombreCategoria", categoriaModel.NombreCategoria));


            conectar.abrir();
            int resultado = cmd.ExecuteNonQuery();

            cmd = null;
            conectar.cerrar();
            if (resultado > 0)
            {
                prueba = true;
            }
            else
            {
                prueba = false;
            }

            return(prueba);
        }
 public ExcluirCSP(CategoriaModel Categoria)
 {
     operacao = "Categoria";
     InitializeComponent();
     CenterToParent();
     LoadDataGrid();
 }
        // GET: Categoria/Details/5
        public ActionResult Details(int id)
        {
            string requestUrl = "/api/" + _CONTROLLER + "/" + id;

            HttpResponseMessage response = client.GetAsync(requestUrl, HttpCompletionOption.ResponseHeadersRead).Result;

            if (response.IsSuccessStatusCode)
            {
                var data = response.Content.ReadAsStringAsync().Result;

                CategoriaModel model = JsonConvert.DeserializeObject <CategoriaModel>(data);

                if (model != null)
                {
                    return(View(model));
                }
                else
                {
                    return(NotFound());
                }
            }
            else
            {
                return(View());
            }
        }