Exemplo n.º 1
0
        public async Task <IActionResult> Edit(int id, [Bind("NoticiaId,Titulo,DataDaInclusao,Descricao,NomeDaImagem")] NoticiaModel noticiaModel)
        {
            if (id != noticiaModel.NoticiaId)
            {
                return(NotFound());
            }

            if (ModelState.IsValid)
            {
                try
                {
                    _context.Update(noticiaModel);
                    await _context.SaveChangesAsync();
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!NoticiaModelExists(noticiaModel.NoticiaId))
                    {
                        return(NotFound());
                    }
                    else
                    {
                        throw;
                    }
                }
                return(RedirectToAction(nameof(Index)));
            }
            return(View(noticiaModel));
        }
Exemplo n.º 2
0
        public bool AtualizarNoticia(NoticiaModel noticiaObj)
        {
            try
            {
                Connection();

                using (SqlCommand command = new SqlCommand("up_tb_noticia", _con))
                {
                    command.CommandType = CommandType.StoredProcedure;
                    command.Parameters.AddWithValue("@cod_noticia", noticiaObj.cod_noticia);
                    command.Parameters.AddWithValue("@nom_titulo_noticia", noticiaObj.nom_titulo_noticia);
                    command.Parameters.AddWithValue("@ds_noticia", noticiaObj.ds_noticia);
                    command.Parameters.AddWithValue("@ds_tipo_noticia", noticiaObj.tipo_noticia_selected);
                    command.Parameters.AddWithValue("@im_vitrine", noticiaObj.nom_imagem);

                    _con.Open();

                    command.ExecuteNonQuery();
                }

                _con.Close();

                return(true);
            }
            catch (Exception e)
            {
                _con.Close();
                throw new Exception("Erro ao atualizar Noticia. Error: " + e);
            }
        }
Exemplo n.º 3
0
        public async Task <IActionResult> Create([Bind("NoticiaId,Titulo,DataDaInclusao,Descricao,NomeDaImagem")] NoticiaModel noticiaModel)
        {
            if (ModelState.IsValid)
            {
                _context.Add(noticiaModel);
                await _context.SaveChangesAsync();

                return(RedirectToAction(nameof(Index)));
            }
            return(View(noticiaModel));
        }
Exemplo n.º 4
0
        /// <summary>
        /// Buscamos en la web por más información relacionada con la noticia (Contenido, Imagen, YoutubeID, etc...)
        /// </summary>
        /// <param name="BaseItem">Noticia (NoticiaModel) sobre la cual queremos buscar más información</param>
        /// <returns>Devuelve la noticia "Ampliada" (NoticiaModel)</returns>
        public static async Task <NoticiaModel> DetallesNoticias(NoticiaModel BaseItem)
        {
            string TextoHTML = string.Empty;
            await Task.Run(async() =>
            {
                TextoHTML = await IntentarCargarContenidoWeb(BaseItem.Url);
            });

            HtmlDocument Documento = new HtmlDocument();

            Documento.LoadHtml(TextoHTML);

            #region method one
            var NoticiaNodes = Documento.DocumentNode.SelectSingleNode("//section[@class='col-md-9 col-md-pull-3']/article");
            if (NoticiaNodes == null)
            {
                Console.WriteLine("No se ha encontrado ningún Item");
            }
            else
            {
                if (NoticiaNodes.NodeType == HtmlNodeType.Element)
                {
                    //Cargar info
                    var BloquedeNoticias = NoticiaNodes.SelectSingleNode(".//div[@class='body f-width']");
                    BaseItem.Contenido = HttpUtility.HtmlDecode(BloquedeNoticias.InnerHtml);
                    try
                    {
                        BaseItem.ImageUrl = @"https://www.mirametv.com" + NoticiaNodes.SelectSingleNode(".//div[@class='aspect-wide']/figure/img").Attributes["src"].Value;
                    }
                    catch (Exception Error)
                    {
                        Console.WriteLine(Error);
                        try
                        {
                            BaseItem.VideoID = (NoticiaNodes.SelectSingleNode(".//div[@class='aspect-wide']/iframe").Attributes["src"].Value).Split('/').Last();
                        }
                        catch (Exception ErrorInt)
                        {
                            Console.WriteLine(ErrorInt);
                            BaseItem.ImageUrl = "Placeholder.jpg";
                        }
                    }
                    return(BaseItem);
                }
                else
                {
                    Console.WriteLine("Not an element");
                }
            }
            return(BaseItem);

            #endregion
        }
