Tag Archives: C#


You heard it here first: I’ve started working on a successor to Fandro (at xsamplex), mainly because, firstly, I love diving into these kind of algorithms. Secondly, Fandro’s popularity (for an app written in the Windows XP age) surprised me. Thirdly, Fandro required a reboot, because well, while it still works, obviously, there are issues with the current app. We’re moving to computers with higher DPI screens and 64-bit computers.

For a second I actually considered rewriting Fandro in FreePascal but I’ve decided to focus on C# for now: Yes, that will mean that most likely, I’ll open-source it. And yes, if time permits, I’ll even add side comments about how NOT to do text searches.

No timelines as of yet, though, but technically, the main algorithm was finished a couple of days ago. Time permitting, I expect at least something out by the end of the month.

The devil is in the SerialPort

I‘m surprised how many people look here for help on the .Net 2.0 SerialPort component (reference, which leads to this posting). I have plenty of example code, but I haven’t had time to re-test the project or even try com0com on this 64-bit Windows box. Com0Com (link) does support 64-bit environments, provided that you:

The com0com.sys is a test-signed kernel-mode driver that will not load by
default. To enable test signing, enter command:

bcdedit.exe -set TESTSIGNING ON

What is bcdedit?

No examples for now but my earlier mentioned posting should get you somewhere.

A circular thing

I‘m extremelyA some control impressed with the Google Chrome download indicator: for some kind of reason, a circular progress meter makes a lot more sense than a linear one. Maybe it’s because of Pi.

Since I was so impressed and because it was ‘Pi day’ the other day (Pi Day), I thought now was a good time to write a component that does just that: show the progress of something in a somewhat circular form. You can find the code right here: a reminder, it’s C# and that means it is meant for .Net. I’d be really surprised if it wouldn’t work on Mono (it should) [just tested and confirmed that it works].

A couple of notes:

  • FillColor is the colour that’s used to fill up the circle
  • ForeColor is used for the Text (progress text)

The code should be pretty clear in what it does: I was planning to also paint a bunch of “spokes” in the meter but couldn’t be bothered at the end1. It shouldn’t be too hard (use the sin/cos methods of the Math class to get the right x/y coordinates).

1 Also, this would have given it the Trivial Pursuit look: Google’s progress meter reminds me of that too.

03/16/09: Introduced drawing of Text/Label/Caption.

03/18/09: Good rewrite: Mostly introduction of ‘progressbar’ like properties and methods (Value, Min/MaxValue), Marquee. Introduction of a ProgressType enumeration (maybe should use the regular ProgressbarType). Also, same license (Commercial/personal free use, but please leave the credits in).


I haveOh Dear been making small progress on my own front-end for FFMPeg (earlier on xsamplex). Earlier I was rounding up the serializers (data persistence, data schmersistence): the threading code was finished months ago. I just have to connect the last dots, which is basically user interface stuff. Most likely I’ll end up redoing some of the serialization but it’s, like I said, pretty much done.

This reminds me of a couple of things: The FFMPeg developers maintain a list of software venders that violate the software’s license (GPL). Their list (“Hall Of Shame”) can be found at the FFMPEG website. Just a couple of seconds ago, I saw a google ad (see picture above) and I thought the name in that ad rang a bell. Oh noes, they’re in the issues trackerz!

I also noticed that a lot of people ask for ‘how to track progress FFMPEG’ and they end up at the very first post I wrote on interfacing with FFMPEG’s command-line. This is not too difficult and requires parsing of the error output (you probably need a state machine too). At one time, a programming board linked here with pointers how to track the frames and translated that to time, which they basically extracted from the bare information that I put in my sample code. I can’t find the link though, so will add that at a later stage.


During my programming career, I’ve ran into several cases where I absolutely had to use owner-draw to accomplish customized drawing. Originally, as a Delphi programmer, this required knowledge of the specific graphic wrappers around the Windows GDI (and GDI+) functions which Borland (appropriately) called TCanvas. The C#/.Net equivalent is called ‘Graphics’, which (admittingly) does not sound as fancy as Canvas.

