Tag Archives: C#


I was looking for dictionaries the other day after finding myself impressed by Ubuntu’s Dictionary program. I found out that it actually uses the gdict set of XML files, and you can find around the freedict site (you probably need to scroll down: look for Dict Databases (Webster’s 1913). The dictionary is in an awful XML format though. Sample Perl-code is provided too.

This is also where I found the WordNet lexical database for English language: a C# interface can be found at ebswif’s (GPL). Not cleanly written code, though, but if it strikes you fancy, the source might be with you. (WordNet files are binary files, though).

Dictionaries, huh? A good friend of mine had a theory that good programmers generally have a knack for math and language. I always thought there was some truth in that.


Alfons mentioned the ‘4400’ show, a series I’ve never heard of before. Apparently, it just started on its 4th season on USA Networks (I think it may be carried by NBC, not sure about this). There’s an extensive Wikipedia entry on the show and just like ‘Lost’, fans of the series have started a 4400 Wiki. I recognized one of the songs played during the pilot (you can watch episodes on the tv-links site [11/01/07: Defunct]): it was the theme song used for Stephen King’s ‘Kingdom Hospital’ (which was song/performed by the band Ivy [website]).

Earlier this week, someone pointed to the (video) site ‘I’m Cooked’, a site that allows users to upload videos of how to prepare their favourite recipes or meals. Actually, I think I got there via a MetaFilter link (right here). I was skeptical about the site but, apparently it’s popular.

Slightly related to above (relatively): I found this video about the double slit experiment and quantum theory. Informative, funny and clear.

And last but not least: I found an excellent series of articles about generics, graphs, datastructures and binary trees in C#. If you forgot about these elementary programming parts, now is a good time to refresh your mind.

Hey, hey.

Today, I discovered that the StringReaders/Writers in .Net only support UTF-16 encoding, which may lead to some breakage if you’re using it in combination with the XMLSerializer object.

If you really need to maintain UTF-8 compatibility, you should use a MemoryStream. This is actually just as simple as using a StringReader:

  MemoryStream m = new MemoryStream();
    XmlSerializer formatter = 
        new XmlSerializer(typeof(TMakeUpYourMind));
    formatter.Serialize(m, this);
    m.Seek(0, 0);
    StreamReader rd = new StreamReader(m);
      res = rd.ReadToEnd();

Don’t forget to ‘rewind’ the stream to position 0.

I’m not sure why this isn’t mentioned in the SDK. Also note to the Visual Studio Express developers: please make this weekly ‘registration of Visual Studio Express’ on my computer stop. I’m sure it’s a bug because everytime I register I get the same e-mail in with the same deals. I’ve already got 12 of them. Please.


While working on billing software, I was planning to write something on visual inheritance in Visual Studio Express (C#): this feature is ‘amiss’ in the lower end versions of that programming environment. I decided not to because the concept is simple (and natural for all object-orientated languages). I like the way how it is implemented in Delphi, naturally, where all forms that work as your base class are stored in a central repository so that they can be reused for other applications as well.

Earlier we saw ‘Babel’ (2006), which I can only describe as ‘a complex story with a happy end’. I thought the end part was surprising, were the viewer finds out that that single phone actually happens in the past. The movie is rated R (nudity, violence and some drug use) by the MPAA.

I read that the bald eagle is soaring in the US. I’m not sure if I mentioned it here before, but there’s a pair of bald eagles living around Middle Stewiacke. I thought this was ironic (More on bald eagles in Nova Scotia).

And last but not least, I ran into one of those ‘ErrorSafe’ popups (it wasn’t stopped by FireFox). If you run across it, the (general) advice is to pull the plug of your ethernet before it starts downloading. In my case it didn’t make the download but if it did, Symantec has a page describing how to remove the program manually. (ErrorSafe was sighted around about.com). I used fandro to verify recently changed or created files.

That, SerialPort stuff

The log files reveal that a lot of people are looking for help using the Serialport component of the .Net Framework. Once again, lets summarize:

  • There are two ways to access data from a serialport:
    1. Using the DataReceived event (non-blocking)
    2. Using (individual) ReadLine statements in your code (blocking)
    For a more detailed description, I mentioned the difference in a different posting. Which method you’re going to use depends on how or when data becomes available to you and where you want that data to appear in your application. If your GUI needs to be updated frequently, use non-blocking. Note that you can mix ReadLine statements in your DataReceived events, but most likely you will need to clear your serial port buffers before closing off the program.
  • Know the difference between the various way of reading data (Read, ReadLine and ReadExisting). Experiment with them.
  • If you need to read a certain amount of bytes, check into the BytesToRead property.
  • If you’re going to use blocking methods, make sure to adjust both read and write timeouts appropriately.

More cards

Since A bunch of cardsthe weather was bad yesterday and (it appears) it’s going to be same-o-same-o today, I decided to check into (this last month’s) Card objects project. All earlier created objects were ‘non-visual’ objects and since we’re playing cards, it probably makes sense to create a couple of visual components that show the player’s hands.

I decided to base my custom component on the PictureBox control, mainly because I’m not concerned about using specific drag and drop effects at this stage. If you make a descendant of the PictureBox and plan to do some custom drawing, you should override the PictureBox’s OnPaint event:

Continue reading

SerialPort and C#

What you need to know before you plan to work on Serial port communication:

0. Create a good test environment. You may need com0com (earlier) which can simulate a loopback between 2 ports.

1. Carefully choose between non-blocking and blocking. You save yourself a lot of pain when you thought using non-blocking was going to make work a lot easier. If you’re not familiar with the blocking vs. non-blocking approach, consider the table below the fold. (More on blocking vs. non-blocking). Holy wars have been fought between proponents of either form.

2. While doing your serial port stuff, also note that ReadLine has a BLOCKING nature. This is not mentioned in the original FrameWork SDK help files, but yes, it is mentioned in the SDK online. There’s no problem using ReadLine in your OnDataReceived event, but you must clear the port’s/socket buffer first before you can close your port/application (you’ll get specific errors).

3. There is no 4.

Continue reading


I added a minor project to the ‘Current Project’ section (Right here), a program in C# that generates classes based on table meta-data. It’s simple and it works: there are a couple of tricks how to collect metadata from ODBC datasources.

Currently, I used ‘hardcoded’ datatype conversion (SQL_xxx -> Dot.Net type): I was in a rush and decided to (conveniently) forget about using reflection. That said, I keep forgetting about my linefeeds [sorry], but then, your Visual Studio formats everything nicely out anyway.

This reminds me that I’ve downloaded ‘Orcas’ yesterday, Microsoft’s CTP of the new Visual Studio IDE. It comes with a visual ‘class designer’ that allows you to create classes from tables like the generator above does, but obviously (at this stage) that feature only supports the typical MS-like database interfaces. Not much of a help if you work in other environments. The only interesting items are the new C#/.Net language extensions, like LINQ and XAML. And yes, the Dev Team finally decided to add a Compile to Target feature, which allows you to compile and link your executables with other .Net Frameworks.



For something completely unrelated, I decided to check into my older Delphi code and noticed the ‘remnants’ of the code that actually started as a framework for a (basic) Spades1 card game. So hey: the code was actually so readable that most of it was easily turned into a C# version (that is minus the bidding code).

The fun part of it all was the ease of sorting in C#. Actually, you still need to write code to get that going, but compared to the things I needed to get a hand sorted in Delphi, that can be a different story (it’s actually not too bad either if you use regular TLists and that):

First of all make your base object descend from the IComparable class. This means, you’ll have to add a CompareTo method to your base object

 public class TCard : IComparable
        private TFaceValue ffacevalue;
        private bool ffaceup = false;
        private TSuit fsuit;
        // Code removed for brevity reasons...

        public int CalcValue
            get { return NumericValue(); }

        public int CompareTo(TCard acard)
            return this.CalcValue.CompareTo(acard.CalcValue);

Then create a class based on IComparer:

    public class THandComparer : IComparer
        private TSortOptions fsort = TSortOptions.Ascending;

        public TSortOptions SortOption
            get { return fsort; }
            set { fsort = value; }

        public int Compare(TCard x, TCard y)
            if (fsort == TSortOptions.Ascending)
                return x.CompareTo(y);
                return y.CompareTo(x);

I decided to give the player an option to sort the cards descending or ascending based on the combination of suit and card value: Notice that for descending order, you literally just switch the objects (the base CompareTo method returns -1, 0 or 1!)

And then in the THand Class:

        // [....]
        public void Sort()
            THandComparer fcomparer = new THandComparer();
            fcomparer.SortOption = forder;


What rest are the drawing procedures, the card faces (I should have a couple of sets somewhere on my source backup disks) and the bidding engine.

1 I find it amazing that Pagat once again serves as a reference for card games, just like it used to do back in 2000.


I read that A genuine garbage collectorJohn Backus died at age of 82 (Slashdot discussion), who happened to be the person who apparently led the team of developers that brought us FORTRAN.

I recalled his name because I was studying some BNF notations of several languages (described in this post). If you’re not sure what BNF is, well, try Wikipedia again.

There’s an interesting (and hilarious) quote from Backus:

“Much of my work has come from being lazy. I didn’t like writing programs, and so, when I was working on the IBM 701, writing programs for computing missile trajectories, I started work on a programming system to make it easier to write programs for the 701.”

I hear productivity went up after his crack team of developers released the first version of FORTRAN. Which reminds me that a good developer is lazy in the sense of ‘why do things manually, if I can write a program to make that problem go away faster’. This also reminds me of the way how easy it is to create objects in C# without even thinking of properly disposing them because, well, the garbage collector does that automatically for you (or I should say, this applies to any language that uses a garbage collector). It almost makes me long to Delphi, just to feel less lazy.

Or maybe, I mean, less helpless: I mean, these objects, can I please make them dispose?


The Tech, The Science and Space

For no New Horizon’s Flybyreason I was earlier up than normal, today: with the extra time I had I looked into several compiler-compilers (or parsers/scanners) targetting C#. I ran into a couple of ones: First of all there’s ANTLER (Public Domain, needs runtime). Secondly, there’s GOLD (written in VB, Freeware, needs runtime), which can output to multiple programming languages, including C#, ADA and Java. And there’s COCO/R (other link), a system I’m actually familiar with, if I just can find those earlier experiments.

The hunt for the Higgs Boson is almost on: Today, a milestone was reached in the construction of the LHC, as the BBC reports (reporter’s impression). Cern has a report too.

Two flybys made it in the news: First ESA’s Rosetta made it past Mars (News in chronological order: 1, 2, 3) and shot some pretty images. And then, just today, NASA’s ‘New Horizon’s’ probe flew by Jupiter and sent back imagery from Jupiter and some of its moons (news at NASA, fly by trajectory).


One point with which I want to close off for today: Ownerdraw stuff in C#. Yesterday, I was comparing code to create owner-draw listboxes and comboboxes in both Delphi and C# and noticed how remarkably easy it’s to switch from Delphi to C#: if you did this in Delphi before, the procedure is almost the same in C# (once again this is not surprising if you know who designed C#, earlier at xsamplex)

In Delphi for example, most VCL components have an ‘ownerdraw’ property: switching this one to either true (or to a specific enumerated value like ‘Ownerdrawfixed’), you generally capture two events to draw (and colour) individual items. The same is true for C#: you set the DrawMode property either to ‘OwnerDrawFixed’ or ‘OwnerDrawVariable’. Which one you choose depends on what you plan to do with the listbox.

As mentioned earlier, code to actually draw an item is done in an event: for this C# has the DrawItem event. I’m not going to explain the code, because it should speak for itself.

private void cboDataSources_DrawItem(object sender, DrawItemEventArgs e)

    if (e.Index > -1)
        TDataSourceType nt = 
           (cboDataSources.Items[e.Index] as TDataSource).SourceType;

        // Background first!

        if (nt == TDataSourceType.System)
            // Draw image from image list...
            imlSources.Draw(e.Graphics, e.Bounds.X, e.Bounds.Y + 1, 0);
                e.Font, Brushes.Black, e.Bounds.X + 18, e.Bounds.Y + 2);

        // ... other code removed...

        // and then draw the focus rectangle...

What do you mean, it smells like Delphi?


I was reading this posting All these sourcesat Slashdot (“OSS Music composer gaining attention”), which is about a developer who has started a Buzz-like music ‘tracker’ in C#. The part that caught my eye at the linked article was the following paragraph (Italics mine):

The day the source code to Buzz got lost was a very sad day and there was absolutely nothing anyone could do. We’d just had an updated version of Buzz released and suddenly everyone realised there would *never* be another one.

Then I went back to the development log of Rosegarden (that outstanding MIDI composer for KDE/Linux, website), which reminds us that there was indeed a Windows branch:

1995-1996: Andy makes a sibling version of Rosegarden for Microsoft Windows, adding a significant amount of extra sequencer functionality. Then he loses the only copy of the source code in a hard disc crash. You can still have the 32-bit binaries if you like, but they might not work. Don’t come crying to us if you blow up your computer.

I think I have exactly one backup of my oldest sources, (covering 1995 to 2002) which have been put on (exactly) one 700 MB CD ROM. Compressed. Then, when working on my first Toshiba (2004?), all of my sources from then on where stored in a personal folder called ‘Sources’ (how original) with many (many) subfolders, all of them containing some sort of project, library or explanation. This folder has moved with me since then and currently covers 3.5 gig of space. Naturally, I always include the executables too (that is in case I ever lose my sources1). And what not.

If you just started programming and you think you’re a hotshot: Think about the Megabytes of code you can write in the next 10 years. Oh: and don’t forget to make backups too.

1 I did lose code over the years: Missing in action are the original WordPlay/Scrabble server (PHP, this is the one I once demoed to explain separation of UI, Code and data), a NNTP statistics collector (Python, this one actually worked too and I have no idea why I wrote it) and a directory synchronizer (Python too). I recently recovered that last one though (sheer luck) when cleaning up a directory on a ‘free hosting’ server (that was the same day I wrote code to extract passwords from a popular FTP program): The code actually still works, but I have no idea how or why I actually wrote it. I don’t understand the code either, anymore, which is worst than actually losing code).