Exemplo n.º 5
0
    private void LlenarPagina()
    {
        //obtener una lista de todos los productos en la BD
        NoticiaModel   noticiaModel = new NoticiaModel();
        List <Noticia> noticias     = noticiaModel.GetAllNoticias();

        //asegurarse de que los productos existen en la base de datos
        if (noticias != null)
        {
            //cree un nuevo panel con un botón de imagen y dos etiquetas para cada producto
            foreach (Noticia noticia in noticias)
            {
                Panel       productoPanel = new Panel();
                ImageButton imageButton   = new ImageButton();
                Label       lblTitulo     = new Label();


                //establecer propiedades de controles secundarios
                imageButton.ImageUrl = "~/Imagenes/Productos/" + noticia.Imagen;
                imageButton.CssClass = "productoImagen";


                lblTitulo.Text     = noticia.Titulo;
                lblTitulo.CssClass = "productoNombre";



                //agregar controles secundarios al panel
                productoPanel.Controls.Add(imageButton);
                productoPanel.Controls.Add(new Literal {
                    Text = "<br />"
                });
                productoPanel.Controls.Add(lblTitulo);
                productoPanel.Controls.Add(new Literal {
                    Text = "<br />"
                });


                //agregar panel dinámico al panel principal estático
                pnlNoticias.Controls.Add(productoPanel);
            }
        }
        else
        {
            //no se encontraron productos
            pnlNoticias.Controls.Add(new Literal {
                Text = "no se encontraron noticias"
            });
        }
    }
    private void LlenarPagina(int id)
    {
        //obtener producto seleccionado de la bd
        NoticiaModel noticiaModel = new NoticiaModel();
        Noticia      noticia      = noticiaModel.GetNoticia(id);

        //llenar cuadro de textos
        txtTitulo.Text      = noticia.Titulo;
        txtDescripcion.Text = noticia.Descripcion;



        //establecer el valor de la lista desplegable
        ddlImagen.SelectedValue = noticia.Imagen;
    }
Exemplo n.º 7
0
        public void ExcluirImagem(NoticiaModel noticia)
        {
            var filePath = Server.MapPath("~/ImagensVitrine/" + noticia.nom_imagem);

            FileInfo imagem = new FileInfo(filePath);

            try
            {
                if (noticia.nom_imagem != "Apresentacao.jpg" || noticia.nom_imagem != "Festival.jpg" || noticia.nom_imagem != "Novidade.jpg")
                {
                    imagem.Delete();
                }
            }
            catch (Exception e)
            {
                ViewBag.Message("Erro ao deletar Imagem.");
            }
        }
    protected void btnEnviar_Click(object sender, EventArgs e)
    {
        NoticiaModel noticiaModel = new NoticiaModel();
        Noticia      noticia      = createNoticia();

        //comprueba si la url contiene un parámetro id
        if (!String.IsNullOrWhiteSpace(Request.QueryString["id"]))
        {
            //si Id existe se actualiza la fila existente
            int id = Convert.ToInt32(Request.QueryString["id"]);
            lblResultado.Text = noticiaModel.ActualizarNoticia(id, noticia);
        }
        else
        {
            //si Id no existe se crea una nueva fila
            lblResultado.Text = noticiaModel.InsertarNoticia(noticia);
        }
    }