That said: in my never-ending quest to fill a niche craving, I decided to look into the basics of photo-editing; that is, on a much smaller scale. The first step was to create a component that (given a specific image), drops a frame on it, which you can use to crop a photo (by either moving it and/or resizing it). Additionally, I always liked how some photo-editors integrate the Rule Of Thirds during cropping of photos, so, that had to be part of the custom-draw routine too.

There are couple of common tasks that need to be taken care of when doing own-draw stuff, all in C# (however, should be similar in Delphi):

  • The first thing is to decide which control you’re going to ‘descend’ from, or rather, which control is going to be your base-class
  • If your control requires user-interaction (i.e. mouse/key input), you should probably override the control’s MouseUp/Down and MouseMove events. Most likely you’ll need a couple of (private) flags that track down if a mouse button is still ‘pressed’. Add to that a couple of variables that track down the last positions clicked on the screen.
  • Separate the drawing routines and call these routines from an overridden OnPaint event.
  • Debugging (owner-draw) graphical routines is extremely painful, so think through your drawing routines.

Boring sample code is about to follow.

Continue reading


Between all the ripping of my (legally) purchased DVDs and transcoding them to the proper format for my iPod I found out that most of the applications that I used have something in common (from Videora [free] to Mediacoder (open source). All these applications actually use FFMPEG under the hood: FFMPEG literally accepts many fileformats, open-sourced and runs on too many platforms (it’s highly portable, I guess). Trouble is, since it’s part of the other multi-platform media player (MPlayer) and, particularly, thanks to the legal minefield that is called transcoding, the binaries for FFMPEG are hard to find (well, you can’t miss it now!) (you can also fetch the sources and compile a binary yourself: you’d probably need to get the MingW compiler/environment).

Anyway, all videoconverter applications that I found had either crappy interfaces or they came with that ‘build-in’ Internet browser that allows the developer to push unneeded and unwanted ads to your desktop. So yeah, it shouldn’t be too hard to build your own fricking video converter. You only need to know and study FFMPEG’s commandline options after reading this (boring code after the fold).

Update: Slightly related: the BBC’s programming team released the very first version of their Dirac Video Compression codec.

Continue reading

PropertyGrids in C#

Yesterday, An example property gridI decided to tackle .Net’s PropertyGrid component: for Helios, I was working on code to allow users to view Datasource-specific data at run-time. For this, I already had several support objects programmed and ready to go, and what better to test them right in that PropertyGrid component?

This worked out easier than I thought: Basically, the only thing you need to do as a programmer is to actually create those objects and assign it to ‘SelectedObject’ property of the component. This works in most cases, however, I had a TServerPropertyObject contained inside a TDataSourceObject (half-pseudocode follows):

public class TServerPropertyObject
     public string GroupByBehaviour {get; set;}
     public string IdentifierCase{get; set;}
     // etc...

public class TDataSourceObject
     private TServerPropertyObject fserverproperties = 
             new TServerPropertyObject();

     public string ServerName {get; set; }

     public string DSN { get; set; }

     public TServerPropertyObject Properties { 
          get { return fserverproperties; }

Obviously, the idea is to have the properties object of TDataSourceObject to show as a ‘collapsible’ item in the PropertyGrid component. To achieve this, you need to add (those devilish) so called ‘property attributes’ (I believe these are the only things that makes .Net look evil). In our case of the collapsible item, we’re going to use the ‘TypeConverter’ class and pass it the ExpandableObjectConvertor type.

public class TDataSourceObject
     private TServerPropertyObject fserverproperties = 
             new TServerPropertyObject();

     public string ServerName {get; set; }

     public string DSN { get; set; }

     // Make this property expandable and let .Net
     // figure out what to do with the object.
     [ TypeConverter(
        Description("Server properties")]
     public TServerPropertyObject Properties { 
          get { return fserverproperties; }

This will let .Net handle (and figure out) what to do with the object itself: In my case the contained object only exposed simple types (like strings and integers). Naturally, you’ll have to do a lot more work (read coding) when your objects (and components) need specialized ‘property-editors': for that, I have to refer you to the .Net documentation.

Update: See also here for more context and a larger screenshot (outdated though but still relevant).

CVS meet Enscript

Last night, This sucks. TerriblyI was installing CVS on my Debian box. Actually, it was already installed: the CVSROOT was ready to go and the service itself had been listening since the early days. However, I never finished assigning rights to myself, so, with that done and by adding myself to the cvs group, I was finally able to check in my latest Helios sources using WinCVS (I despise TortoiseCVS1).

For work, I had once added viewcvs to the CVS repository engine: Viewcvs allows developers to view the repository via a webserver. Easy as is: During its install (apt-get install viewcvs), I ran into the normal installation checks and changes for this specific script: Most of them can be resolved by Debian’s viewcvs installer but (as usual) you should prepare yourself for some old-handy typework. The first action on your list is to add a couple of Aliases to Apache’s httpd.conf file (in my case I was only interested in one, the viewcvs ‘docroot’ parameter: I don’t like graphics2).

 Alias /viewcvs/ /usr/share/viewcvs/

The next step is to set the ‘docroot’ and ‘icons’ folder parameters in the viewcvs.conf file (/etc/viewcvs/): these folders refer to the folderstructure on the webserver and not to the physical folder structure on your Linux system (hint: check Alias). After this, you can set the use_cvsgraph and use_enscript variables in that same file to 1.

Enscript is a ‘source code highlighter’, but (obviously) it doesn’t come with a state file for C#: I found a good one at Adam Milazzo’s (Thanks Adam). This file should be copied to the enscript states directory (on Debian that is at /usr/share/enscript/hl). Also, you will have to make a couple of changes to the enscript.st file (which is in the same directory): add the csharp highlighter to the namerules section. The final step that needs to be undertaken is a change to the viewcvs.py file (you generally should be able to find this at or around /usr/lib/python2.3/site-packages/viewcvs/). Look for the enscript_extensions section. Notice the comment that one of the programmer left behind, just right above that extensions section:

### this sucks… we have to duplicate the extensions defined by enscript

You wouldn’t say.

1 Yeah, I was going to write something here, but I forget. Oh right, something about TortoiseCVS and how I hate it.
2 Uh. Right. What was that again?

When the Earth

A couple of links to keep you busy for now:

I’m not sure where I got this one from, but to me ‘Social Wallpaper’ is the only compelling social network. If you can call it a social network: basically, it allows everyone to upload their wallpaper, with mixed results, of course. Some of the pictures are truly amazing, some of them plainly suck. Some pictures come from the NASA archives and some, well, don’t. I have to admit that I haven’t been convinced to change my desktop wallpaper yet (that wallpaper comes from Alfons).

Earlier this week, I stumbled upon this 2004 discussion on the Physics Forum where someone asked for ‘Prove that the Earth revolves around the Sun’Geocentric vs heliocentric:

I find it obvious, as did many previous people, that the sun goes aroudn the earth. I of course know htis to be untrue as it has been drummed into me again and again for the past 16 years.
Can someone please prove to me (so that i can prove to others as well) that the earth goes around the sun. Do not be afraid to explain using mathematics, as i see that as the only way of undeniable proof.

The discussion is eye-opening: the most compelling (easy to verify) proof seems to be planetary retrograde motion, which is too complex to explain if our solar system was a geocentric system. Additionally, with the knowledge we have of gravity, it would have been scientifically impossible to explain why the sun would move around an object with less mass (more on heliocentric vs. geocentric, right here).

And last but not least: I was surprised to find out that OpenOffice comes with CLI/.Net assemblies (if you have OpenOffice installed, it’s right in your “Program Files\OpenOffice.org 2.0\program\assembly” folder). Sample code can be found at OpenDocument4All: the projects seem to be geared towards .Net 1.1 (Sourceforge project page).

Update: Slightly unrelated: Fulll moon eclipse for next Thursday.

Owner-draw (II)

Earlier, An owner-draw gridwhich is, almost a year ago, I was comparing owner-draw programming in Delphi and C# and concluded that it’s quite similar: basically you set any visual component in a particular mode (‘I’m going to take care of drawing the content’) and then you basically override the component’s OnPaint/OnDraw event. Drawing the actual stuff is the hardest part, but there’s pretty good API help for both Win32 and .Net platforms. If you have programmed graphics in Win32 before, this is going to be a piece of pie.

So, yeah: a couple of years ago, I did some fancy stuff in a Delphi Drawgrid component. The .Net framework has a similar ‘grid’ like component, which is called a ‘Datagridview’ and you probably guessed it: it has basically the same functionality and offers the (almost) the same features as Delphi’s DrawGrid component. This brings me to that earlier mentioned project I was working on: a Sudoku puzzle generator, which obviously needed to use a custom grid-like component with a lot of colours (Warning: if you’re not interested in programming, you probably don’t want to continue reading).

Continue reading

Is there a statistician in the house?

I downloaded the Visual Studio 2008 Express Edition ISO from the Microsoft site and discovered that specific stuff I was looking for isn’t supported in that special edition. I guess there is (or rather was) a huge difference between ‘Orcas’ and the Express Editions (Earlier at xsamplex).

That said, there was a time for looking through code and then I discovered that at Microsoft’s WPF site somebody had uploaded a Peer-2-Peer version of Sudoku (see also this post, or rather, this photo). This reminded me that a couple of weeks ago, I was asked to help with an algorithm that generates a complete filled out Sudoku puzzle. This I did and after that I moved on. So, that Peer-2-Peer version apparently has an algorithm that does the same, so when I opened the particular source file, I was shocked to find the following code (see my tag):

for (int iRow = 1; iRow < = 9; iRow++)
    for (int iCol = 1; iCol <= 9; iCol++)
        iNum = rnd.Next(1, 10);
        while ((IsInColumn(iNum, iCol) 
                  | IsInRow(iNum, iRow) | 
                             iRow, iCol)))) 
                  == true)
            // Generate a number to be put on the grid..
            iNum = rnd.Next(1, 10);

            // AH01 -- OH NOES...
            if (iAttempts == 100)
                bStuck = true;
            // AH01 -- Ends.
        if (bStuck)
        iAttempts = 0;
        arrPuzzle[iRow - 1, iCol - 1] = iNum;
        if (iRow == 9 && iCol == 9)
            bDone = true;
    if (bStuck)

Let me go back a couple of steps. In Sudoku, a 9 by 9 grid is divided in nine 3×3 grids: the numbers in each 3×3 grid MUST be unique and between 1 and 9. Additionally the same rule applies to each horizontal and vertical line in the grid. A fairly good description can be found at Wikipedia.

The main algorithm for filling out a 3×3 grid with 9 unique numbers, is a statistical routine that should have came up during math classes as the ‘coloured balls in a basket problem’. There’s 10, no, lets say 9 different coloured balls in a basket. What are the chances of (blindly) picking out the red ball in the second turn?

Back to that source snippet: Random generating a number from 1 to 9 The author randomly draws a number between 1 and 9, checks if the number has already been drawn. If so, he keeps generating a random number until he gets a number that fits the needs. Here’s where the problem starts: the more numbers you have picked, the less chances there are going to be that your random generator is going to pick one of the numbers that has not been drawn yet. Take a look at the example on the right (an animated gif, opens in separate window): If the stars are aligned right and your computer is in a bad mood, it may just take a while to randomly generate those last numbers. Certainly, you could throw in a 8-core computer to speed up the random number generator but the problem will still be there. The programmer knew this too hence the reason for that ‘jailbreak condition’ (“After 100 attempts I think I should break it off otherwise it looks like the program has crashed”).

Randomly drawing numbers from 1 to 9The right way to do this is, by actually drawing these numbers from either a list or an array as shown in the animated GIF (click on the image on the left). This effectively means that your randomize Next routine needs to adjust dynamically after each draw: after all, every time you draw a number, the amount of available numbers decreases by one. There’s a minor catch here, but that’s up for you to figure out.

So: what’s the point of bringing this up? The Sudoku Peer-2-Peer application is a great showcase of the latest and greatest .Net technologies but fails horribly on the basics: using math to solve a complex problem. I do (for example) have more respect for this guy who threw in a genetic algorithm to solve the problem. This is overkill for sure because it can take up to 10 minutes to fill out a complete grid. At least he understands (and showcases) how genetic algorithms work.

Update (01/21/08): Related: Who killed the Software Engineer?


A couple of months ago (around the same time that I was looking into the sources of the .Net version of KeepPass) I ran into this page: an algorithm to generate pronounceable passwords1. Well, at least a bit more pronounceable than the ones generated by password generators like the one that is used in KeepPass.

The original code was written in Java (by Thom van Vleck, if I’m not wrong) and it appears that there’s also a C++ version available.

Not to be outdone by these formidable programmers, I converted most of the code to C#: I don’t dare to say ‘porting’, which it obviously isn’t. However, I made drastical changes to how the GPWData class is being called: all of the functionality now is IN this class (including password generation and initialization). This makes more sense and it’s also a bit more elegant to use, as shown in the following example:

            GPWData npdata = new GPWData();            
            npdata.GeneratePasswords((int)numPasswords.Value , 
                (int) numPasswordL.Value);
            foreach (string s in npdata.Items)
                textPasswords.Text += s + "\n";

I dumped the code in the Public Domain which means that you can use it for whatever you wish to use it as long as you credit me and the original authors. Go grab the sources. The zip-file only contains the sources: I generally don’t add executables to full-source projects. Also, the target platform is .Net 2.0.

1 From that Multics page: The routine was modeled after Morrie Gasser’s ‘Random Word Generator for Pronounceable Passwords’. The original routine was then standardized (adapted might be a better word) by the NIST


An assortment of links:

I was reading this article at More Intelligent Life written by Enid Stubin (who appears to be an assistant-professor of English) and the first comment in the comment section literally says:

Brilliant. This chick can actually write.

Behold: the future of the Internet!

3 Quarks Daily links to a 2 hour discussion between Dennet, Dawkins, Harris and Hitchens (in two parts). If you have some time and have read some of the material of any of the authors, you may find their commentary on religion and current events interesting.

So, Movable Type has gone open-source: the announcement was made this Summer but effectively a couple of weeks ago the official sources were (finally) published. You may remember that earlier versions of xsamplex ran on Movable Type 3. Heck, you can even steal my original MT template!

A couple of months ago, I happened to run into the sources of MyJabber IM: Much to my surprise, the sources were open-sourced (GPL). It appears that the MyJabber site doesn’t exist anymore, so, I assume that the (original) programmer’s goal was to ensure the program continues to live on. Good choice: the code is a bit ‘old’ fashioned and relies heavily on the agsXMPP library (which is dual-licensed). [Note: this is all C# stuff]

And finally (as in: the last paragraph), Toshiba has developed a Micro Nuclear Reactor, which measures only 20 by 6 feet and can deliver up to 200 KW. I read that the reactor is self-sustaining and should last more than 40 years. If you want one of these things, you can apply for one at your local security agency. People with last names that rhyme with ‘laden’ do not need to apply. If you have certificate in theoretical quantum physics, that is a plus. Oh: and you may need to allow UN inspectors on your property.