Archive for November 2008

C# Xml database

I was thinking I needed a small footprint database the other day when coding a small app. If you need something to save small amount of data you can just serialize it to Xml file and back. There is your little database. Obviously not very usable for heavy load, but with a small amount of data it works just fine. There is not much involved lets take a look.

public class Car
    {
        public string Model = string.Empty;
        public int Year = 0;
        //
        public Car() {}
    }

        /// Reads car objects from xml file
        public static List<Car> readXML()
        {
            // Trap
            if (!File.Exists(XML_FILE)) return new List<Car>();

            // Deserialize, load from XML
            FileStream fs = new FileStream(XML_FILE, FileMode.Open);
            XmlReader reader = new XmlTextReader(fs);
            XmlSerializer ser = new XmlSerializer(typeof(List<Car>));
            List<Car> myList = (List<Car>)ser.Deserialize(reader);
            fs.Close();
            //
            return myList;
        }

        /// Writes car objects to xml file
        public static void writeXML(List<Car> plStocks)
        {
            // Now create the Xml
            XmlSerializer s = new XmlSerializer(typeof(List<Car>));
            TextWriter writer = new StreamWriter(XML_FILE);
            // Serializes the objects in list
            s.Serialize(writer, plStocks);
            // done, close the file
            writer.Close();
        }

Syncfusion browser control put to bed

I have replaced the old Syncfusion browser control with a FREE Firefox / Mozilla control, it works quite well, it is an ActiveX control.  Because of us needing to be 508 compliant I had to add a few properties, with a wrapper.  Not a big deal the old control was already wrapped anyway. After that the software program used by our blind users can read and speak the content of the control to the user.

ListView sort C#

If you need to sort using the ListView control it is straight forward. But what about leaving some of the rows out of the sort. For example if you need a total row in the end. Obviously you don’t want that last one as a part of the sort routine. Simply add to the ListViewItem.Tag a string something like DONT_SORT and look for that in the comparer.

public int Compare(object x, object y)
{
            int compareResult;
            ListViewItem listviewX, listviewY;

            // Cast the objects to be compared to ListViewItem objects
            listviewX = (ListViewItem)x;
            listviewY = (ListViewItem)y;

            // Don’t sort on requested tags
            if (listviewX.Tag.ToString().Equals(DONT_SORT))
                return compareResult = 1;
            if (listviewY.Tag.ToString().Equals(DONT_SORT)
                return compareResult = –1;

Json in C#

I did some Json work in C#, I hadn’t done any Json with C# before.  Naturally I go googling without much luck at first.  When you look for Json libraries and code snippets they are plentiful, but most of them java script browser stuff.  Then a friend pointed out Jayrock which was exactly what I needed.  It can be used in C# code to address Json feed similar to Xml feeds.

As mentioned before json is extremely java script friendly.  Let’s take a look at one of the Google examples.

<h3>Upcoming Google Developer Events</h3>
<div id=“agenda”></div>
<script>
  function listEvents(root) {
    var feed = root.feed;
    var entries = feed.entry || [];
    var html = [‘<ul>’];

    for (var i = 0; i < entries.length; ++i) {
      var entry = entries[i];
      var title = entry.title.$t;
      var start = (entry[‘gd$when’]) ? entry[‘gd$when’][0].startTime : “”;     
      html.push(‘<li>’, start, ‘ – ‘, title, ‘</li>’);
    }
    html.push(‘</ul>’);
    document.getElementById(“agenda”).innerHTML = html.join(“”);
  }
</script>

<script src=“http://www.google.com/calendar/feeds/developer-calendar@google.com/public/full?alt=json-in-script&callback=listEvents”>
</script>

Run the sample.

And then in C# using Jayrock

using Jayrock.Json;

WebClient client = new WebClient();
Uri url = new Uri(“http://www.google.com/calendar/feeds/developer-calendar@google.com/public/full?alt=json”);
string gevents= client.DownloadString(url);

using (JsonTextReader reader = new JsonTextReader(new StringReader(gevents)))
{

    while (reader.Read())
    {
        if (reader.Depth == 4 &&
            reader.TokenClass == JsonTokenClass.Member &&
            reader.Text != null )
        {
            if (reader.Text.Equals(“gd$when”))
            {
                // navigate to the right node
                for( int i = 0; i < 6; i++)
                    reader.Read();
               
                // startTime
                Console.WriteLine(reader.ReadString());
            }
            else if (reader.Text.Equals(“title”))
            {
                // navigate to the right node
                for (int i = 0; i < 5; i++)
                    reader.Read();

                // $t
                Console.WriteLine(reader.ReadString());
            }
        }
    }
}

Those for loops are a bit ugly to get down the tree to the correct node. There has to be a better way of doing that. With simple data pairs it’s no problem but with heavier feeds like the one I took in the sample it’s not as obvious. If you have a simpler or more elegant way of doing it in C# drop a comment.

This is what the Json feed looks like.

Here are some tools, that I came up on JsonViewer which is hosted on CodePlex. The viewer also comes with a plugin for Fiddler, which is really handy and also has one for VS. Fiddler is a http debugging proxy. CodePlex is Microsoft’s answer to sourceforge.

You can find extensive list of json libraries here, for bunch of different languages.

Akismet plugin

I have been running this blog without any spam filter.  Let me tell you it was a big mistake.  I just updated the wordpress version I’m running.  Since I was doing the housekeeping I thought maybe I should also activate the Akismet plugin.  Pretty much the Akismet plugin will catch all the spam comments.  Similar to email spam filters, it works great.  I should have activated it day 1.

Another nice geeky thing, if your running Ms media center instead of Tivo, do yourself a favor and install McBuddy.  It can cut those commercials out for you so you don’t need to fast forward when watching your fav shows.

Cutting edge website

Three friends and I started a company in Iceland back in ’94.  We were pretty much fresh out of the University.  We did odd projects here and there as young companies go.

Then we came up with this brilliant idea, to make a website for the world championship in team handball.  That was to be held in Reykjavik in 1995.  There wasn’t much of dynamic web sites at the time, they sure existed not the norm though.  After striking a deal with the handball association the work begun.  The website even had an Oracle database on the back end for dynamic content.  Mostly to look up teams, players and game stats as the tournament took place.  Not only that it was also available both in Icelandic and English.

Like I said cutting edge in 1995, we even got published in the newspaper and Tv stations.  We had just started development when I had to move to New York to secure my green card.