Exemplo n.º 9
0
        public List <NoticiaModel> ListarNoticias()
        {
            List <NoticiaModel> listaNoticias = new List <NoticiaModel>();

            try
            {
                Connection();

                using (SqlCommand command = new SqlCommand("se_all_tb_noticia", _con))
                {
                    command.CommandType = CommandType.StoredProcedure;

                    _con.Open();

                    SqlDataReader reader = command.ExecuteReader();

                    while (reader.Read())
                    {
                        NoticiaModel noticia = new NoticiaModel()
                        {
                            cod_noticia           = Convert.ToInt32(reader["cod_noticia"]),
                            nom_titulo_noticia    = Convert.ToString(reader["nom_titulo_noticia"]),
                            tipo_noticia_selected = Convert.ToString(reader["ds_tipo_noticia"]),
                            ds_noticia            = Convert.ToString(reader["ds_noticia"]),
                            dat_noticia           = Convert.ToDateTime(reader["dat_noticia"]),
                            cod_imagem            = Convert.ToInt32(reader["cod_imagem"]),
                            //im_vitrine = nom_imagem
                            nom_imagem = Convert.ToString(reader["nom_imagem"])
                        };

                        listaNoticias.Add(noticia);
                    }

                    _con.Close();

                    return(listaNoticias);
                }
            }
            catch (Exception e)
            {
                _con.Close();
                throw new Exception("Erro ao buscar Noticias. Error: " + e);
            }
        }
Exemplo n.º 10
0
        public NoticiaModel BuscarNoticia(string nomTituloNoticia = null, string dsNoticia = null, string dsTipoNoticia = null)
        {
            try
            {
                NoticiaModel noticiaObj = new NoticiaModel();

                using (SqlCommand command = new SqlCommand("se_tb_noticia", _con))
                {
                    command.CommandType = CommandType.StoredProcedure;
                    command.Parameters.AddWithValue("@nom_titulo_noticia", nomTituloNoticia);
                    command.Parameters.AddWithValue("@ds_noticia", dsNoticia);
                    command.Parameters.AddWithValue("@ds_tipo_noticia", dsTipoNoticia);

                    _con.Open();

                    SqlDataReader reader = command.ExecuteReader();

                    noticiaObj.cod_noticia           = Convert.ToInt32(reader["cod_noticia"]);
                    noticiaObj.nom_titulo_noticia    = Convert.ToString(reader["nom_titulo_noticia"]);
                    noticiaObj.tipo_noticia_selected = Convert.ToString(reader["ds_tipo_noticia"]);
                    noticiaObj.ds_noticia            = Convert.ToString(reader["ds_noticia"]);
                    noticiaObj.dat_noticia           = Convert.ToDateTime(reader["dat_noticia"]);
                    noticiaObj.cod_imagem            = Convert.ToInt32(reader["cod_imagem"]);
                    //im_vitrine = nom_imagem
                    noticiaObj.nom_imagem = Convert.ToString(reader["nom_imagem"]);

                    _con.Close();

                    return(noticiaObj);
                }
            }
            catch (Exception e)
            {
                _con.Close();
                throw new Exception("Erro ao buscar a Noticia. Error: " + e);
            }
        }
Exemplo n.º 11
0
        public ActionResult UpNoticia(int codNoticia, NoticiaModel noticia)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    _repositorio = new NoticiaRepository();

                    //Metodo para excluri imagem.
                    ExcluirImagem(noticia);

                    //Esse metodo Que salva o nome da imagem(com mais um monte de validacoes)
                    SalvarImagem(noticia);

                    _repositorio.AtualizarNoticia(noticia);
                }

                return(RedirectToAction("ListarNoticias"));
            }
            catch (Exception e)
            {
                return(View("ListarNoticias"));
            }
        }
Exemplo n.º 12
0
        public ActionResult InNoticia(NoticiaModel noticia)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    _repositorio = new NoticiaRepository();

                    //Esse metodo Que salva o nome da imagem(com mais um monte de validacoes)
                    SalvarImagem(noticia);

                    if (_repositorio.InserirNoticia(noticia))
                    {
                        ViewBag.MessageCadastroSucesso = "Noticia Cadastrada com Sucesso!";
                    }
                }

                return(View());
            }
            catch (Exception e)
            {
                return(View("ListarNoticias"));
            }
        }
