Tag Archives: .Net

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).

Ice, Ice, Maybe (part 2)

I finally figured out why help is skimpy on Wix (the Windows Installer XML toolkit): that’s mainly because the original designers of Wix don’t want you to use Wix. It’s that simple: Wix’s learning curve is so steep, I wouldn’t even recommend it if you’re not willing to spend time at it. Additionally, don’t bother looking for sample templates (that is if you can find them) or help for the cryptic warning and error messages.

On the good side, there are a couple of good tutorials that should give you some leeway in your custom install script: There’s Gábor DEÁK JAHN’s (excellent) basic tutorial on Wix, which is probably the first site you should take a look at. Additionally, for more advanced application and use of Wix, you should probably check out Alex Shevchuk’s pages: his articles are highly technical and you may actually pick up some stuff regarding the inner workings of Microsoft’s Setup Installer SDK.

Anyway: if you just figured out that you need to add an additional data directory to your application setup program and you ran into a roadblock of cryptic messages (don’t bother going in here if you’re not interested):

Continue reading

Ice, Ice, Maybe

Everytime a Wix script (Windows Installer XML) fails to compile, it logs ICE errors. For some kind of reason, whenever these errors or warnings pop up, I keep humming the tune of Vanilla Ice’s “Ice Ice Baby” (Youtube, if you’re so obliged).

I have always been a fan of NSIS (@sourceforge), the Nullsoft Installer System, but I hear that NSIS’s installers don’t run 100% flawless on Vista systems. Wix then, and that’s not because it’s the best system: it’s slow, clunky and the errors are highly Vanilla Ice, Baby.

A couple of years ago, I used to use InnoSetup, but nowadays, I find it too tied to the Delphi language: There’s no doubt in my mind that Embarcadero has great plans for Delphi, but their “reasons why you should buy Delphi” remind too much of the old ‘slogan’ days. You know: “RAD”, “productive”, “rich” and “ease”. I don’t want that: I want Push-Button Spreadsheet Power.

And shit, yo.

FFMpeg II

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.

Canvas

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

Net. Net.

I read that the Mono developers officially released Mono 2.0, which promises compatibility with Microsoft .Net 2.0. The official announcement can be found at the Mono-project (releasenotes, if you’re impatient). The Slashdot discussion is right here.

There was a long thread (discussion, so you will) on the Postgres mailinglist about Debian, Postgres and backports (ugh!). The issue is complex and it’s a long story about why latest versions of Debian were stuck with older Postgres versions, while most platforms moved to the recent 8.x series of that database. Anyway, the good news is that it looks like that Debian Lenny will come with a more up-to-date version of Postgres. Or, something like that.

Going back to Slashdot, there’s an interesting thread about multi-threading, or rather, about recommendations about good books on this. I’ll be the first to admit that at one time I picked my nose up for .Net threading: I thought Delphi’s way was a lot more elegant, where you’re threading model essentially starts with creating descendants from Delphi’s TThread class. Threading, indeed is a different and difficult beast.

FFMpeg

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(
           typeof(ExpandableObjectConverter)),
        Category("Connection"),
        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).

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) | 
                   IsInThreeByThree(
                      iNum, 
                      GetThreeByThree(
                         GetThreeByThreeIndexFromRowCol(
                             iRow, iCol)))) 
                  == true)
        {
            // Generate a number to be put on the grid..
            iNum = rnd.Next(1, 10);
            iAttempts++;

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

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?

Oh. Noes!

Yesterday, my two sets of Ubuntu 7.10 (“Gutsy Gibbon”) arrived by snail-mail, which means that I’ll be upgrading my ‘v1r7u41 b0xen’ this weekend. Once again, the package came with free stickers. Hey, Sun, what’s that? Still no free stickers with your Solaris disks?

Engadget listed PhotoVu’s Digital Frame which comes with an RSS reader. Wait, there’s more: it has a built-in webserver (so that you can set up things and stuff). Wait there’s more: It uses Samba. 1, 2, 3, 4: Why, it runs Debian, of course. Nifty.

And on a completely different note: the .Net Framework (confirmed in 2.0, for sure) doesn’t support serialization of TimeSpans. This is not really a big issue, because you can generally workaround this. It just struck me by surprise.

The Duh

I think I saw the announcement of the new Boing-Boing TV on MetaFilter or Reddit, I can’t remember (Oh wait, it was via Laughing Squid). I generally have no problems with videocasts (For example, I always enjoyed watching ‘Rocketboom with Amanda Congdon’ and ‘Ze Frank’), but the show produced by Boing-Boing was not something I could bear longer than one minute. I also know why: it smells ‘over-produced’, thanks to that ‘glossy soft-focus’ look. Yeah, ‘over-produced’ sounds like the right word.

Hey: Microsoft announced their Zune 2.0s. The only real killer feature of the Zune is the wireless connection feature, which allows Zune users (limited) filesharing. And talking about Microsoft, I hear that they plan to release .Net code under (Microsoft’s specific) Reference License (which falls under the company’s Shared Source Initiative, which allows you to view the sources but not to copy and ‘recompile’ them). Read the Slashdot thread.

And to top it off, at CBC’s there’s an excellent discussion (and a podcast) about the HPV vaccine.