Simple lookup items in C#

October 13th, 2011

Anyone who’s ever written a desktop application in C# has probably come across this problem before: You have a class that needs a few options. Each of them has a range of values, and the value is usually selected in the GUI with a drop down box. That’s the simple bit. But you have to persist the data.

The simplest approach is to just store the strings in a column in the table that represents the class. However, there are a few drawbacks with that. Firstly, if you ever decide to change the string for the option, you have to change it in all the rows that use the string. Secondly, if your application is multi-lingual, it has to be translated every time an object is created from the database row. Third, this wastes a lot of space in the database.

The next best idea is to use an enumeration. That does away with the database update problem and the waste of space, but it doesn’t solve the translation issue. Plus: your lookup control has to convert all the values, which makes for pretty ugly code.

So here’s my solution: I create a simple class that holds static instances of itself. The class implements an interface that is probably useful to have in any case, called ILookup. Here’s the interface definition:

    public interface ILookup
{
uint ID { get }
string Name { get }
}

Now let’s look at what we need out of the class. Firstly we need it to provide a list or collection of all the lookup items. Each item is an instance of the class. But we don’t want other folks to add items to the list, so we make the constructor protected or private (depending on whether we need to inherit from the base class or not). And we have a static constructor to generate the items, then store them inside in a List<T>.

Next we have a static method that returns this list on request, thus providing the data for the drop-down boxes.

Then we have a few static methods returning individual items of the list, thus allowing for simple comparison, very similar to what we would do with an enumerator.

And finally we have two instance methods returning the ID and the name. The first is needed to provide the numerical value to store in the database. And both of them are needed by the drop-down combo to populate it’s display list.

Here is an example for class providing genders:

//
//  Gender.cs
//
//  Author:
//       Wolfgang Schulze-Zachau <wolfgangs@manticoreit.com>
//
//  Copyright (c) 2011 2011 Manticore Software
//
//  This program is free software: you can redistribute it and/or modify
//  it under the terms of the GNU General Public License as published by
//  the Free Software Foundation, either version 3 of the License, or
//  (at your option) any later version.
//
//  This program is distributed in the hope that it will be useful,
//  but WITHOUT ANY WARRANTY; without even the implied warranty of
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//  GNU General Public License for more details.
//
//  You should have received a copy of the GNU General Public License
//  along with this program.  If not, see <http://www.gnu.org/licenses/>.

using System;
using System.Collections.Generic;
namespace Manticore.Basics
{
public class Gender : ILookup
{
static List<Gender> genders;
static Gender male, female;

uint id;
string name;

static Gender() {
genders = new List<Gender>();
genders.Add(new Gender(1, "Any"));
male = new Gender(2, "Male");
genders.Add(male);
female = new Gender(3, "Female");
genders.Add(female);
genders.Add(new Gender(4, "Mixed"));
}

public static List<Gender> getAll() {
return genders;
}

public static Gender getByID(uint id) {
foreach (Gender gender in genders) {
if (gender.ID == id) return gender;
}
throw new ArgumentOutOfRangeException("Cannot find a gender for ID " + id);
}

protected Gender (uint id, string label)
{
this.id = id;
this.name = label;
}

public uint ID {
get { return this.id; }
set {
throw new NotSupportedException ("Genders are immutable");
}
}

public string Name {
get { return name; }
set {
throw new NotSupportedException ("Genders are immutable");
}
}

public static Gender Male {
get { return male; }
}

public static Gender Female {
get { return female; }
}

}
}

And that’s really it. You can use this for any number of lookup items. Because the text is only used once, and it’s embedded as a string in the code, it’s easy to convert into a multi-lingual item. The database only stores the numbers, no space is wasted. And the objects get only instantiated once, at application startup (or rather when the class is accessed for the first time).

PHP and recursion

February 21st, 2011

Hello all,

after quite some silence I have now finally got my sights again on the codercorner. Today I am to just give a little rant on the above, since it really, really angers me.

