Tutorial - RSS Feed
Autor: Bira | Publicado: 2013-06-03T23:31:00-03:00

Olá, pessoal.
Bem nunca escrevi sobre tecnologia aqui no blog, mas tudo tem a sua primeira vez!

Então vamos lá, hoje trago um exemplo de leitor de RSS, é bem simples a solution esta no VS 2012.
Utilizei como fonte de pesquisa o site http://www.geekpedia.com/tutorial147_Creating-an-RSS-feed-reader-in-Csharp.html , que mostra como fazer uma solução voltada para desktop. Achei uma solução prática e fiz algumas adaptações para pode utilizar o exemplo para fazer um Web Forms.



O RSS
O RSS (Really Simple Syndication – RSS 2.0) é uma maneira simplificada de apresentar conteúdo de um site, ele é construído em XML (eXtensible Markup Language) e pode ser acessado por um programa especifico ou sites agregadores. 
Uma das vantagens é que não é preciso acessar um determinado site, ou sites, para ver o que esta sendo atualizado ou postado, com o leitor de RSS você escolhe o tipo de informação (muitos RSS são separados por categorias, tais como: Tecnologia, Economia, etc..) que deseja e de quais sites em um único lugar.


Codificando
Primeiro passo foi criar uma solução web no VS 2012, conforme segue figura abaixo.



O VS 2012, cria um projeto web forms ,&nbsp; ficando como a figura abaixo, no caso utilizei o template criado já que é apenas um exemplo, única coisa que fiz depois foi apagar a pasta “Account” e os arquivos “About.aspx” e “Contact.aspx”, utilizando apenas a “Default.aspx” e editei a master page, “Site.Master”.





Depois adicionei um novo projeto a solução, com o nome de Util, é ai que vamos codificar as classes para fazer a leitura de um RSS Feed.





Escolhemos então o tipo de projeto, escolhi uma Class Library, que irá criar uma dll que será utilizado como referencia no projeto web.



&nbsp;
O VS 2012 por default cria uma classe Class1 que não iremos utilizar.

Então criaremos duas classes, a classe Feed e a classe RssReader.&nbsp; A classe Feed será o objeto que será criado a partir da leitura do RSS, para cada item do XML será criado um feed e adicionado em uma lista. Já o RssReader será responsável por ler o endereço e preencher essa lista. 
&nbsp; 







Classe Feednamespace Util{&nbsp;&nbsp;&nbsp; /// 
&nbsp;&nbsp;&nbsp; /// Class Feed&nbsp;&nbsp;&nbsp; /// &nbsp;&nbsp;&nbsp; public class Feed&nbsp;&nbsp;&nbsp; {&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; #region Property&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; public string Titulo { get; set; }&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; public string Descricao { get; set; }&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; public string Link { get; set; }&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; #endregion Property&nbsp;&nbsp;&nbsp; }}Classe RssReaderusing System;using System.Collections.Generic;using System.Xml;namespace Util{&nbsp;&nbsp;&nbsp; /// &nbsp;&nbsp;&nbsp; /// Class RssFeed&nbsp;&nbsp;&nbsp; /// &nbsp;&nbsp;&nbsp; public class RssReader&nbsp;&nbsp;&nbsp; {&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; #region Private properties&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; private string url;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; private XmlTextReader rssReader;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; private XmlDocument rssDoc;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; private XmlNode nodeRss;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; private XmlNode nodeChannel;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; private XmlNode nodeItem;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; #endregion Private properties&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; /// &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; /// Constructor&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; /// &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; /// url do feed&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; public RssReader(string url)&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; {&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; this.url = url;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; /// &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; /// Return feeds&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; /// &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; /// &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; public IList RetornaFeeds()&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; {&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; IList listRetorno = new List();&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; if (string.IsNullOrEmpty(this.url))&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; {&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; throw new Exception("A url não pode ser vazia!");&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; else&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; {&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; rssReader = new XmlTextReader(this.url);&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; rssDoc = new XmlDocument();&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; rssDoc.Load(rssReader);&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; // Loop for the rss tag&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; for (int i = 0; i &lt; rssDoc.ChildNodes.Count; i++)&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; {&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; // If it is the rss tag&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; if (rssDoc.ChildNodes[i].Name == "rss")&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&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nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; if (nodeRss.ChildNodes[i].Name == "channel")&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; {&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; // channel tag found&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; nodeChannel = nodeRss.ChildNodes[i];&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; // Loop for the title, link, description and all the other tags&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; for (int i = 0; i &lt; nodeChannel.ChildNodes.Count; i++)&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; {&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; // If it is the item tag, then it has children tags which we will add as items to the List&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; if (nodeChannel.ChildNodes[i].Name == "item")&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; {&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; nodeItem = nodeChannel.ChildNodes[i];&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; // Create a item to the List containing information from inside the nodes&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Feed feed = new Feed();&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; feed.Titulo = nodeItem["title"].InnerText;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; feed.Link = nodeItem["link"].InnerText;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; feed.Descricao = nodeItem["description"].InnerText;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; listRetorno.Add(feed);&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; return listRetorno;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }&nbsp;&nbsp;&nbsp; }}Agora vamos para o projeto web, é lá que iremos fazer a chamada que fará a leitura do RSS Feed.Primeiramente, vamos criar um Text Box e um Button para poder ler o endereço e carregar as informações de um feed.


Agora vamos adicionar um GridView onde serão carregadas as informações,&nbsp; após o clique no botão carregar.No GridView vamos adicionar um Hyperlink Field, clique no grid e depois escolha “Edit Columns...”&nbsp; e escolha a opção “HyperLinkField” e clique em “Add”. Nomeie a propriedade “HeaderText”&nbsp; para “Rss Feed” que como nome já diz será o nome do cabeçalho da coluna. 


Ainda na mesma tela na propriedade "NavigateUrl" coloque Link, essa propriedade virá da lista de objeto que será o DataSource do grid, essa lista será populada com objeto do tipo Feed, que foi criada anteriormente no projeto Util.&nbsp; E na propriedade “DataTextField” será colocado a propriedade Titulo, que também virá da lista de objetos do tipo Feed.&nbsp;


Agora vamos codificar a ação do botão, é ai que vamos chamar o método que responsável por popular o grid com as informações. Na página “Default.aspx” iremos dar um duplo clique no botão “Carregar...”, ele irá nos jogar para a tela onde iremos codificar (Code-Behind) &nbsp;



Antes de colocar o trecho de código com a chamada do método, devemos fazer a referencia ao projeto Util, para podermos utilizar as classes criadas.Para adicionar é muito simples, basta clicar com o botão direito no projeto RssReader, e escolher a opção “Add reference...”&nbsp;

Escolha a opção&nbsp; “Solution” e em seguida escolha o projeto Util&nbsp;

Então colocamos o seguinte trecho de código:protected void btnOk_Click(object sender, EventArgs e)
{&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; try&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; {&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; //set the object&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Util.RssReader readerFeed = new Util.RssReader(txtUrl.Text);&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; //load url&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; GridView1.DataSource = readerFeed.RetornaFeeds();&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; GridView1.DataBind();&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; catch (Exception ex)&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; {&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Page.ClientScript.RegisterStartupScript(this.GetType(), "Alert", &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; "alert('" + ex.Message + "');", true);&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }&nbsp;}
Depois, é só executar e está pronto!&nbsp;


&nbsp;



Podem ter certeza, demorei muito mais tempo fazendo o tutorial do que a solução em si! Espero ter ajudado e quaisquer dúvidas podem falar, caso eu não saiba responder ai procuro a resposta!


Link com a solution - RssReader.zipAbraços! :)