Exemplo n.º 13
0
        private ActionResult LoadIndexNews(string editorialUrl, string categoryUrl, string blogurl, string newsUrl, bool isPreview = false)
        {
            try
            {
                // redirect where curitiba
                if (editorialUrl == "where-curitiba")
                {
                    return(new RedirectResult("http://www.wherecuritiba.com.br", true));
                }

                var newsId = ToolService.GetIdByUrl(Request.Url.ToString());

                //Get the news object
                var objNoticia = null as Noticia;

                if (newsId.HasValue)
                {
                    objNoticia = Noticia.Load(newsId.Value);
                }

                if (objNoticia == null)
                {
                    objNoticia = Noticia.GetByUrl(newsUrl);
                }

                #region Validations
                //Redirect 301 to new url
                if (!isPreview)
                {
                    #region Redirect

                    var originUrl = Request.RawUrl.Remove(Request.RawUrl.Length - 5);

                    if (objNoticia != null)
                    {
                        if (originUrl != objNoticia.UrlFull)
                        {
                            return(new RedirectResult($"{objNoticia.UrlFull}.html", true));
                        }
                    }
                    else
                    {
                        var redirectUrl = UrlRedirect.GetByUrl(originUrl);

                        if (!string.IsNullOrEmpty(redirectUrl))
                        {
                            return(new RedirectResult($"{redirectUrl}.html", true));
                        }
                    }

                    #endregion
                }

                if (objNoticia == null)
                {
                    return(new HttpStatusCodeResult(HttpStatusCode.NotFound));
                }

                if (objNoticia.Autores != null && objNoticia.Autores.Count() > 0)
                {
                    //19 = Estadão, 65 = Folhapress
                    var objAutorGoogleNews = objNoticia.Autores.Where(a => a.Id == 19 || a.Id == 65).FirstOrDefault();

                    ViewBag.isAutorGoogleNews = objAutorGoogleNews != null ? true : false;
                }

                //Caso a noticia for inativa responde com redirect permanente para a home
                if ((objNoticia.StatusId == Status.Inativa.Id || !objNoticia.Categoria.Status) && !isPreview)
                {
                    return(new RedirectResult("/", true));
                }

                //Caso a noticia for diferente de publicada responde com 404
                if (objNoticia.StatusId != Status.Publicada.Id && !isPreview)
                {
                    return(new HttpStatusCodeResult(HttpStatusCode.NotFound));
                }

                #endregion

                //Recupera a origem
                var urlReferrer = Request.UrlReferrer?.AbsolutePath.TrimEnd('/') ?? string.Empty;

                //Ultimas Notícias
                var lastestNews = new List <Noticia>();

                //Get the location id
                var locationId = CookieFx.GetLocationId(Request);

                //Get the user city
                var objCidade = Cidade.Load(locationId);

                //getTemperature(locationId);

                if (urlReferrer.StartsWith("/tag"))
                {
                    var tagUrl = urlReferrer.Split('/').Last();

                    var tag = Tag.GetByUrl(tagUrl);

                    if (tag == null)
                    {
                        return(null);
                    }

                    var isNewsWithTag = false;

                    var newsWithTag = NoticiaSrv.GetTagsByNewsIdCached(objNoticia.Id);

                    foreach (var item in newsWithTag)
                    {
                        if (item.Id == tag.Id)
                        {
                            isNewsWithTag = true;
                            break;
                        }
                    }

                    if (isNewsWithTag)
                    {
                        lastestNews = GetValuesOfTag(urlReferrer, objNoticia).ToList();
                    }
                    else if (editorialUrl == "blogs")
                    {
                        lastestNews = GetValuesOfBlogCategory(objNoticia).ToList();
                    }
                    else
                    if (objNoticia.CidadeId.HasValue && objNoticia.CategoriaUrl.Equals("plantao"))
                    {
                        if (objNoticia.Cidade.MicroregiaoId == objCidade.MicroregiaoId)
                        {
                            lastestNews = GetValuesOfMyRegion(objCidade.MicroregiaoId, objNoticia).ToList();
                        }
                        else if (objNoticia.Cidade.MicroregiaoId != objCidade.MicroregiaoId)
                        {
                            lastestNews = GetValuesOfParana(objCidade.MicroregiaoId, objNoticia).ToList();
                        }
                    }
                    else if (!objNoticia.CidadeId.HasValue && objNoticia.CategoriaUrl.Equals("plantao"))
                    {
                        lastestNews = GetValuesOfParana(objCidade.MicroregiaoId, objNoticia).ToList();
                    }
                    else
                    {
                        lastestNews = GetValuesOfCategory(objNoticia).ToList();
                    }
                }
                else if (urlReferrer.StartsWith("/fotos"))
                {
                    lastestNews = GetValuesOfGallery().ToList();
                }
                else if (editorialUrl == "blogs")
                {
                    lastestNews = GetValuesOfBlogCategory(objNoticia).ToList();
                }
                else
                {
                    if (objNoticia.CidadeId.HasValue)
                    {
                        //If the news has the category 'plantao'
                        if (objNoticia.CategoriaUrl.Equals("plantao"))
                        {
                            if (objNoticia.Cidade.MicroregiaoId == objCidade.MicroregiaoId)
                            {
                                //Sua Região
                                lastestNews = GetValuesOfMyRegion(objCidade.MicroregiaoId, objNoticia).ToList();
                            }
                            else if (objNoticia.Cidade.MicroregiaoId != objCidade.MicroregiaoId)
                            {
                                //Paraná
                                lastestNews = GetValuesOfParana(objCidade.MicroregiaoId, objNoticia).ToList();
                            }
                        }
                        else
                        {
                            //If the news is's category 'plantao
                            lastestNews = GetValuesOfCategory(objNoticia).ToList();
                        }
                    }
                    else
                    {
                        //If the news has the category 'plantao'
                        if (objNoticia.CategoriaUrl.Equals("plantao"))
                        {
                            //Paraná
                            lastestNews = GetValuesOfParana(objCidade.MicroregiaoId, objNoticia).ToList();
                        }
                        else
                        {
                            //If the news is's category 'plantao
                            lastestNews = GetValuesOfCategory(objNoticia).ToList();
                        }
                    }
                }

                //Habilita Comentários
                ViewBag.AllowComments = !isPreview;

                //Caso a notícia exista na lista é removida para evitar duplicidade
                if (lastestNews.Any(n => n.Id == objNoticia.Id))
                {
                    lastestNews.Remove(lastestNews.Single(n => n.Id == objNoticia.Id));
                }

                //insere noticia na lista de notícias
                lastestNews.Insert(0, objNoticia);

                ViewBag.NavItems = lastestNews.Select(n => new NoticiaNavItem(n, lastestNews.IndexOf(n).Equals(0)));

                ViewBag.Lastest4News = lastestNews.Take(4).ToList();

                //Set the list of categories
                if (objNoticia.Categoria.EditorialId == 4 && ViewBag.NavigationType == "categoria")
                {
                    ViewBag.Categorias      = NoticiaSrv.GetCategoriasByEditorial(objNoticia.Categoria.EditorialId);
                    ViewBag.MenuCategoriaId = objNoticia.Categoria.CategoriaPaiId.HasValue ? objNoticia.Categoria.CategoriaPaiId : objNoticia.Categoria.Id;
                }

                ViewBag.AmpLink = $"{Constants.UrlWeb}/amp{objNoticia.UrlFull}.html";

                /* base model defaults */
                var model = new NoticiaModel
                {
                    //Title = $"{objNoticia.Titulo} - Massa News {objNoticia.Cidade.Nome}",
                    Description = $"{(objNoticia.Conteudo.Length > 220 ? Text.RemoveHtmlTags(objNoticia.Conteudo.Substring(0, 220) + "... Leia mais no Massa News!") : Text.RemoveHtmlTags(objNoticia.Conteudo) + " Leia no Massa News!")}",
                    Robots      = isPreview ? "noindex, nofollow" : "index, follow",
                    Canonical   = $"{Constants.UrlWeb}{objNoticia.UrlFull}.html",
                    News        = new NewsItemViewModel(objNoticia, ControllerContext)
                };

                if (objNoticia.Cidade != null && !string.IsNullOrEmpty(objNoticia.Cidade.Nome))
                {
                    model.Title = $"{objNoticia.Titulo} - Massa News {objNoticia.Cidade.Nome}";
                }
                else if (objNoticia.Blog != null && !string.IsNullOrEmpty(objNoticia.Blog.Titulo))
                {
                    model.Title = $"{objNoticia.Titulo} - {objNoticia.Blog.Titulo} - Massa News";
                }
                else
                {
                    model.Title = $"{objNoticia.Titulo} - Massa News";
                }

                if (!string.IsNullOrEmpty(objNoticia.ImgLg))
                {
                    model.ImgOpenGraph = $"{Constants.UrlDominioEstaticoUploads}/{"noticias"}/{objNoticia.ImgLg}";
                }
                else if (objNoticia.Blog != null)
                {
                    model.ImgOpenGraph = $"{Constants.UrlWeb}/content/images/avatar/blogs/{objNoticia.Blog.Url}.jpg";
                }

                // Página
                ViewBag.Pagina = "interna";

                // ID
                ViewBag.Id = objNoticia.Id;

                // Editoria
                ViewBag.EditoriaUrl    = objNoticia.Categoria.Editorial.Url;
                ViewBag.EditoriaTitulo = objNoticia.Categoria.Editorial.Titulo;

                // Categoria
                ViewBag.Categoria = objNoticia.CategoriaUrl;

                //Formata Noticia Site Antigo Negocio da Terra
                if (editorialUrl == "negocios-da-terra" && objNoticia.DataPublicacao < new DateTime(2017, 09, 12))
                {
                    var aux = model.News.News.Conteudo.Split('\n');
                    model.News.News.Conteudo = "";

                    foreach (var item in aux)
                    {
                        if (!String.IsNullOrEmpty(item))
                        {
                            model.News.News.Conteudo = model.News.News.Conteudo + "<p>" + item + "</p>";
                        }
                    }
                }

                return(View("index", model));
            }
            catch (Exception ex)
            {
                var vars = new Dictionary <string, string>
                {
                    { "Editorial", editorialUrl },
                    { "Category", categoryUrl },
                    { "NewsUrl", newsUrl }
                };

                NewRelic.Api.Agent.NewRelic.NoticeError(ex, vars);

                throw;
            }
        }