A few days ago I ran into a situation with a web application, where clearly I must have made a mistake, since everytime I called upon a certain page in that app the apache child process died with a segmentation fault, and the browser offered me the download of an empty PHP file instead of showing anything on the page. This had me puzzled for a few minutes. I then started to simply encircle the issue by looking at my changes (luckily I am using git for that web app, so that was the simple part) and then placing a few debug statements in strategic locations in the code. And within 10 minutes I had it figured out. During instantiation a class constructor instantiated another class, which in turn created another instance of the original class. And so on and so forth, until PHP runs out of memory.

As said, that was a mistake, and it is now fixed. However, there are plenty of scenarios where recursion is not a mistake, but a very elegant solution to a programming problem. One example is gathering information from all files (or a subset of files) in a folder and all its subfolders. Yes, yes, I have read all those good books that teach you how to replace recursion with loops. But guess what: the results are almost invariably ugly. Very ugly.

Now, according to several posts I have found, the PHP developers simply shrug their sholders and say that this is the way it is, like it or not, and they are not going to do anything about it. Now that really irks me.

For starters, it leads developers who do not know this, into a situation where they are baffled. The web server children die, leaving only a segmentation faults in the logs. The page itself is empty, and there are no other error messages anywhere. That’s just great. So now you have to dig through your code to figure out what is causing the behaviour, and only once you have solved the problem, can you actually go looking for an explanation, only to be greeted by this arrogance.

Secondly, recursion is a useful programming solution to some situations. It’s elegant, it’s powerful and it makes for easily readable code. Replace it with a loop implementation and 9 out of 10 times you get something that is not elegant and not easily readable.

Thirdly, how difficult can it be to implement a simple error message that indicates the problem, such as “Out of memory” or “stack overrun”? Seriously, how hard can that be? I cannot think of any other programming language that does not have it. I remember the dark days when I had to implement my own memory management code, because the compiler wouldn’t handle it and there was no runtime, either. That was more than 10 years ago. But guess what: I never had that problem.

And finally: the online manual does not even mention it. Not a single word.

So that’s today’s rant. Maybe you let me know what you think of it.

We’re back!

February 4th, 2010

Hello again!

As the frequent visitor will have undoubtedly noticed, we’ve had a little downtime lately. If you’re interested in the whole story, read on. In any case, we’re back and with a vengeance. I have spent far too much time on other projects, and not enough writing. But this will change now. Quite a bit of stuff has built up over the last few months, and now it’s time to disgorge it into the public.

As you can see, I have managed to get most of my posts back, mostly thanks to google cached pages. Now here is the whole story what happened:

Just before Christmas 2009, I get an email from one of my customers, saying his site is down. So I ssh into the server. First thing to note: it appeared to have changed its RSA signature. Strange, I thought. Do I have an intruder? Looked around. All seemed very normal, nothing unusual. And yes, the web server had stopped. When I tried to start it, I got an error message saying it bind to port 80. Hmm, also strange. Somehow some other process had managed to bind to that port. I disconnected that service, started apache and all looked fine.

The very next day, the same thing happened again. This time I noticed that all my commands in bash executed quite fast, but it took forever to get back to the command prompt.

Well, eventually I decided the machine needed a reboot. It hadn’t had one for 992 days (I have proof!), so it deserved one. Except after the reboot there was no sign of life. Nothing, zilch, nada, niente, zero. So, off I go to the hosting center to have a closer look. When I get to the box, it seems to have booted OK, but output stopped after the end of the init-bottom scripts. And most certainly no prompt, no shell, no networking, and no other services.

So I try and boot from a Knoppix CD (praise to Dr Knopper for this ingenius tool!). Except it won’t boot from the CD. Well, it was a little scratched and the guys from the hosting centre were kind enough to cut me another one, latest version. Still no boot. I get all sorts of funnies, but no working OS.

