M'he animat i he posat RSS al blog, ja que també m'ho han demanat. Doncs dit i fet. El cas és que tampoc és gaire difícil fer-ho. Hi ha unes classes de .NET SyndicationFeed, que ho fan fàcil. Cal fer un ASHX i posar el "using System.ServiceModel.Syndication;", després un parell de bucles, es recupera de la BBDD amb la clsDades els posts i voilà. Com sempre el codi.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ServiceModel.Syndication;
using System.IO;
using System.Xml;
using System.Data;
using Blog.data;
namespace Blog
{
public class RSS : IHttpHandler
{
private clsConfig Conf = new clsConfig();
private string ConnStr = "";
public void ProcessRequest(HttpContext context)
{
Conf.Initialize();
ConnStr = Conf.GetVal("CadConn");
SyndicationFeed feed = CreateRecentPostsFeed();
var output = new StringWriter();
var writer = new XmlTextWriter(output);
new Rss20FeedFormatter(feed).WriteTo(writer);
context.Response.ContentType = "application/rss+xml";
context.Response.Write(output.ToString());
}
private SyndicationFeed CreateRecentPostsFeed()
{
List<SyndicationItem> syndicationItems = GetPostsRecents();
return new SyndicationFeed(syndicationItems)
{
Title = new TextSyndicationContent("Blog"),
Description = new TextSyndicationContent("Una mica de tot i a vegades més"),
ImageUrl = new Uri("http://blog.canalda.net/Img/laughing_man_p.jpg")
};
}
private List<SyndicationItem> GetPostsRecents()
{
List<SyndicationItem> Posts = new List<SyndicationItem>();
clsPosts PostsTA = new clsPosts(ConnStr);
Dictionary<string, string> Params = new Dictionary<string, string>();
DateTime FPubs = DateTime.Now;
DataTable PostsTBL;
FPubs = FPubs.Subtract(TimeSpan.FromDays(7));
Params.Add("DataPubMesGran", PostsTA.DateTimeToSQL(FPubs, "0"));
Params.Add("Actiu", "true");
PostsTBL = PostsTA.GET(Params);
foreach (DataRow Post in PostsTBL.Rows)
{
Posts.Add(GeneraSyndicacioPost(Post));
}
return Posts;
}
private SyndicationItem GeneraSyndicacioPost(DataRow DR)
{
string id = DR["IdPost"].ToString();
string title = String.Format("Post: {1}", id, DR["Titol"]);
string content = DR["PostText"].ToString();
DateTimeOffset DataPub = new DateTimeOffset((DateTime) DR["DataPub"]);
Uri url = new Uri(String.Format("http://blog.canalda.net/Post.aspx?IdPost={0}", id));
return new SyndicationItem(title, content, url, id, DataPub);
}
public bool IsReusable
{
get
{
return false;
}
}
}
}
|