Why would you?

Last week I ran into a variable called @continue in the sourcecode of a project I’m reviewing. At first I had to think a bit before I knew what the @ was for. Of course I knew it’s an escape character when used in front of a string value. But when used in front of a variable name? In that case, it is an escape character also, but this time for the name of your variable. This way you can use a reserved word as a variable name.

Why would you do this? What’s so important about that exact name of the variable that it is not possible to think of a slightly different name which is not a reserved word? In this particular case, the boolean was used to indicate if the method it was declared in should continue parsing the next value in a foreach loop. I would call the variable ‘continueParsing’ or ‘continueLooping’ or something like that*. Those more clearly state the purpose of the variable, and don’t make you escape your variable name. Furthermore it doesn’t baffle 75% of the developers maintaining or reviewing your code because they don’t know why the variable starts with an @.

Maybe I’m missing something. Maybe there are certain situations where this an absolute must. I can’t think of one right now though…. can you?


* By the way, the best way would probably be to use a break statement, but that’s not the reason I’m posting this for. ;)

By |March 20th, 2007|.Net|1 Comment

UIPAB with ASP.Net 2.0 – our solution

As I posted earlier we had some trouble with upgrading the UIPAB to be used in a ASP.Net 2.0 Web Application Project. Eventually, we solved the problem and life was good. Almost a week ago I received a mail through my blog from someone looking for the solution. So here we go…

We changed a few lines in the UIPAB WebFormViewManager. The problem was in determining the application path in the method ‘RedirectToNextView’. Here the applicationpath was all garbled up, which caused the redirect not to work. We implemented a property to return the right applicationpath:






1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
       private string applicationPath = null;
 
        /// <summary>
/// Property returning the entire URL to the current request,
/// excluding the page name but including the last slash (“/”)
/// </summary>
private string ApplicationPath
{
get
{
if (applicationPath == null)
{
if (HttpContext.Current.Request.UrlReferrer == null)
{
applicationPath = HttpContext.Current.Request.Url.ToString().Substring(0, HttpContext.Current.Request.Url.ToString().LastIndexOf(“/”) + 1);
applicationPath += “(S(“ + HttpContext.Current.Session.SessionID + “))/”;
}
else
{
applicationPath = HttpContext.Current.Request.UrlReferrer.AbsoluteUri;
applicationPath = applicationPath.Substring(0, applicationPath.LastIndexOf(“)/”) + 2);
}
}
return applicationPath;
}
}

The above returns the path we need. It’s not a perfect example of defensive programming, but that’s not the intention of this post ;).  We added the sessionstring because the application in which we used the UIPAB kept the session id in the URL. The RedirectToNextView method now looks like this:






1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
    private void RedirectToNextView(string previousView, ViewSettings viewSettings)
    {
try
{
if (previousView == null)
{
HttpContext.Current.Response.Redirect(ApplicationPath + viewSettings.Type, true);
}
else
{
HttpContext.Current.Response.Redirect(ApplicationPath + viewSettings.Type, false);
}
}
catch (System.Threading.ThreadAbortException)
{
}
    }

And that’s it! Looking back the problem seemed so big, but the solution seems/is so simple… ;)

By |February 16th, 2007|.Net|0 Comments

Cannot create/shadow copy ‘your assembly info here’ when that file already exists

I encountered his error for the first time today. A Web Application Project I’ve been working on for the last months started throwing this error today almost every time I wanted to debug the project. The assembly info changed from time to time, but the error was the same. Most of the time I could ‘repair’ it by closing the ASP.Net development server. But sometimes, even that didn’t work.

After the first time it hit me today, I kept encountering this until I was fed up. I searched the internet, but there’s not much documented about this little bug. There are more people with the same problem but I didn’t find a solution at first. Then I found this page. That’s the exact error I’m getting! And now I think of it, I too always build my solution before I press F5 to debug. After searching based on that page, I found this post here. It seems there’s a web.config solution for this problem: adding <hostingEnvironment shadowCopyBinAssemblies=”false” /> to the system.web element of your web.config file. The ‘shadowCopyBinAssemblies’ property is described as follows: Sets a Boolean value indicating whether the assemblies of an application in the Bin directory are shadow copied to the application’s ASP.NET Temporary Files directory.

Hope this helps.

By |February 14th, 2007|.Net|1 Comment

Defensive programming

We all encountered them in the field somewhere along the way: pieces of code that are based on assumptions. There’s something fundamentally wrong in assuming when writing code. I can understand that, looking at the big picture, you sometimes have to make an assumption when developing software. Some things you just can’t know for sure. This might concern something simple like the resolution of the targeted audience. But most of the time these kinds of assumptions are based on experience or plain old common sense. When these assumptions fail to be true, most of the time a mitigation strategy is at hand. And the software usually keeps running.

When it comes to actually writing lines of code, I think you should always check and never assume. I tend to compare it to riding on a motorcycle. My instructor teached me to drive defensively. To ‘Expect the unexpected’. Sure, you can assume there won’t come a kid running from inbetween the two parked cars, but why take the risk? It’s better to anticipate a kid running across the street, so you can react accordingly when it does. And if it doesn’t? You at least didn’t take a chance …