Now, I could go on with this for quite a while, the whole story took several weeks to unfold. It was Christmas anyway and I couldn’t get back into the hosting centre, and all the sellers on ebay were celebrating (= no deliveries), so I took some time to investigate this. And here’s the long and the short, as far as I could establish it: The motherboard developed a defect in the IDE connector. Probably somewhere in the interface circuitry. The net result was that all traffic on the main bus was pretty much accident prone. This explains the random reading errors from the CD-ROM (which sits straight on IDE0), but it also had far more dire consequences. The server ran on RAID5, and an integrity check from the RAID controller checked out 100%. No problems.

However, all my partitions were severely damaged. In the root partition the whole of the /etc/ folder was now suddenly a file. That explains why any boot attempt started after the init-bottom scripts, as at that point the OS would have started running through the init scripts, which are all in, you guessed it, /etc/init.d/.

And from there it just got worse. I managed to get a disk image of the /usr and /home partitions. I then started using some advanced search and rescue tools to investigate what could be found. And there is mostly nothing. The root inodes on these partitions (all ext3) were completely flattened (all zeros), and the rest of them was in a very,very sad state indeed. For my most important partition (/var) I have so far not even managed to get a disk image.

I did find myself another server that could accept the RAID controller and the disks, but it turned out that that particular box had a problem with its memory. So I am still no further with the data rescue.

Luckily enough I had some backups of the most important database on the box. Otherwise I would have really been in the pits. But as is often the case, there were lots of little files which weren’t covered by the backups. I mean, who would expect this sort of thing to happen! A fire could not have been more devastating. The backups were mostly there to protect against accidental deletion of a file.

Well, lesson learnt. Now I have backups that cover everything. I mean EVERYTHING!!!. And, of course, a new server. Not brand new, can’t afford that. But a decent box. With hardware RAID (again). But this time it’s RAID10, with a hot spare.

Well, enough for today. Hope you enjoyed the story. And remember: offline backups of everything, or might as well not do them at all.

The Great VB.Net Horror

February 3rd, 2010

Today I received an update on my LinkedIn account, so I started browsing a little around my various contacts on the site, and I came across somebody with a blog that looked interesting, so I went to have a look. I won’t name anybody here, but what I found there triggered in me the urge to write a little about it.

The blogger in question was writing about replacing some existing VB.Net applications with a PHP based web application. I happen to know a little about the applications he was talking about. I also happen to be an open source fan myself (as the blogger in question undoubtedly is).
What really caught my attention was the following quote:
“Anyway, at the moment we’re working through the process of moving all our internal business applications from Visual Basic.NET (urgh!) to PHP + a web based app”.
Well, I don’t really care too much about that particular company’s reasons why such an attempt is made. What I do care about, though, are two things here:
a) in some camps there seems to be an irresistible urge to convert anything and everything into web based applications. I’ll write more about that at some other time.
b) some people cannot resist to publicly denounce everything that has the Microsoft name attached to it.

Let’s talk about b) above. I do admit that the writer of that blog may not necessarily fall 100% in the category mentioned, but nevertheless he couldn’t resist a statement that makes it sound like VB.Net is just about the worst thing anybody could have chosen to implement software in.
Before we go any further: I love open source software. My home network runs Debian Linux (gateway and two workstations), I run a Debian desktop at work (with Windows Vista in a virtual machine, because I need it), and I would love to convert more people to using open source stuff. On average, it just works better.
Having said all of this, I do have an extensive background in computing, and for the longest part of that, Microsoft played a big part in it. I started using computers in 1985, at a time when some of my readers weren’t even born yet. So I think I can claim a little experience. And at that time, MS-DOS was the height of the game (unless you had an Apple, which was pretty much unaffordable for students like me). And Microsoft software stayed important, if not dominating, until a few years ago. And if one looks at the market shares (I am not talking commercial market shares, because that comparison doesn’t make any sense, I am simply talking about how many computers run what operating system), then Microsoft is still very much in a commanding position. According to most sources, Windows holds between 85 and 90% of the market, with MacOS in second and Linux in third.

