#739 - Un HttpHandler per generare feed RSS

RSS è un formato di syndication che nella versione 2.0 ha raggiunto praticamente la popolarità assoluta.
Benchè ci siano molte classi di generazione di feed RSS, non tutte sono flessibili. Questa presentata in questo script è implementata come HttpHandler, quindi risulta facilmente installabile e personalizzabile, dato che agisce leggendo query e stringa di connessione direttamente dal web.config locale.
Per prima cosa è dunque necessario creare una class library all'interno della quale compilare questa classe:

using System;
using System.Web;
using System.Xml;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Text;

namespace ASPItalia
{
  public class RSSHandler:IHttpHandler
  {

    public void ProcessRequest(HttpContext ctx)
    {
      ctx.Response.ContentType = "text/xml";

      // creo un nuovo oggetto XmlTextWriter con output

      // sullo stream dell'oggetto Response

      XmlTextWriter writer = new XmlTextWriter(ctx.Response.OutputStream, Encoding.Default);

      writer.Formatting = Formatting.Indented;

      // aggiungo l'intestazione XML

      writer.WriteRaw("<?xml version=\"1.0\" encoding=\"iso-8859-1\"?>");

      // root

      writer.WriteStartElement("rss");
      writer.WriteAttributeString("version", "2.0");
      writer.WriteAttributeString("xmlns:dc", "http://purl.org/dc/elements/1.1/");

      // channel

      writer.WriteStartElement("channel");

      // info

      writer.WriteElementString("title", "Feed RSS");
      writer.WriteElementString("link", "http://www.aspitalia.com/");
      writer.WriteElementString("description", "descrizione");
      writer.WriteElementString("dc:language", "it-it");
      writer.WriteElementString("generator", "RSS Generated by ASPItalia.com");
      writer.WriteElementString("managingEditor", "Gestore(gestore@sito.ext)");
      writer.WriteElementString("webMaster", "Gestore(gestore@sito.ext)");
      writer.WriteElementString("copyright", "(C)");

      // leggo le info da web.config

      string sql = ConfigurationSettings.AppSettings["rssSql"] as String;
      string strconn = ConfigurationSettings.AppSettings["rssConnection"] as String;

      // estraggo i dati

      using (SqlConnection conn = new SqlConnection(strconn))
      {

        using (SqlCommand cmd = new SqlCommand(sql, conn))
        {
          conn.Open();
          SqlDataReader reader = cmd.ExecuteReader();

          // ciclo per inserire i dati nel feed

          while (reader.Read())
          {
            writer.WriteStartElement("item");
            writer.WriteElementString("title", ctx.Server.HtmlEncode(reader["titolo"].ToString()));
            writer.WriteElementString("link", reader["URL"].ToString());

            writer.WriteElementString("pubDate", Convert.ToDateTime(reader["data"]).ToString("r"));
            writer.WriteElementString("description", reader["description"].ToString());
            writer.WriteElementString("dc:creator", reader["autore"].ToString());
            writer.WriteElementString("comments", reader["URL"].ToString());
            writer.WriteElementString("guid", reader["URL"].ToString());

            writer.WriteEndElement();
          }
        }
      }

      // chiudo tag channel

      writer.WriteEndElement();

      // chiudo tag rss

      writer.WriteEndElement();

      // scrivo a video e chiudo lo stream

      writer.Flush();
      writer.Close();
    }

    public bool IsReusable
    {
      get
      {
        return true;
      }
    }
  }
}

Una volta ricavato l'assembly, andrà registrato nel web.config, insieme a due chiavi che andranno a contenere la query e la stringa di connessione:

<configuration>
  <appSettings>
    <add key="rssSql" value="SELECT 'http://sito/?title_id=' + title_id as Url, title, pubdate as date, notes as description, '' as author FROM titles" />
    <add key="rssConn" value="server=localhost;database=pubs;trusted_connection=true;" />
  </appSettings>

  <system.web>
    <httpHandlers>
      <add verb="*" path="rss.aspx" type="ASPItalia.RSSHandler,RSSHandler" />
    </httpHandlers>
  </system.web>
</configuration>

In questo esempio l'handler risponderà alle chiamate al file rss.aspx, estraendo i dati attraverso la query specificata.
E' utile notare che i nomi dei campi restituiti devono essere gli stessi utilizzati dalla classe e che questa limitazione si aggira facilmente utilizzando opportunamente gli alias all'interno della query.
Qualora si voglia avere feed RSS diversi, è sufficiente creare sottodirectory, piazzando all'interno di ciascuna questo web.config, ovviamente modificando la query.

Nota: Questo script contiene un allegato.


Approfondimenti

Commenti

Esprimi il tuo giudizio su questo script:

Per procedere devi essere autenticato.

maltra scrive:
#739 - Un HttpHanlder per generare feed RSS

chi mi puo' dare una mano, ho inserito il codice, ma nel web config non riesco a capire questa riga a cosa si rifrisce:
mercoledì 12 dicembre 2007 | 1 risposta
visfab scrive:
#739 - Un HttpHanlder per generare feed RSS

Chi mi può aiutare ... ho provato ad utilizzare questo codice ma nel momento in cui vado a generarlo con Visual Studio .Net 2003 ma da questi errori:(...
giovedì 27 luglio 2006 | 2 risposte

Aggiungi un nuovo commento »»»
Per inserire un commento, devi registrarti alla nostra community.




IN EVIDENZA
MISC