New widget FMyLife

by Derek Pinkerton 3. July 2009 19:15

I just added my first new item to this site for your enjoyment. I created a new widget to display random entries from the FMyLife.com website. This widget was incredibly easy to create. FMyLife has an API that simply presents the data as XML. Using the .Net Framework's System.Xml namespace I was able to easily parse the XML data.

C#

private void Page_Load(object sender, EventArgs e)
{
    String FmlXml = GetWebPage("readonly&language=en">http://api.betacie.com/view/random?key=readonly&language=en");
    XmlDocument xDoc = new XmlDocument();
    xDoc.LoadXml(FmlXml);
    XmlNodeList xnl = xDoc.GetElementsByTagName("item");
    // we only want the details of the first one.
    if (xnl.Count > 0)
    {
        foreach (XmlNode node in xnl[0].ChildNodes)
        {
            if (node.Name == "text")
            {
               this.lblRecentFML.Text = node.InnerText;
             }
         }
    }
}

public static string GetWebPage(string Uri)
{
    StringBuilder sb = new StringBuilder();
    byte[] buf = new byte[8192];
    HttpWebRequest request = (HttpWebRequest) WebRequest.Create(Uri);
    HttpWebResponse response = (HttpWebResponse) request.GetResponse();
    Stream resStream = response.GetResponseStream();
    string tempString = null;
    int count = 0;
    do 
    {
        count = resStream.Read(buf, 0, buf.Length);
        if (count != 0)
        {
            tempString = Encoding.ASCII.GetString(buf, 0, count);
            sb.Append(tempString);
        }
    } while (count > 0);
    return sb.ToString();
}

Be sure to add using statements for both System.Xml and System.Net.

You can also download the widget here:

FMyLife.zip (3.54 kb) Simply download and unzip into the widgets folder.

Tags: , ,

c#

Comments are closed