# Tuesday, 27 January 2009

http://www.developer.com/img/2002/09/18/OOP01.gifToday I read a nice post by Brian Rasmussen in which he describes how to set up Visual Studio to generate class definitions which are sealed by default. I had to post my own point of view in the matter although it is going to be awkward. Not in the teenage, “define me”-sense but in my choice of language as I can’t really quote him effectively, so you’ll have to make do with me paraphrasing his post :)

Now I’d like to put myself in the I-could-not-disagree-more camp. The default choice in my humble opinion should be to leave classes open and have all members be virtual if you want to take it to the extreme. This would leave the system open for change just as the SOLID principles state. Java got it right in my opinion.

To be able to make the decision on whether a class should be open for inheritance you’d have to travel to the future to see what the class might be used for. If you’re anything like me you’re probably challenged in the time travelling department, and so I postulate that you can’t really make a good decision in the matter. More often than not closing the system for change will be the wrong choice as requirements and environments change.

I do agree with Brian’s statement that sealing a class would take away options thus creating a simpler API. I would, however, also like to state that there are better ways of achieving a simple API. How about not exposing the type all? Why not create a simple interface, which exposes only what is needed for the task at hand?

Please don’t make the default choice for your classes sealed. Go with open classes and live a happy life with a system, which is open for change. Trust me I’ve seen systems, which adopted a closed stance and it wasn’t pretty. The team kept hitting the wall in the changes they wanted to make, simply due to the fact that the original developer had no time machine, which enabled him to foresee the changes, which future members of the team needed to implement.

posted on Tuesday, 27 January 2009 12:19:30 (Romance Standard Time, UTC+01:00)  #    Comments [0] Trackback
# Monday, 08 September 2008

evil-insideWhen first I saw the var keyword in C# 3.0 I was excited, my body tingling with excitement for the possibilities this keyword would bring to the world of many a .NET developer: Productivity, clarity, fame, and fortune. Unfortunately now that C# 3.0 has been with us for a while I feel that I must warn the public of the evil that is the var keyword. Productivity, clarity, fame, and fortune have succumbed to mind boggling spaghetti code, confusion, and lets be honest fame and fortune were never really on the table to begin with :)

What then is this evil of which I speak? Massive overuse of the var keyword. Observe the following hot dish of spaghetti bolognese:

   1:  public void SpaghettiBolognese()
   2:  {
   3:      var calculator = new Calculator();
   4:      var taxLevel = GetTaxLevels();
   5:      var person = GetPerson();
   6:      var tax = calculator.CalculateTaxLevel(person, taxLevel);
   8:      person.Tax = tax;
   9:  }

All kidding aside this piece of code breaks one of my most fundamental rules when reading and writing code: Don't make me think. Grokking a piece of code is though enough as it is having to keep types and varibles in memory (read: the developer brain) will slow down the process of code reviewing or debugging a piece of code.

For now I'm using a couple of rules to keep the var silliness at manageable levels.

1) Always use proper types for variables which are set from a method or property. It makes the code so much more readable.

   1:  Tax tax = calculator.CalculateTaxLevel(person, taxLevel);

2) Do use the var keyword when there is no question about which type it will be inferred to.

   1:  var calculator = new Calculator();
   2:  var i = 100;
   3:  var s = "Søren";

While the var keyword does offer a nice productivity gain it's important to realize when to use and more importantly when not to use it. Also it would seem that the var keyword is in cahoots with the good folks at Jetbrains as ReSharper is very eager to convert perfectly well formed type declarations to implicitly typed ones. As I started out by saying be wary of the var keyword - it's one sneaky bastard :)


posted on Monday, 08 September 2008 21:57:14 (Romance Daylight Time, UTC+02:00)  #    Comments [10] Trackback
# Sunday, 18 February 2007

I still need to run classic ASP pages at home from time to time. Me having migrated every single machine at home to Windows Vista presents a slight problem as getting classic ASP pages running under IIS 7.0 is far from obvious.

Right off the bat you'll need to enable error messages on IIS. IIS 7.0 introduces a concept which reminds me of friendly HTTP errors in Internet Explorer. basically you need to turn this off to see the actual error message. I was lucky enough to find a person called Mike Plate who encountered the same issue and wrote a post about it.

Also if you need to use the OLEDB provider to do database access to Access (heh) you need to check out this knowledge base article: Error message when you request an ASP page that connects to an Access database in IIS 7.0: "Microsoft JET Database Engine error '80004005'".

Mr. Legacy strikes again!

