コード例 #1
0
        public JsonResult Edit(CategoriaFoto CategoriaFoto)
        {
            var Retorno = new RetornoJson();

            if (CategoriaFoto.Nome == null)
            {
                Retorno.Mensagem += "<span> Digite o Nome</span>";
            }

            if (Retorno.Mensagem != "")
            {
                return(Json(Retorno, JsonRequestBehavior.AllowGet));
            }

            var bdCategoriaFoto = new CategoriaFotoRepositorioEF(contexto);

            bdCategoriaFoto.Atualizar(CategoriaFoto);
            bdCategoriaFoto.SalvarTodos();

            Retorno.Mensagem += "<span> Editado com sucesso</span>";

            Retorno.Sucesso      = true;
            Retorno.Redirecionar = true;
            Retorno.Link         = "/Admin/CategoriaFoto/Index";

            return(Json(Retorno, JsonRequestBehavior.AllowGet));
        }
コード例 #2
0
        public JsonResult Create(CategoriaFoto CategoriaFoto)
        {
            var Retorno = new RetornoJson();

            if (CategoriaFoto.Nome == null)
            {
                Retorno.Mensagem += "<span> Digite o Nome</span>";
            }

            if (Retorno.Mensagem != "")
            {
                return(Json(Retorno, JsonRequestBehavior.AllowGet));
            }

            try
            {
                var bdCategoriaFoto = new CategoriaFotoRepositorioEF(contexto);
                bdCategoriaFoto.Adicionar(CategoriaFoto);
                bdCategoriaFoto.SalvarTodos();

                Retorno.Mensagem    += "<span> Cadastrado com sucesso</span>";
                Retorno.Sucesso      = true;
                Retorno.Redirecionar = true;
                Retorno.Link         = "/Admin/CategoriaFoto/Index";
            }catch (Exception e)
            {
                Retorno.Mensagem += "<span> CategoriaFoto não cadastrado.</span>";
            }
            return(Json(Retorno, JsonRequestBehavior.AllowGet));
        }
コード例 #3
0
        public ICommandResult Execute(CreateOrUpdateCategoriaFotoCommand command)
        {
            CategoriaFoto _CategoriaFoto = AutoMapper.Mapper.Map <CreateOrUpdateCategoriaFotoCommand, CategoriaFoto>(command);

            if (command.Id == 0)
            {
                CategoriaFotoRepository.Add(_CategoriaFoto);
            }
            else
            {
                CategoriaFotoRepository.Update(_CategoriaFoto);
            }
            unitOfWork.Commit();

            AutoMapper.Mapper.Map <CategoriaFoto, CreateOrUpdateCategoriaFotoCommand>(_CategoriaFoto, command);

            return(new CommandResult(true));
        }
コード例 #4
0
        public HttpResponseMessage Put(int Id, string cultura, CategoriaFotoModel categoriafoto)
        {
            try {
                if (ModelState.IsValid)
                {
                    if (cultura != Localizacion.CulturaPorDefecto)
                    {
                        CategoriaFoto      _categoriafoto           = categoriafotoRepository.GetById(new string[] {}, (p => p.Id == Id));
                        CategoriaFotoModel _categoriafotoPorDefecto = new CategoriaFotoModel();
                        // Solo funciona el Mapper si se ha configurado el Mapper con Mapper.CreateMap<EmpresaModel, EmpresaModel>(); Se está creando en la carpeta mappers.
                        _categoriafotoPorDefecto = AutoMapper.Mapper.Map <CategoriaFotoModel, CategoriaFotoModel>(categoriafoto, _categoriafotoPorDefecto);

                        _categoriafotoPorDefecto.Nombre = _categoriafoto.Nombre;

                        var command = AutoMapper.Mapper.Map <CategoriaFotoModel, CreateOrUpdateCategoriaFotoCommand>(_categoriafotoPorDefecto);
                        var result  = commandBus.Submit(command);
                    }
                    else
                    {
                        var command = AutoMapper.Mapper.Map <CategoriaFotoModel, CreateOrUpdateCategoriaFotoCommand>(categoriafoto);
                        var result  = commandBus.Submit(command);
                    }
                    CategoriaFoto_Idioma _categoriafotoIdioma = categoriafoto_IdiomaRepository.GetMany(t => t.IdRegistro == categoriafoto.Id && t.Cultura == cultura).FirstOrDefault();
                    var commandIdioma = AutoMapper.Mapper.Map <CategoriaFoto_IdiomaModel, CreateOrUpdateCategoriaFoto_IdiomaCommand>(new CategoriaFoto_IdiomaModel {
                        Id = (_categoriafotoIdioma != null ? _categoriafotoIdioma.Id : (int)0), IdRegistro = categoriafoto.Id, Cultura = cultura, Nombre = categoriafoto.Nombre
                    });
                    var resultIdioma = commandBus.Submit(commandIdioma);
                    return(Request.CreateResponse <CategoriaFotoModel>(HttpStatusCode.OK, categoriafoto));
                }
                else
                {
                    var errors = new Dictionary <string, IEnumerable <string> >();
                    foreach (var keyValue in ModelState)
                    {
                        errors[keyValue.Key] = keyValue.Value.Errors.Select(e => (!string.IsNullOrWhiteSpace(e.ErrorMessage) ? e.ErrorMessage : (e.Exception != null ? e.Exception.Message : string.Empty)));
                    }
                    return(Request.CreateResponse(HttpStatusCode.BadRequest, errors));
                }
                throw new HttpResponseException(HttpStatusCode.BadRequest);
            } catch (Exception _excepcion) {
                log.Error(_excepcion);
                return(Request.CreateResponse(HttpStatusCode.InternalServerError, _excepcion));
            }
        }
