“Dotnet tips, SQL Server tips, Silverlight tips, AJAX tips...”
Read Experts reviews and compare prices to find the right desktop or laptop for you from the huge collection.
Learn LINQ To SQL and LINQ to XML by example
Simple, step by step, sample about how to generate an RSSFeed using LINQ and LINQ TO SQL in only five lines of code.
I wanted to start coding some LINQ stuff... something simple, and maybe a bit stupid, but something real: I decided to create an RSS file generator for my site.
Ok, I know that maybe there are professional tools, or whatever... but I had the opportunity of combining LINQ To SQL (To read from my DB), and LINQ To XML (to generate the XML output), ... realizing that I only need five lines of code to generate my feed using LINQ !!.
Let's start by defining the scenario:
Now let's define our Business need: in order to better promote our site we want to offer RSS Syndication, other sites or portals can read from our RSS XML file a summary of the articles / post available from our blog. The Feed that we are going to generate will have the following structure:
<?xml version="1.0" encoding="utf-8" standalone="yes"?> <rss version="2.0"> <channel> <title>Name of the site</title> <description>Description of the site.</description> <link>http://www.linktothesite.com</link> <item> <title>Title of the post</title> <link>http://linktothepost.com?ID=12</link> <pubDate>2007-11-24T08:12:24.323Z</pubDate> <description> short description of the post</description> </item> <item> ... Title / link / pubDate / Description ... </item> (...) Lot of items... (one per article/post) </channel> </rss>
What we have to implement: Read from the articles table all the entries (fields: title, pubDate and RSSDescription) , create an RSS XML feed and insert all the rows that we read from the DB in the XML RSS format
Let's start coding:
Create a new Visual Studio Console application project (File >> New Project):
Add a new item to the project, we are going to create a LINQ DBML item (let's name it SampleDB):
On the Server Explorer >> add a connection to our SQL Server database. Double click over the new LINQ DBML item created and drop a table from the database connections:
Click on the items and rename the fields to a more friendly ones (we are using an entity, no need to keep horrible database name with prefix), and remove the fields that you are not going to use.
Save and close the DBML.
(*) Note down that the connectionstring is stored in a non secure way in your DBML file, you choose to use integrated security, or not to store user and password, and in your code point to the right connection string using the property of the data context: db.Connection.ConnectionString.
Before start coding let's ensure that we have all the references needed to use LINQ and LINQ XML:
and all the "using" in the cs file:
using System; using System.Collections.Generic; using System.Linq; using System.Xml.Linq; using System.Text;
Now let's instantiate a DBContext associated to that DBML, and let's read all the entries that we need:
// Instantiate the SampleDBDataContext (from previously dbml created). SampleDBDataContext db = new SampleDBDataContext(); // Let's assume that our site use http://www.mysite.com/Article.aspx?ID=99 string blogURLENG = "http://www.mysite.com/Article.aspx?BLID={0}"; // First create all the items node, we will have a substructure like (a collection // of items, one per article/post): // // <item> // <title>Title of the post</title> // <link>http://www.mysite.com?ID=12</link> // <pubDate>2007-11-24T08:12:24.323Z</pubDate> // <description> short description of the post</description> // </item> var articlesEntries = from p in db.BlogEntries orderby p.EntryDate select new XElement("item", new XElement("title", p.Title), new XElement("link", string.Format(blogURLENG, p.ID)), new XElement("pubDate", p.EntryDate.ToUniversalTime()), new XElement("description", p.RSSDescription) );
Here I execute a select (using LINQ sintax) retrieve the fields that I need, and encapsulate it in an XElement structure (bunch of XML, with the RSS Item structure). As you can see, I don't want to bother about what type of list is returning me the query, I know that is a list and that it implements the IEnumerable interface, I just declare the variable using "var" and forget about the concrete type.
Let's create the whole XML structure, and inject the articles chunk of XML that we generated in the previous line of code:
// Now let's fit the items subtree in the whole XML Document: // // <?xml version="1.0" encoding="utf-8" standalone="yes"?> // <rss version="2.0"> // <channel> // <title>Name of the site</title> // <description>Description of the site.</description> // <link>http://www.mysite.com</link> // <item> // ...Article post info, previously created // </item> // (...) Lot of items... (one per article/post) // </channel> // // As you can see we can create in the same constructor the declaration, single // hardcoded elments (channel), and inside them a list of elements to hang from // then channel XDocument doc = new XDocument( new XDeclaration("1.0", "utf-8", "yes"), new XElement("rss", new XAttribute("version", "2.0"), new XElement("channel", new XElement("title", "RSS My Sample site"), new XElement("description", "Sample Description for mysite.com."), new XElement("link", "http://www.mysite.com"), articlesEntries ) ) );
Quite amazing isn't it? We just define the Document, main elements and start nesting other XElement containing parent nodes, or even list of nodes to insert !!
Next step just save the generated document...
// Save the resulting XML into a file doc.Save(@"rss.xml");
As I said in the beginning you get a simple RSS generator just with five lines of code !!!