posted on Sunday, 18 February 2007 20:10:03 (Romance Standard Time, UTC+01:00)  #    Comments [0] Trackback
# Tuesday, 07 June 2005
Martin Fowler puts in his two cents on the static vs. dynamic debate. He makes some good points for both sides, and I couldn’t agree more with his statements about Basic kinda reminds me of the trails and tribulations I continue to have with VB6.
posted on Tuesday, 07 June 2005 12:12:02 (Romance Daylight Time, UTC+02:00)  #    Comments [3] Trackback
# Wednesday, 20 April 2005

I was looking for a Bittorrent framework targeting the .NET platform a while back, however I couldn’t come up with anything searching around. Carl Franklin to the rescue with a post entitled Pwop gets new life where he mentions an application he’s writing which takes advantage of a C# Bittorrent library.

The framework is not in an advanced state at the moment but it looks like it’s getting there. I’ll be following the progress from here on in, maybe even donate some of my time.

Go check put Btsharp (registration required).

posted on Wednesday, 20 April 2005 13:00:59 (Romance Daylight Time, UTC+02:00)  #    Comments [2] Trackback
# Thursday, 17 March 2005

How fantastic to find a bug in my code which is so easily fixed due to the use of a regex. Do you use it enough? The SQL of strings, the love of my life?

I may just have to add an ode to the regex along with an ode to Reflector to my odes todo-list

Also be sure to download and install The Regulator for you’re regexing needs. It’s right out of the “slick-tools-which-do-one-thing-perfectly” along with iTunes, BlogJet, and XanaNews.

posted on Thursday, 17 March 2005 10:29:45 (Romance Standard Time, UTC+01:00)  #    Comments [0] Trackback
# Wednesday, 16 March 2005

Want to build something like those super slick web applications coming out of Google, like Gmail, or Google Maps? Part of the trick is using the XMLHttpRequest object and Javascript for request new data behind the scenes. I’ve used this technique to solve a problem on a large-scale traveling site here in Denmark. While you need to do some SOAP goo to get it working, it does work like a charm.

Interested in learning more? XML.com has an article about the subject by Drew McLellan entitled Very Dynamic Web Interfaces.

One of the classic drawbacks to building a web application interface is that once a page has been downloaded to the client, the connection to the server is severed. Any attempt at a dynamic interface involves a full roundtrip of the whole page back to the server for a rebuild--a process which tends to make your web app feel inelegant and unresponsive. In this article, I'll be exploring how this problem can be tackled with the use of JavaScript and the XMLHttpRequest object.

posted on Wednesday, 16 March 2005 12:00:12 (Romance Standard Time, UTC+01:00)  #    Comments [0] Trackback
# Sunday, 13 March 2005

I’ve started playing around with Visual Studio 2005 for a small Flickr project I need, and I’m really digging on the new ability to specify different protection levels on get and set accessors. I’ve often found myself needed a public get accessor and a protected or private set accessor. With .NET 2.0 I can have this with writing a separate internal set accessor. Small feature but it’s something I see myself using on a regular basis.

public string MyString




                      return "";


           private set


                      string s = value;



Also: Generics… Wow! I want my next child to have this feature


posted on Sunday, 13 March 2005 09:06:22 (Romance Standard Time, UTC+01:00)  #    Comments [0] Trackback
# Monday, 07 February 2005

I figured I’d post the compiled binary containing the code for uploading images using the MetaWeblog API for everyone to use. No need to make this stuff overly complicated. Also I’ve contacted Omar Shanine in the hopes that the code might get integrated in the main source of DasBlog.

Just download the updated newtelligence.DasBlog.Web.Services.dll and copy it to the /bin folder of your DasBlog installation and you should be all set. Testing has only been performed using BlogJet 1.5 with both default location and specific location of the binary files. Remember to give the ASPNET worker process write access to the folder you wish to use to store the images in.

posted on Monday, 07 February 2005 13:41:32 (Romance Standard Time, UTC+01:00)  #    Comments [0] Trackback
newtelligence.DasBlog.Web.Services.dll (96 KB)
# Wednesday, 10 November 2004

I'm currently reading Martin Fowler's Refactoring: Refactoring: Improving the Design of Existing Code which is an interesting read given that I have started doing some of the things he describes in the book on my own. It's an interesting way of being validated and gaining an even better grasp of what is possible with the technique.

One thing I find troubling though is his section on the problems with refactoring. He himself mentions that the section is shorter than he'd like it to be and that the reason for it being that way is that the field is young and we need to gain a better understanding of it.

Great I'm with him so far but I got thinking about a potential problem with refactoring and the notion of "beautiful code". I may be missing a crucial point and I admit that I haven't read through the entire thing yet but from my point of view a critical problem with the before mentioned notion of beautiful code is that different people have different ideas of what is considered clean and beautiful code.