And for many years, BASIC was very much part of the toolbox. You may say about Microsoft what you like, but they have always looked after their existing user base. No other OS has gone to such lengths to ensure that what ran under a previous version of their OS would also run under the new version. One has to remember that much effort has gone into writing lots of code for commercial applications, that never saw any publicity. And Microsoft made sure that these applications would carry on working, for the most part.

Another aspect to consider is the language itself. Originally BASIC was intended for beginners (it actually stands for Beginners All purpose Symbolic Instruction Code), but over the years, many people who liked the simplicity of it, started asking for more advanced features. While this dichotomy has been the death of many other languages, Microsoft has managed to find a useful balance. The most modern variants of BASIC, i.e. Visual Basic.NET, are actually capable of fully object oriented code, with features very similar to C# (which is hailed by some people as “java, done right”). As such, VB.NET actually provides an ideal ground to introduce non-OO programmers to OO coding. C# doesn’t have the same flexibility, it’s all OO from the word go, and if one doesn’t feel comfortable with OO (and I have seen many programmers over the years who just didn’t dig it), then one won’t get very far with C#.

So, there is absolutely no call to say “urgh!” at the mere mention of VB.NET. This be said from somebody who is not a fan of VB.NET or indeed Microsoft. I just think they (both) deserve a little more respect than that.

Software from the heap

February 3rd, 2010

I have often wondered why it is that so many software developers have tremendous trouble writing good software. Over the years I have seen lots of programs or libraries that look like like the equivalent of something from Scrapheap Challenge, and in many cases the writers of these accidents are even proud of what they did!

They don’t even understand what they are doing with their work:

  1. they are delivering something that will either collapse as soon as the input is outside their perception of what “good input” is, or it will deliver unreliable results (which is even worse, if it goes undetected)
  2. in consequence they are costing their companies money. Serious money, because their employers now have to spend more time (= money) fixing first the problems and secondly the damage done to their business and or reputation
  3. they are damaging the image of ALL software developers.

And before I go any further: I have written my own share of crap. So I do know what I am talking about. But I have also written some pretty good stuff, example being some major parts of a real-time multi-tasking operating system that to this day is in use in a few dozen power stations around the world.

So what is the problem? Well, if I look back in time to the years when I first started writing software, here are a few things that have improved over the years:
In the 1980’s there were very few universities that actually offered a degree in software engineering. My own degree is in communication electronics, and I learned programming more as a necessary evil than a desired skill. And the labs we used were positively antiquated when compared to what was being used in the industry at the same time. I can only presume that the same applied (and probably still applies) to the software engineering courses.
Nowadays there are definitely better equipped universities. But are they up to scratch? Are the professors and teachers up to scratch? Well, I am not even sure this is an important question. You see, the same universities that produce crap software engineers also produce good or very good software engineers.
Having said this, in my opinion it is way to easy to get a software engineering degree. And in fact, nobody forces you to get one in order to work as a software developer. As long as you either prove that you know what you are talking about (the good way) or you can sweet talk your way in (the bad way) or the situation is such that just about anybody who spell “software” gets hired (remember, we had that just before the dot com crash!, and the results were really bad), you are in.
In fact, because the degrees handed out by colleges and universities are so useless, I have completely abandoned the attempt to sort possible candidates by their degrees. You might as well judge them by age or gender or any other (legal or illegal, but in any case irrelevant) discriminatory factor.
Which brings me to my next bug bear. More often than not it is the companies themselves who bring on their own doom. And they do so with candidate selection processes that are woefully inadequate to the task at hand. It doesn’t take too long to develop some really good methods of sorting the good candidates from the bad, but it does take at least one person who knows what they are talking about. Which means, somebody from the software engineering team has to get involved. But the reality is that in many companies major parts of the selection process are performed by the HR department. Guess how much they know about software engineering? Well, on average I think I know more about employment law than the other way round.