Sometimes, an assumption is obvious:





1
2
3
4
public string ConvertObjectToString(object objectToConvert)
{
return objectToConvert.ToString();
}

Here, you assume the object which is passed in will always contain an actual object. But when a null reference is passed in, this method will throw an exception because objectToConvert is not set to an instance of an object and therefore you can’t invoke ToString(). When this method is written ‘defensively’, it looks something like this*:





1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public string ConvertObjectToString(object objectToConvert)
{
string returnValue;










if (null == objectToConvert)
{
returnValue = string.Empty;
}
else
{
returnValue = objectToConvert.ToString();
}

return returnValue;
}

That was an easy one. Sometimes, assumptions in code aren’t very transparent. Let’s take a look at this sample:





1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
/// <summary>
/// Method that ‘does something’ to a Control.
/// </summary>
/// <param name=”controlToWorkOn”>Control on which ‘someting will be done'</param>
/// <returns>A Control on which ‘something has been done'</returns>
public Control DoSomething(Control controlToWorkOn)
{
if (null != controlToWorkOn)
{
if (controlToWorkOn is TextBox)
{
//Do something important to a TextBox
}
else if (controlToWorkOn is Button)
{
//Do something important to a Button
}
}
return controlToWorkOn;
}

We will leave the ‘do something important to…’ parts out of this. The Control is checked for being null. The Control is typechecked so no wrong casts will be made. So nothing seems wrong, right? The problem here is the fact that you know this method only does something for a TextBox or a Button. But what happens if a year from now somebody gets the assignment to change the application, and he or she doesn’t know about the method only working for TextBoxes or Buttons? The method will return the Control unchanged, but the caller might think everything is OK. Often we write methods with certain constraints about the calls made to that method in the backs of our heads. And often without realy realizing it. But there might come a time that somebody who doesn’t know the constraints has to jump in.
To be sure passing in another type of Control will not give any problems, you might consider a solution like this one:





1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
/// <summary>
/// Method that ‘does something’ to a Control.
/// </summary>
/// <param name=”controlToWorkOn”>Control on which ‘someting will be done'</param>
/// <returns>A Control on which ‘something has been done'</returns>
public Control DoSomething(Control controlToWorkOn)
{
if (null != controlToWorkOn)
{
if (controlToWorkOn is TextBox)
{
//Do something important to a TextBox
}
else if (controlToWorkOn is Button)
{
//Do something important to a Button
}
else
{
throw new NotSupportedException(“Control-type not supported in this method”);
}
}
return controlToWorkOn;
}

Another way to solve this problem is to make the DoSomething method private and generate two public methods. One that takes a TextBox and one that takes a Button, both eventually calling the private DoSomething method. This would actually be the solution I would choose, because then the problem pops up compile time in stead of runtime. And I think it aids future developers better.

‘Defensive programming’. Writing software anticipating as many problems as possible to ensure correct functioning of the software. Even when the software is edited later by someone who doesn’t have your mindset.

Edit: Wikipedia has an article on defensive programming.
Edit2: Thanks Geraldo Hockx for your sharp eye! I changed the code samples: I made a few typo’s.


* Yes, you could initialize the local parameter to string.Empty and only have an if-statement. And yes, you could use the conditional operator. And of course you could use two return statements. But this is my coding style (at the moment) so this is how I would do it right now ;).

By |February 8th, 2007|.Net, HowTo|0 Comments

ASP.Net (2.0) AJAX extensions version 1.0 released

Scott Guthrie announced it January 23rd: version 1.0 of the ASP.Net AJAX extensions has been released. Good news … !

Scott also added a post containing Links to ASP.NET AJAX 1.0 resources, and answers to some common questions. A good read for people who would like to get started on AJAX. It catches some of the common problems you might encounter when you get started with the ASP.Net AJAX extensions. I liked the addition 2.0 (ASP.Net 2.0 AJAX extensions), but that’s not used everywhere. Probably because it’s kinda weird using two (different) version numbers in a single products’ name after adding 1.0 for the version for the AJAX library… (full & difficult productname used here.)

By |January 25th, 2007|.Net|1 Comment

UIPAB trouble upgrading to ASP.Net 2.0 Web Application Project

We’re working to upgrade our current ASP.Net 1.1 project to an ASP.Net 2.0 Web Application project (so that’s not the new Visual Studio 2005 website model). We had some basic minor migration issues, which have all been addressed and are currently solved. The only problem we have right now is with the UIP Application Block. There are several people online stating they’ve got UIPAB working in a .Net 2.0 project. Unfortunately, we haven’t got it working… yet ;)