Now I don't know about you but I've not yet worked on a project where I was the only developer in action. One of the things Martin Fowler promotes is that you should refactor whenever you encounter something which you need to gain a better understanding of or if you are actually trying to improve in the existing design. He gives an example of using refactoring in code reviews in order to better understand what the code does.

What I see as a problem is that when different people are looking at the same code with different ideas of what beautiful code is we may end up in a situation where one person refactor another persons code, the person who wrote the code in the first place may not agree with the changes and refactor yet again, and so the story would continue without really adding any value to the overall product.

The situation which prompted this though is code review on some of my code a while back where the reviewer noted that I was using the C# one-line conditional assignment in a lot a properties, I don't actually know what it is called but an example would be

string s = ( 1 == 1 ) ? "OneEqualsOne" : "OneDoesNotEqualOne";

Now what the reviewer noted was that I should use the full blown if-construct because this would be easier to read. Here is the kicker I disagree but had he used refactoring in his code review he would have simply changed my code to use the if construct. Later I might have revisited the code and noticed those changes and went ahead and changed it back.

Of course the above example is very simple and we wouldn't keep changing that small detail back and forth but it seems to me that refactoring is very much dependent on a development team having the some idea of what constitutes clean code.

posted on Wednesday, 10 November 2004 11:28:17 (Romance Standard Time, UTC+01:00)  #    Comments [0] Trackback
# Saturday, 19 June 2004

Darrell Norton posted a stored procedure which will change all users on objects to DBO. Pretty useful if you, like me, sometimes forget to specify the owner when creating an object.

posted on Saturday, 19 June 2004 16:53:48 (Romance Daylight Time, UTC+02:00)  #    Comments [0] Trackback
# Thursday, 03 June 2004

One of the products I work with daily is Commerce Server 2000 and 2002 from Microsoft which is an interesting product trying to create a standard e-commerce platform on which you can develop your own solutions.

Anyway the product is very complex and has all kinds of nooks and crannies due to the fact that version 2000 was an ASP only product. Version 2002 has a lot of .NET classes and stuff to use but it is still just a layer added to the top of the COM objects found in version 2000.

I was tasked with creating a program which does some bulk updating using the Commerce objects. One of the tricks in Commerce Server is that it comes with a built in data abstraction layer called the profile system. A profile in the profile system is basically a table in SQL Server.

Back to the task at hand; I needed to create a ProfileContext outside of ASP.NET where it is available through a HTTP handler so I needed to figure out how to get at it without the HTTP handler doing the "heavy lifting".

First you need to add a couple of references to the COM based DLLs named ADODB.dll, AppHelper.dll, and MSCSCFG.dll. They are all found in your Commerce directory. Finally you need the managed Commerce Server runtime DLL named Microsoft.CommerceServer.Runtime.dll which is found in the Commerce Server\Assemblies directory.

Now for some code: First I needed to get the connection string for the profile system which I did in the following way: 


//  Get the profile connection string from the system config


AppConfig appConfig = new AppConfigClass();

appConfig.Initialize( ConfigurationSettings.AppSettings[ "name of your commerce application" ] );

Microsoft.CommerceServer.Runtime.IDictionary configDictionary = appConfig.GetOptionsDictionary( "" );

string profileConnectionstring = Convert.ToString( configDictionary[ "s_ProfileServiceConnectionString" );



//  Instantiate the ProfileContext object


string profileDefinitionCatalog = "Profile Definitions"; // You can look this value up in the Commerce Manager

ProfileContext profileContext ProfileContext( connectionString, profileDefinitionCatalog, new ConsoleDebugContext( DebugMode.Production ) );


posted on Thursday, 03 June 2004 23:03:32 (Romance Daylight Time, UTC+02:00)  #    Comments [0] Trackback
# Saturday, 29 May 2004

Some time ago I discovered a neat language feature of VB.NET where you can name parameters for method calls. This is actually something which has been around a long time even before .NET (was there anything before .NET? :) ).

Named parameters is a feature you can use if you want to be really explicit in your method calls it does actually improve readability somewhat.

As an example I had to code a components which would do transactions on people's credit card for Bolia.com because they have way too many transactions each week for them to handle it all manually.

The interface I was programming against looking something like:


Function Capture(ByVal sAmount As String, _

                         ByVal sTransact As String, _

                         ByVal sOrderid As String, _

                         ByVal bForce As Boolean, _

                        Optional ByVal sAccount As String = "") As Long