Exemplo n.º 14
0
        //[HttpPost]
        //public ActionResult CadastroNoticia(NoticiaModel noticia)
        //{
        //    try
        //    {
        //        SalvarImagem(noticia);

        //        //Chama o metodo que realiza o insert na base.
        //        InNoticia(noticia);

        //        return View();
        //    }
        //    catch (Exception e)
        //    {
        //        return View();
        //    }

        //}


        public void SalvarImagem(NoticiaModel noticia)
        {
            string path = Server.MapPath("~/ImagensVitrine/");

            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }

            //Tratar o erro de variavel tipo httpPostedFFileBase null
            var ImageNull = noticia.im_vitrine as HttpPostedFileBase;

            if (ImageNull == null)
            {
                switch (noticia.ds_tipo_noticia.ToString())
                {
                case "Novidade":
                    noticia.nom_imagem = "Novidade.jpg";
                    break;

                case "Apresentação":
                    noticia.nom_imagem = "Apresentacao.jpg";
                    break;

                case "Festival":
                    noticia.nom_imagem = "Festival.jpg";
                    break;
                }

                //Limpa os campos do formulario, precisa estar antes do View().
                ModelState.Clear();
            }
            else
            {
                //Resgatando o nome da imagem para jogar no viewbag.
                string oldFileName = Path.GetFileName(noticia.im_vitrine.FileName);

                //Gera um indenficador QUASE unico para renomear a imagem e salva-la na pagina.
                string newFileName = Guid.NewGuid().ToString("N");

                //chama o metodo de validacao de imagens que retorna true ou false.
                if (validarImagem(noticia.im_vitrine))
                {
                    //resgata o formato da imagem para renomear com a extensao.
                    string[] formatoImagem = noticia.im_vitrine.ContentType.Split('/');

                    //salva a imagem na pasta determinada no path.
                    noticia.im_vitrine.SaveAs(path + newFileName + "." + formatoImagem[1]);

                    noticia.nom_imagem = newFileName + "." + formatoImagem[1];

                    //ViewBag.MessageSucesso += string.Format("<b>{0}</b> Sucesso ao subir a imagem.<br />", oldFileName);
                    //ViewBag.MessageCadastroSucesso += string.Format("Noticia Registrada com Sucesso.");

                    //Limpa os campos do formulario, precisa estar antes do View().
                    ModelState.Clear();
                }
                else
                {
                    /*ViewBag usa o {0}, {1}, {2} e assim vai, e voce vai colocando os campos no final de acordo com a ordem que deseja.
                     * Ex: fileName, isso faz concatenar a mensagem com variaveis.*/
                    ViewBag.MessageErro += string.Format("Somente arquivos .jpeg .jpg .png .gif. com Resolucao Max 2mb 684x312.");
                }
            }
            //return View();
        }