But, back to the original question: why are so many programmers so bad? So I had a go at the universities, and I have my gripes with employment procedures. Still, there is more.
Software engineering is not strictly speaking an engineering discipline (in my view). It is more like craftsmanship. Have you ever seen a really good carpenter at work? The wood will do marvellous things in his hands. Then you try the very same thing yourself and it’s a disaster. Why? Because the carpenter has learned over years of practice to work with the wood, he knows the different types of wood and their strengths and weaknesses. He has learned (either by try and error or from another master in the craft, and more often than not from both) a whole range of little tricks and skills, and he has honed them to perfection through practice. And let’s just face it: there are plenty of average or awful carpenters out there. So what makes the difference between them and the true masters?
I believe it is love of the craft, dedication, the desire to achieve perfection and the will to exert energy (which for carpenters also means a lot of sweat) on the way there.
So what has that got to do with software engineering? Well, in difference to other engineering disciplines, software engineering has comparatively few fixed rules. A mechanical design engineer is embedded in a whole flood of standards and norms and rules, and even a very moderately gifted engineer can achieve decent work, as long as he sticks with those rules. This is not (yet) the case in software engineering, and it is likely that it will never be the case. In order to compensate for that, software engineers have to learn how to work with code, get a very intimate understanding of what a computer actually does with the code they write.

So ultimately I come back to those programmers themselves. Unfortunately there is still a perception in the marketplace that it’s easy to get a job in software engineering and all you need to do is to sit through a few college courses or maybe you can even get away with reading a few of those “xxx in 24 hours” books. And that attracts the wrong sort of people. People who are not in it for the love of it, but simply because they need an income, and this seemed like the easy way out. But because their heart is not there, they don’t spend energy on learning things properly. They simply learn enough to get by. And yes, they can hack together a piece of code that does something. But, as I said in the beginning: if you just look beyond the paint, it looks like some concoction from Scrapheap Challenge. Or worse.

Authentication with Active Directory in .NET/MONO

February 3rd, 2010

Right, let’s start with something quite simple.

Active Directory is a very common and attractive solution to provide user authentication for corporate environments. Apart from the fact that it is the default for all MS Windows operating systems, there are many,many applications that can be configured to use it. Pretty much anything that can authenticate against an LDAP database can use it. And from a system administration point of view, a single user account in one system for all applications is pure bliss.

In consequence it would be very useful to authenticate against Active Directory from within your custom desktop applications and in-house websites. In this article we’ll focus on authentication from within a .NET/MONO environment. This is simpler than many people would think. Active Directory is exposed by default through an LDAP interface, and that is what we will use here.

What do we need for this to work? All the necessary stuff is contained in a basic library System.DirectoryServices. And here’s the piece of code that makes it work:

using System.DirectoryServices;

//.... (your class definition goes here)

protected override bool doAuthentication(string username, string password) {
    try {
        DirectoryEntry entry = new DirectoryEntry("LDAP://" + LDAPServer + "/" + BaseDN);
        entry.AuthenticationType = AuthenticationTypes.Secure;
	entry.Username = LDAPUser;
	entry.Password = LDAPPassword;
	string filter = "sAMAccountName=" + username;
	DirectorySearcher dsSystem = new DirectorySearcher(entry, filter);
	dsSystem.SearchScope= SearchScope.Subtree;
	SearchResult result = dsSystem.FindOne();
	DirectoryEntry authentry = new DirectoryEntry(result.GetDirectoryEntry().Path,username+"@"+ADDomain, password);
	authentry.AuthenticationType = AuthenticationTypes.Secure;
	authentry.RefreshCache();
    } catch (Exception) {
	throw new ApplicationException("I'm sorry, these are not valid credentials");
    }
    return true;
}