You can use named parameters if you want to be really explicit in your method calls it does actually improve readability somewhat. In the case I mentioned I wanted to make it really clear which values were used for what in the method call like this:


            Dim amount As String = "11111", transactionId As String = "11111"

Dim orderId As String = "11111", forceCapture As Boolean = True, accountNumber = "1111"


Capture(sAmount:=amount, sTransact:=transactionId, sOrderid:=orderId, bForce:=forceCapture, sAccount:=accountNumber)


Unfortunately C# does not support this but I guess that it goes against the whole philosophy of C# anyway :)

posted on Saturday, 29 May 2004 21:46:05 (Romance Daylight Time, UTC+02:00)  #    Comments [1] Trackback
# Wednesday, 19 May 2004

We all know and love the C# version of foreach where you specify the type in the loop like this

foreach ( object o in list )

In VB.NET 1.0 you had to do declare the variable outside of the loop which is pretty ugly as you might end up using it later in your code by accident. With VB.NET 1.1 you can do a foreach loop the C# way which probably is the new feature of .NET Framework 1.1 I use the most :)

So in the old way you would do this:

Dim o As Object
For Each
o In list

The new way allows you to use this form instead:

For Each o As Object In list

Most people probably know this but I think it's worth mentioning for the 5 people who haven't discovered it yet.

posted on Wednesday, 19 May 2004 13:11:13 (Romance Daylight Time, UTC+02:00)  #    Comments [0] Trackback

Are you using a hidden column in your DataGrids to store the ID of rows? I was until recently when I discovered that you can specify a field on the DataGrid which contains the keys. It goes a little something like this

<asp:DataGrid id="MyGrid" runat="server" DataKeyField="TheFieldInDataSourceWhichContainsTheUniqueKey">...

In code you can retrieve the key in a command event handler or something similar like this

private void MyGrid_EditCommand( object sender, DataGridCommandEventArgs e )
  int id = ( int ) MyGrid.DataKeys[ e.Item.ItemIndex ];

Neat little trick which keeps your DataGrids a little bit cleaner :)

You can of course use any data type as the data key, just change the cast to the appropriate type and you're all set :)

posted on Wednesday, 19 May 2004 12:48:59 (Romance Daylight Time, UTC+02:00)  #    Comments [2] Trackback
# Tuesday, 18 May 2004

My main focus for this blog is .NET which really isn't apparent when you look at the posts so I thought I'd add an entry about a nifty little language trick I picked up reading blogs last week :)

The @ is a really neat symbol which you use for making C# interpret a string literally. You probably written double \ more than once in a file path. Well with the @ symbol you don't have to do this simply write:

string s = @"c:\windows\Microsoft.NET";

Most C# developers know this but did you know that you can also do this:

string s = @"Line 1


The text will appear just as you wrote it. Pretty neat :)

posted on Tuesday, 18 May 2004 13:02:11 (Romance Daylight Time, UTC+02:00)  #    Comments [15] Trackback
# Wednesday, 28 April 2004

I am sometimes amazed at the lengths people are willing to go to get the job done. Take for example the simple task of getting a date from an input field. Some months ago I was working on a site which the original contractor wasn't able to get done alone so I got to take a peek at how the big businesses do their coding.

One of the things I found was how little the previous coders knew of the .NET platform - it was really obvious that these particular coders had lots of experience with ASP 3.0 but not much with ASP.NET. An example of this was when they needed to pull a date from a textbox - they accomplished this by doing two things: First assuming that the string entered would be formatted in a particular way and second by iterating through the string picking up month, day, and year parts of the date.

I did a little scounting around the SDK docs and found a much nicer way of doing this:

Dim formatInfo As New DateTimeFormatInfo()
Dim myDate As Date
formatInfo.ShortDatePattern = "dd-MM-yyyy"
myDate = Convert.ToDateTime(myDateTextBox.Text, formatInfo)

I am certainly no .NET god so as I am writing this I am wondering how much cool stuff I am missing in the .NET framework simply because I don't know enough about it?

posted on Wednesday, 28 April 2004 19:50:37 (Romance Daylight Time, UTC+02:00)  #    Comments [1] Trackback
# Friday, 23 April 2004

Ever wondered how to enumerate an enum? Well I did yesterday when I needed it to list the installed fonts on a system. It's actually very simple once you know how to :)

For Each s As String In [Enum].GetNames(GetType(System.Drawing.KnownColor))

colorDropDownList.Items.Add(New ListItem(s, s))

Next s

UPDATE: Found an article on Codeproject.com which describes even more tricks with enum. Go have a read.

posted on Friday, 23 April 2004 09:03:56 (Romance Daylight Time, UTC+02:00)  #    Comments [0] Trackback