Tag: csharp

rss 2.0 feed format tutorial for .NET

Posted by – August 22, 2007

I have been creating custom blog software using csharp.net. One task that I accomplished today was getting both an RSS and an ATOM feed setup. This will allow people to read the blog on sites like netvibes, my yahoo, or google IG. So heres how I did it:

  1. Change the content type of the page to text/xml

    This is needed so that other computers and browsers will know that it is an XML page they are reading, and not the standard HTML. Luckily this is simple to do, simply add ContentType=”text/xml” to the Page directive, like so:

    
    <%@ Page Language="C#" AutoEventWireup="true" CodeFile="rss.aspx.cs" Inherits="rss" ContentType="text/xml"%>
    
  2. Setup RSS 2.0 XML Document

    Now in our code behind file, we can write directly to the output stream, as the proper header is already set. You may think about using Response.Write to create the RSS XML tags, but there is a much easier way. You can use an XmlTextWriter to achieve the same result, without needing to escape all characters that can’t normally be in an xml file

    
            // Create a new XmlTextWriter instance
            XmlTextWriter writer = new XmlTextWriter(Response.OutputStream, Encoding.UTF8);
    
            // Create Document
            writer.WriteStartDocument();
                writer.WriteStartElement("rss");
                writer.WriteAttributeString("version", "2.0");
                    //Set Channel Information
                    writer.WriteStartElement("channel");
                        writer.WriteElementString("title","[SITE_TITLE]");
                        writer.WriteElementString("link",[SITE_URL]);
                        writer.WriteElementString("description",[SITE DESCRIPTION]);
                        writer.WriteElementString("lastBuildDate",[RFC-822 DATE]);
    

    Here we setup the start of the XML document with all required fields. The lastBuildDate element should be the last time the xml feed has changed, which should also be the last time something new was posted.

  3. Output Post information

    The standard is to display them in reverse chronological order. Most likely you will be creating these in a loop, like so:

    
    for (int i = 0; i < postList.Count; i++)
    {
    
        writer.WriteStartElement("item");
            writer.WriteElementString("title",postList[i].pageTitle);
            writer.WriteElementString("link", postList[i].url);
            writer.WriteElementString("description", postList[i].content);
            writer.WriteElementString("pubDate", postList[i].postDate);
            writer.WriteElementString("guid", postList[i].url);
        writer.WriteEndElement();
    }
    

    Here I am assuming postList is a list of object containing post information. The pubDate tag is the date that the post was published, and guid is a globally unique identifier for the post. If you have a GUID setup in the database for the post you can use it, otherwise it's easiest to just use the permalink (url).

  4. Close Document

    Now that we have displayed all relevant information, we simply need to close open tags, and end the xml document

    
                    writer.WriteEndElement();
                writer.WriteEndElement();
            writer.WriteEndDocument();
    writer.Close();    
    

    Thats all there is to it. You can now use this page to submit to sites such as netvibes, google ig, my yahoo, or any other services that will parse rss 2.0 xml feeds.

CSharp Blog ping code using xml-rpc and weblogupdates.ping for Pingomatic, Technorati

Posted by – August 1, 2007