Now a little explanation for all those things above:

  • LDAPServer is the fully qualified domain name of your Active Directory Server, e.g. myhost.mydomain.com
  • BaseDN is the branch of your Active Directory where the user accounts reside. In a normal AD system this will  a string like this : CN=Users,DC=mydomain,DC=com
  • LDAPUser is the name of a user account that can read from the Active Directory. In difference to other LDAP databases, AD requires a valid username and password. Although you should be able to use the credentials of the user trying to log in, this could go sour if that user can’t even remember his user name (because in that case you won’t even get a connection going to AD). MUch better to use a set, known user account.
  • LDAPPassword is the password associated with the above user account.
  • ADDomain is the domain of the user trying to log in. Normally all users in a particular instance of AD are in the same domain, and you will be able to define this as a constant (as in the above example, where it would be something like “mydomain.com”. However, it is possible to have multiple domains, in which case you would need to allow the user to select the domain in the login dialogue, and then pass it into the above method as an additional parameter.
  • And finally, the parameters username and password are the bits supplied by the user.

The first part of the above code just establishes whether the user does actually exist. If it doesn’t an exception is thrown (your login dialog must catch this and show an appropriate error message). This check is accomplished with the line

	SearchResult result = dsSystem.FindOne();

Once we know that the user account exists, we simply try to retrieve all information about it, but this time using the actual user credentials provided by the user trying to log in.

In the above example exceptions thown by any of the LDAP operations all result in one generic exception.  Firstly, this hides the somewhat cryptic messages of the DirectoryServices, secondly it doesn’t reveal to any potential hacker whether he’s actually got the username or the password wrong.

But, hold your fire, isn’t there is a bit missing? Passwords are stored in AD as MD5 hashes. So do we need to hash the password type in by the user? Well, no, we don’t. The DirectoryServices take care of that for us.

Well, I hope this got you going. One of the next posts will describe how to the same thing from within PHP.

Web application vs. desktop application

February 3rd, 2010

Nowadays there seems to be a strong urge to replace just about any given desktop application with a web application, sometimes simply because it can be done. Many blog posts have been written about this (http://answers.google.com/answers/threadview/id/747326.html, http://www.vinnylingham.com/top-20-reasons-why-web-apps-are-superior-to-desktop-apps.html, http://community.lionhead.com/forums/thread/3269113.aspx, http://www.bin-co.com/blog/2007/08/between-web-application-and-desktop-applications/, http://www.readwriteweb.com/archives/offline_webapps_online_desktop_counterpoint.php, the list is endless), and I am not going to repeat them here. What I will do, though, is hopefully shine some light from a different angle on this debate.

Before I set out, let me say that I have written (and still carry on doing so) both types of applications. I am strong believer that before making the decision which technology to use, one should carefully weigh the advantages and the disadvantages based on the circumstances of the case.

What follows from here presumes that the reader has made the effort to read the articles linked to above.
When looking at desktop applications, I think we need to distinguish between two very different types. Type A would be the kind of software that generally tends to work on its own, although it can use networked resources to some degree. The classical here being, of course, Microsoft Office (and many others of similar ilk) or Corel Draw or even software development kits (e.g. Visual Studio,…). That’s what most people imagine when they hear “desktop software”.

Type B is the kind of application that is developed by a company to fulfill an internal need. In most cases, these applications are never sold to the outside world (they are way to specialised to be useful to other companies and/or they provide the cutting edge, so the owner would not be interested in selling them), and more often than not these applications rely heavily on networked resources available within that company. In general, these are called enterprise applications. And from experience I would say that approx. 70% of desktop software, if not more (obviously exact figures are a bit hard to come by), fall into this category. This would be true if not in terms of numbers of applications, then certainly in terms of lines of code. At one of my previous employers I was responsible for a set of desktop applications and services built from around 250.000 lines of code, and I am under the impression that this isn’t even particularly big when it comes to enterprise applications.

And then there is type C, which are commercially sold enterprise applications. Typical examples would be accounting software (e.g. the Microsoft Dynamics series) or ERM packages. Often they are big, expensive and not deployed by just installing a client o a desktop (or laptop) computer.

Why do I make that distinction? Well, because the answers to “Could or should this be done as a web application?” vary a lot depending on the type and on the circumstances of deployment.

It is often argued that one major advantage of web applications lies in the fact that they don’t have to be installed, thus avoiding heaps of costs, and the complications that stem from having several version of the software in the field. Now consider this: any software that is mostly used within a company, can easily be written such that on startup of the application it checks whether a newer version is available from a local repository and, if necessary, run an upgrade process. In theory (and with increasing internet bandwidth also in practice) the same can be done for applications available from a global repository. Which completely negates this major argument right away. It also removes the legacy argument, because by sheer virtue of the fact that on every application startup the check is performed, there can be no legacy versions in the field.

“Oh”, I can hear you say, “but then the startup time would be unbearably long!”. No, not necessarily. If your applications are structured properly only the upgraded parts need to be downloaded. And if you deploy regularly, only a few parts will be affected. And if you don’t deploy regularly, then what exactly are you doing? I think the time of deployment cycles a la Microsoft (5 years between MS Office XP and MS Office 2007) are well in the past, the FLOSS community is showing the way here with incremental releases every few months or even weeks.

So, that immediately brings this particular discussion to an end.

Then there’s the argument about platform independency. Well, I have to tell you: if you still write software that can only be deployed under one particular operating system, don’t come whingeing to me. There are a number of frameworks out there that allow deployment to multiple platforms. Use’em. Another one busted.

I could go on shooting down these individual arguments, but that’s just tiring and not proving anything, because it doesn’t answer the question. So what does?

Well, as one of the articles referenced above points out, there are a few factors that determine acceptance of any given tool (and a piece of software is just that, a tool to get a particular job done):

  • availability
  • responsiveness
  • clarity
  • utility

I would put some of my own at the end of that list, particularly when I have to make the decision on how I am going to implement a particular set of functionality:

  • speed of implementation (essentially time to market)
  • convenience
  • purpose

Out of the first four, I think eiffel-ga has pretty much conclusively shown that only responsiveness is a real divider. And there, I have to say, desktop applications win hands down. Which is mostly due to the technology used. By its sheer nature, a web application has a problem when it comes to preserving state. The protocol doesn’t support it, so the application has to implement something to do it in its place. There are various techniques used, but they all result in a lot of extra work. AJAX seems to be the answer for most people, but hold your fire: it plays havoc with your browser behaviour. And: you need to load a lot of javascript to make this work on a scale comparable with a desktop application. And if you say, not a problem, I’ll just make sure my server roundtrips are really fast: now you depend on the quality of the link. And it is very inefficient, because on every roundtrip to the server the context or state has to be rebuilt from scratch before you get to execute the one thing you came for.

Example: in a web application showing a number of tabs as menu items, the user clicks on a tab. The page submits and reloads. If this happens in an environment requiring authentication, the user context has to be established (usually from a cookie or some hidden fields), then the effects of that usr context on the actual environment have to be computed and only then can the web application execute (or refuse to execute) the required action.

A desktop application has all of this context and state information stored in memory and has instant access to it. Only the minimum number of queries to the database is required (if there is such a thing) to provide the information needed to execute the requested action. In some desktop applications not even that, as the data is stored in cached objects. Result: blinding speed. With reliability. As I said, desktop wins hands down on responsiveness.

Now why do I add the other three vectors to my decision matrix? In fact, why do I think these are really the important ones?

Nowadays it’s time to market that more often than not ensures a win. What’s the point of releasing a competitive piece of software if the market is already taken by another company? You are having an uphill struggle all the way. What’s the point of releasing an internal enterprise application 6 months after it is needed? There is none, because the company doesn’t exist any longer. In terms of providing working solutions for a perceived or real need of your target market, speed of delivery is of the essence. Does that make a clear winner for desktop applications. No, not necessarily. If you already have a working web application environment, then it could be quicker and easier to build something on top of it. So no clear winner, it all depends on circumstances. However, if you start from scratch, then I would argue that at least at the moment desktop applications still have the nose in front, as generally web applications require a lot more framework building in order to get something properly off the ground. OTOH, this may change in years to come. I certainly have seen very good efforts in web frameworks.

Convenience is a keyword of our times. We have convenience stores everywhere, and despite the fact that most of them actually offer a lot of crap, they also offer convenient points of sale for everyday items. Convenience is king when it comes to selling on the internet. Nobody in their right mind would even think about implementing a store front for an e-commerce company as a desktop application. Why? Because it would be really inconvenient for the user having to first download the shop software before they can go an browse the catalogue. Same goes for search engines, image galleries, publishing software (such as a blog), and so on. If convenience is a major factor in the application you are going to build, the web application is a clear favourite.

And, finally, purpose. This is a bit difficult to nail down. Probably best to use some examples. If the purpose of your application is to connect people that otherwise have very little in common, the internet holds the ace. Hence the success of LinkedIn, facebook, twitter and so on. If the main purpose of your application is to allow somebody to do something on his own in his little room (i.e. its a type A applications, see above), chances are you’re better off with a desktop app (which is probably the reason why only some specific games are internet based, and most others are desktop based, think about it!). For most type B applications the web platform also doesn’t make a lot of sense unless you already have a working web framework in place. The disadvantages simply outweigh the advantages. And what about type C applications? Well, there I am pretty undecided. And, so it seems, is the world at large. MS Dynamics CRM has two clients with almost identical functionality, one as a plug-in for MS Outlook, the other is a web client. Alfresco, a serious OSS document management system, has desktop clients (Windows Explorer plug-ins) and a web interface. I think the reasoning here is simply that these heavyweights can afford the effort to build both interfaces, because their commercial raison d’etre provides the funds to do so, and it adds choice for their customers.

And so the list goes on.

So let’s come to a conclusion. The clear winner is:… … … ahem, I’m sorry. There is no clear winner. It all depends on the circumstances, the purpose, the time available for the first release, and a host of other factors.
I suppose what I really wanted to say with this article is: don’t be dogmatic, be pragmatic. Think first WHAT you are trying to achieve, then HOW. Not everything that can be done, should be done. And not everything that has been done, has been done for the right reasons. Technology changes. The environment changes. Your target audience changes. Take all factors into consideration and come to a decision based on weighing all the factors against each other, case by case.

Hello world!

January 21st, 2010

Hello, indeed.

I am not a seasoned blogger. Just wanted to say that so that right from the start we understand each other. Why are you doing this, I hear you ask. Well, I am now approaching fifty very quickly (yes, I’m an old geezer) and I’ve been in IT and related fields of activity for most of my life.I wrote my first of software when MS-DOS (anybody remember what that is/was?) wasn’t even around yet. I can’t even remember what programming language I used, I believe it was some form of Pascal. And I only did it because I needed to fill an 8k EPROM with some data and I was to lazy to hack it all manually into a file. Well, I’m sure one day I’ll write a post about that with more detail.

So back to the subject. Why me? Why now?
Over the last twenty-odd years I have done a lot of programming, seen a lot of code (the good, the bad and the truly ugly) and committed my own share of sins (don’t we all). And now it’s time to pay some back. Hopefully some younger (or maybe I should rather say: less experienced) members of the community will stumble across this site and get some pointers from my ramblings.

What will you find here?

I intend to publish here lots of little code snippets, custom components/widgets, and general ramblings on how to write better software, including some musings about more general aspects of the software world as I see it.

So let’s get on with it!