The fact they’ve got it working might be in several things: are we using the UIPAB differently? Is the problem in the fact that we’re using the Web Application Project projecttype? And maybe others have got it working in WinForms apps, but not in WebApps? Anyway, we changed the UIPConfigSchema based on this thread to get it to ‘run’ without generating runtime errors. At this point, everything compiles and runs without runtime errors… What’s the problem, you ask? The UIPAB is supposed to redirect to the first page of the view as soon as a button is pressed, but doesn’t. Actually, it doesn’t do anything. After calling UIPManager.StartOpenNavigationTask, the code execution eventually stops in the WebformViewManager class at the RedirectToNextView method with a ThreadAbortException. This seems to be caused by the Response.Redirect, which natively causes this exception. When you use the override with the EndResponse boolean set to false, this should avoid the Response.End being called and so should stop exception from being thrown. The UIPAB uses this overload, but the exception is still thrown. I’m not sure if that is the problem, but it seems so at this point.

We’re looking in to this right now. If we find anything, I’ll keep you posted. On the other hand: if you have any pointers, I’m open to suggestions. Drop me a line.

By |November 28th, 2006|.Net|0 Comments

Getting the computername of the host of a VMware image

Because of a new way of working here at the customer I’m located at, two virtual machines will be deployed to each developer’s machine. These VM’s will be run using VMware player. The thing is, the VM’s should be able to access the network and all the ‘normal’ resources. Because of this, all the VM’s should have unique (computer)names. But they have to be traceable to the host machine.

The wish the customer has at this point is to give the VM’s a computername based on the name of the machine the VM will be run on. Unfortunately, this doesn’t seem to be supported in VMware, other than using sysprep and asking the user to enter the host’s computername. At this point the ‘asking the user’ option is being used, but we’re trying to find a way to get host’s name from within a VM without any user interaction. Nice challenge… ;)

The VM’s are working like a charm. Dragging and dropping files between host and VM, supergood performance (of course, with a 2.16 GHz Core Duo 2Gb internal memory laptop….!) and seamless resizing of the entire VM desktop. My first impression tells me VMware player works smoother than Microsoft Virtual PC, but the comparison is uneven because of the state of the art hardware I’m running VMware on right now… If I have any more info, I’ll keep you posted.

By the way, if you have any ideas about getting the host’s name, drop me a line.

By |September 15th, 2006|.Net|1 Comment

Basic .Net training

Together with a colleague, I’m giving basic .Net training for colleagues at this moment. Not at THIS moment exactly, because they’re doing exercises right now. But today is the second day of four days of training in total. Currently we already have two weird things popping up.

Last week we encountered significant inaccuracy when calculating values using doubles. For instance, when adding 0.1 to a double (instantiated at 0) several times, the value wondered off. After 3 or 4 times there was an inaccuracy of 2 or 3 in the last decimal. The difference is very very small, but it’s there… I knew there’s an inaccuracy in the representation of doubles, but I always thought it only occurred with difficult fractional values.

VB6 DLL’s are not always imported as you would expect. Visual Studio (2005) automatically generates interop assemblies when you reference a non .Net assembly. Today one of the course takers did this, which resulted in classes that didn’t have all the properties defined in the old DLL. There were two string properties having the exact same coding placed in different classes, and only one of them showed up in the interop assembly. Also, some properties showed up as properties, some showed up as methods (set_PropertyName()) and some of them didn’t show up at all. I’m currently investigating why, but it’s kind of weird…

By |September 12th, 2006|.Net|1 Comment

New MSDN Library provides IE7 Search provider

MSDN 2 Library has been online for a while now. When you visit the ‘old’ MSDN library, you see the following text:


We’re upgrading the MSDN Library to a new publishing system which provides improved performance, better search relevance, XHTML compliance, URLs which don’t change after product releases, and more. During the next few months we’ll gradually move content over to the new site, although MSDN Search will work across both sites automatically. The first few levels of the Table of Contents (TOC) tree will be kept in sync across both sites; you can select the product/technology you want in the directory tree and we’ll redirect you to the correct library for that content.


You are currently viewing the “classic” MSDN Library located at http://msdn.microsoft.com/library. To go to the new MSDN Library, go to http://msdn2.microsoft.com/en-us/Library.


In the coming months, the documentation hosted in both libraries will be consolidated into a single MSDN Library.


That last sentence is a nice one…: Microsoft won’t be maintaining two different libraries, but they will be consolidated into a single library.


When I visited the ‘new’ MSDN Library for the first time, things looked pretty much the same to me. Maybe some links and functionality moved to another place on the screen, but the basics were still the same. After my first search, I saw something nifty: “Got IE7? – get our search“. Microsoft developed an IE7 search provider for the MSDN Library. This means you can use the search bar in IE7 to directly search the MSDN Library! It has saved me lots of time already…

By |July 17th, 2006|.Net|0 Comments

Unexpected behaviour when calling overriden method

Since not too long ago, I joined the MSDN Forums. The MSDN Forums is a big community where lots of knowledge is passed around. I recommend joining.

Yesterday I ran into an interesting post. It’s about an overriding method that exactly seems to match the call, but doesn’t get called. In stead, the base method is called… Apparently this is because of override-resolution starting at the base working its way up, and a method declaration that matches more than you would think it does.

You can find the thread here.

By |June 30th, 2006|.Net|1 Comment