Sunday, September 28, 2014

Creating RSS Feeds using Repeater Control

RSS Feeds are XML Formatted documents  using which updated data can be read from different website without actually visiting it.

To create a rss feed in asp.net all we need is to follow following steps:-
1)Create New Website in Visual Studio.
2)In WebForm Drag a Repeater Control.
3)In the Page Directive add ContentType="text/xml".

Feeds.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Feeds.aspx.cs" Inherits="_Default" %>
<asp:Repeater id="rptFeeds" runat="server" onitemdatabound="rptFeeds_ItemDataBound" >
<HeaderTemplate>
<rss version="2.0">
  <channel>
    <title>Test Feeds</title>
    <description></description>   
    <copyright></copyright>  
</HeaderTemplate>
<ItemTemplate>
  <blog>
    <title><%# Eval("Blog_Title")%></title>
<url><%# Eval("Blog_Url")%></url>
    <date><%# Eval("Blog_date")%></date>   
   
    <description><%# Eval("Blog_Description")%></description>
  </blog>
</ItemTemplate>
<FooterTemplate>
<asp:Literal ID="ltlEmpty" runat="server" Visible="false" ></asp:Literal>
  </channel>
</rss>   
</FooterTemplate>
</asp:Repeater>

Now in code behind file we will get data from database and bind the repeater.
Feeds.aspx.cs
public partial class Feeds : System.Web.UI.Page
    {
        SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["blogConnection"].ConnectionString);
      
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            { feedsbind(); }
        }
        protected void feedsbind()
        {
            SqlCommand cmd = new SqlCommand("Select * from Blogs", conn);
            SqlDataAdapter da = new SqlDataAdapter(cmd);
            DataSet ds = new DataSet();
            da.Fill(ds);
            rptFeeds.DataSource = ds;
            rptFeeds.DataBind();
        }

protected void rptFeeds_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {

            if (e.Item.ItemType == ListItemType.Footer)
            {
if(rptFeeds.Items.Count==0)
{
                Literal ltlEmpty= (Literal)(e.Item.FindControl("ltlEmpty"));
                ltlEmpty.Text="No Blogs Found.";
ltlEmpty.Visible=true;
               }
            }
        }
    }

Note:- Above i have used Literal instead of label since Label will generate HTML ,but we only need to show plain text.