I am currently writing a custom blog application in csharp.net (c#.net). One requirement for the software was that it needed to send update information to sites like Technorati or Ping-o-matic. After some research, I’ve found that sites allow you to do this utilizing xml-rpc. The process is called pingback, but it more commenly refered to as simply pinging. Basically every time you write a new post, you can ping these services to tell them you have updated content, and let people know about it.

The specific method we want to access via xml-rpc is called “weblogUpdates.ping”. This function is implemented on all blog ping services. Below is a function which defines a list of sites to ping, then goes through and pings them one by one. It takes as parameters the name of your site, and the url of your site.


private void sendPing(String name, String url)
{
ArrayList listToPing = new ArrayList();
listToPing.Add("http://rpc.technorati.com/rpc/ping");
listToPing.Add("http://rpc.pingomatic.com");
listToPing.Add("http://blogsearch.google.com/ping/RPC2");

for (int i = 0; i < listToPing.Count; i++)
{
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(listToPing[i].ToString());
    request.Method = "POST";
    request.ContentType = "text/xml";

    Stream stream = (Stream)request.GetRequestStream();

    using (XmlTextWriter xml = new XmlTextWriter(stream, Encoding.UTF8))
    {
        xml.WriteStartDocument();
        xml.WriteStartElement("methodCall");
        xml.WriteElementString("methodName", "weblogUpdates.ping");
        xml.WriteStartElement("params");
        xml.WriteStartElement("param");
        xml.WriteElementString("value", name);
        xml.WriteEndElement();
        xml.WriteStartElement("param");
        xml.WriteElementString("value", url);
        xml.WriteEndElement();
        xml.WriteEndElement();
        xml.WriteEndElement();
        xml.Close();
    }

    using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
    {
        using (StreamReader sr = new StreamReader(response.GetResponseStream()))
        {
            string result = sr.ReadToEnd();
            sr.Close();
        }
        response.Close();
    }
}

The Dictionary Object: similar to PHP arrays.

Posted by – July 25, 2007

In a previous post entitled Associative Arrays in VB.NET I spoke of using a Collection Object to achieve similar functionality to associative arrays in PHP. Upon further inspection, I feel that the System.Collections.Generic.Dictionary Object (hereafter written as Dictionary Object) is a closer match.

The reason I initially chose to write about the Collection Object is because the Dictionary Object requires all keys to be of the same type, and all values to be of the same type. Of course .NET (both VB.NET and CSharp.NET) is a strongly typed language, whereas PHP is not.

The main advantage a Dictionary has over a regular Collection, is that you can edit items. It also provides a syntax to add items which is similar to that of PHP.

The first step is to add the System.Collections.Generic library to your file, with the following directive:

CSharp.NET


using System.Collections.Generic;

VB.NET


imports System.Collections.Generic

Then you can declare the Dictionary Object:
CSharp.NET


<%
        Dictionary dict = new Dictionary();
        dict["one"] = "First Item";
        dict["two"] = "Second Item";
        dict["one"] = "Look, I just edited the first Item!";
%>

VB.NET


<%
        Dim dict As Dictionary(Of String, String) = New Dictionary(Of String, String)
        dict("one") = "First Item"
        dict("two") = "Second Item"
        dict("one") = "Look, I just edited the first Item!"
%>

Look at that! Aside from the missing dollar sign in front of variables, this looks like PHP!

multiple line strings in C Sharp

Posted by – July 19, 2007

Today I found something that made my day. I have always hated that you can’t have strings span multiple lines of code in ASP.NET. For VB.NET this makes since, because there is no semi-colon at the end of statements. To get strings to span multiple lines in VB.NET, you can add an ampersand + space + underscore to the end of each line, like so:


dim sample as string = "notice how " & _
"the string is on multiple lines!" & _
"just make sure you put double quotes on the" & _
"beginning and end of each line"

This works for VB.NET, but not so for C#.NET. I have tried changing the ampersand to a plus sign (c sharp’s character to concatenate strings) but this didn’t work. I had assumed it was impossible, until I came across a solution today. Simply put an ‘at’ sign (@) before the string!


string sample = @"notice how
the string is on multiple lines!";

As you can see, in c-sharp.net you don’t need to start and stop the string like you do in vb.net. The only thing that is slightly tricky, is if you start concatenating strings. Then you need to add the @ symbol to every section of string that will be on multiple lines. For example:


string sample = @"this string
is on multiple lines" + someVariable + @" notice
how i had to use an 'at' symbol again, 
however i don't if the string section stays on one line, 
such as" + here + "... get it?";

Enjoy this ability to word-wrap you sql queries, or any other code strings which need to span multiple lines!

Dynamic Dropdownlist

Posted by – July 12, 2007

Came across a strange problem today. I was dynamically filling a dropdown list, and also was dynamically creating checkboxes from the database. Basically I have a list of options, and the user needs to select a primary choice (via dropdown) and then a bunch of alternates (via checkboxes). I assumed the best way to do this was:


CheckBoxList checkSet = new CheckBoxList();

ListItem leaf = new ListItem();
leaf.Text = categoryList[i].name;
leaf.Value = categoryList[i].categoryId.ToString();
checkSet.Items.Add(leaf);

//primaryCategory is the dropdownlist defined in aspx file
primaryCategory.Items.Add(leaf);

At first everything appeared great. However, when I tried to submit the form somtimes, i would get the following error:
Cannot have multiple items selected in a DropDownList. This confused me, because I wasn’t trying to set the selected value through code. After some digging, I realized they when I select the checkbox item and then post back the form, asp.net sees that the checkbox was selected before, so sets it’s “selected” property to ‘selected’. My code then adds the item to both the dropdown and checkbox list. However, the dropdown had a selected value of it’s own, and therefore I get the error.

The solution, although it seems odd, is to create two different items in code: one for the dropdownlist, and one for the checkbox.


CheckBoxList checkSet = new CheckBoxList();

//add to checkboxlist
ListItem leaf = new ListItem();
leaf.Text = categoryList[i].name;
leaf.Value = categoryList[i].categoryId.ToString();
checkSet.Items.Add(leaf);

//add to dropdownlist
leaf = new ListItem();
leaf.Text = categoryList[i].name;
leaf.Value = categoryList[i].categoryId.ToString();
primaryCategory.Items.Add(leaf);