コード例 #5
0
        public HttpResponseMessage Get([FromUri] int Id, [FromUri] string cultura, [FromUri] string[] include, [FromUri] bool indent = false)
        {
            try {
                var formatter = new MaxDepthJsonMediaTypeFormatter()
                {
                    Indent = indent
                };
                if (include.Length > 0)
                {
                    formatter.SerializerSettings.MaxDepth = 100;                     //include.Max<string>(s => s.Split('.').Length * 5);
                    formatter.SerializerSettings.PreserveReferencesHandling = Newtonsoft.Json.PreserveReferencesHandling.Objects;
                }
                else
                {
                    formatter.SerializerSettings.MaxDepth = 1;
                }
                CategoriaFoto _categoriafoto = categoriafotoRepository.GetById(include, (p => p.Id == Id));
                if (cultura != Localizacion.CulturaPorDefecto)
                {
                    CategoriaFoto_Idioma _categoriafotoIdioma = categoriafoto_IdiomaRepository.GetMany(p => p.IdRegistro == Id && p.Cultura == cultura).FirstOrDefault();

                    // Campos multiidioma
                    if (_categoriafotoIdioma != null)
                    {
                        _categoriafoto.Nombre = _categoriafotoIdioma.Nombre;
                    }
                }

                if (_categoriafoto == null)
                {
                    throw new HttpResponseException(HttpStatusCode.NotFound);
                }
                return(Request.CreateResponse <CategoriaFoto>(HttpStatusCode.OK, _categoriafoto, formatter));
            } catch (Exception _excepcion) {
                log.Error(_excepcion);
                return(Request.CreateResponse(HttpStatusCode.InternalServerError, _excepcion));
            }
        }
コード例 #6
0
        public HttpResponseMessage CargaMasiva()
        {
            // Creating a variable to store the file if it has been sent.
            HttpPostedFile uploadedFile  = HttpContext.Current.Request.Files.Count > 0 ? HttpContext.Current.Request.Files[0] : null;
            string         _rutaRelativa = HttpContext.Current.Request.Form["Ruta"];
            string         _idMarca      = HttpContext.Current.Request.Form["IdMarca"];

            if (uploadedFile != null && uploadedFile.ContentLength > 0 && uploadedFile.ContentLength <= 262144000)
            {
                var _nombreArchivo = Path.GetFileName(uploadedFile.FileName);

                // Set the path in Web.Config file to save the uploaded files.
                string _directorio = ConfigurationManager.AppSettings["RutaArchivos"] + _rutaRelativa.Replace(Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar);

                if (!Directory.Exists(_directorio))
                {
                    Directory.CreateDirectory(_directorio);
                }
                uploadedFile.SaveAs(_directorio + "\\" + _nombreArchivo);
                if (Path.GetExtension(_nombreArchivo) == ".zip")
                {
                    using (ZipArchive _file = ZipFile.OpenRead(_directorio + "\\" + _nombreArchivo)) {
                        _file.ExtractToDirectory(_directorio, true);
                    }
                    //ZipFile.ExtractToDirectory(_directorio + "\\" + _nombreArchivo, _directorio);
                    File.Delete(_directorio + "\\" + _nombreArchivo);
                }

                Dictionary <string, CategoriaFoto> _categoriasProcesadas = new Dictionary <string, CategoriaFoto>();
                List <MensajeModel> _mensajes = new List <MensajeModel>();
                int _indiceEntidades          = 0;
                foreach (string _archivo in Directory.GetFiles(_directorio, "*.*", SearchOption.AllDirectories))
                {
                    string _rutaArchivoRelativa = _archivo.Replace(_directorio, string.Empty);
                    try {
                        string[] _partes = _rutaArchivoRelativa.Split('\\');
                        if (_partes.Length == 2)
                        {
                            string _categoria = _partes[0];
                            if (!_categoriasProcesadas.ContainsKey(_categoria))
                            {
                                CategoriaFoto _categoriaFoto = categoriaFotoRepository.GetMany(cf => cf.Nombre == _categoria).FirstOrDefault();
                                if (_categoriaFoto == null)
                                {
                                    _categoriaFoto = new CategoriaFoto()
                                    {
                                        Id = --_indiceEntidades, Activa = true, FechaAlta = DateTime.Now, Nombre = _categoria, Orden = 1
                                    };
                                    _categoriaFoto.RegistrosIdiomas.Add(new CategoriaFoto_Idioma()
                                    {
                                        IdRegistro = _indiceEntidades, Cultura = "es-ES", Nombre = _categoria
                                    });
                                    _categoriaFoto.RegistrosIdiomas.Add(new CategoriaFoto_Idioma()
                                    {
                                        IdRegistro = _indiceEntidades, Cultura = "ca-ES", Nombre = _categoria
                                    });
                                    _categoriaFoto.RegistrosIdiomas.Add(new CategoriaFoto_Idioma()
                                    {
                                        IdRegistro = _indiceEntidades, Cultura = "en-US", Nombre = _categoria
                                    });
                                    categoriaFotoRepository.Add(_categoriaFoto);
                                }
                                _categoriasProcesadas.Add(_categoria, _categoriaFoto);
                            }
                            string _nombreArchivoImagen = _partes[1];
                            int    _idCategoria         = _categoriasProcesadas[_categoria].Id;
                            Foto   _foto = fotoRepository.GetMany(f => f.IdCategoria == _idCategoria && f.NombreArchivoImagen == _rutaArchivoRelativa).FirstOrDefault();
                            if (_foto == null)
                            {
                                _foto = new Foto()
                                {
                                    Id = --_indiceEntidades, Activa = true, Descripcion = Path.GetFileNameWithoutExtension(_nombreArchivoImagen), FechaAlta = DateTime.Now, IdCategoria = _categoriasProcesadas[_categoria].Id, Nombre = Path.GetFileNameWithoutExtension(_nombreArchivoImagen), NombreArchivoImagen = _rutaArchivoRelativa, Orden = 1
                                };
                                _foto.RegistrosIdiomas.Add(new Foto_Idioma()
                                {
                                    IdRegistro = _indiceEntidades, Cultura = "es-ES", Nombre = Path.GetFileNameWithoutExtension(_nombreArchivoImagen), Descripcion = Path.GetFileNameWithoutExtension(_nombreArchivoImagen)
                                });
                                _foto.RegistrosIdiomas.Add(new Foto_Idioma()
                                {
                                    IdRegistro = _indiceEntidades, Cultura = "ca-ES", Nombre = Path.GetFileNameWithoutExtension(_nombreArchivoImagen), Descripcion = Path.GetFileNameWithoutExtension(_nombreArchivoImagen)
                                });
                                _foto.RegistrosIdiomas.Add(new Foto_Idioma()
                                {
                                    IdRegistro = _indiceEntidades, Cultura = "en-US", Nombre = Path.GetFileNameWithoutExtension(_nombreArchivoImagen), Descripcion = Path.GetFileNameWithoutExtension(_nombreArchivoImagen)
                                });
                                fotoRepository.Add(_foto);
                            }
                            _mensajes.Add(new MensajeModel()
                            {
                                Tipo = "Mensaje", Texto = string.Format("Se cargado el archivo '{0}' correctamente.", _rutaArchivoRelativa)
                            });
                        }
                        else if (_partes.Length > 2)
                        {
                            _mensajes.Add(new MensajeModel()
                            {
                                Tipo = "Advertencia", Texto = string.Format("No se puede cargar el archivo '{0}'. Debe indicar un único nivel de carpetas para indicar la categoría.", _rutaArchivoRelativa)
                            });
                            Directory.Delete(Path.GetDirectoryName(_archivo), true);
                        }
                        else if (_partes.Length == 1)
                        {
                            _mensajes.Add(new MensajeModel()
                            {
                                Tipo = "Advertencia", Texto = string.Format("No se puede cargar el archivo '{0}'. Debe ubicar el archivos dentro de la carpeta de su categoría.", _rutaArchivoRelativa)
                            });
                            File.Delete(_archivo);
                        }
                    } catch (Exception _excepcion) {
                        _mensajes.Add(new MensajeModel()
                        {
                            Tipo = "Error", Texto = string.Format("No se puede cargar el archivo '{0}'. Detalle del error: {1}", _rutaArchivoRelativa, _excepcion.Message)
                        });
                    }
                }
                Uow.Commit();

                return(Request.CreateResponse <CargaArchivoModel>(HttpStatusCode.OK, new CargaArchivoModel()
                {
                    Ruta = _nombreArchivo, Mensaje = "Carga finalizada correctamente.", Mensajes = _mensajes.ToArray()
                }));
            }
            else
            {
                return(Request.CreateResponse <string>(HttpStatusCode.InternalServerError, "Error en la carga del fichero al servidor. No se ha detectado contenido en la petición."));
            }
        }