Using Settings in C# Windows Forms applications

It suprised me how poor the documentation is for using Settings with a Windows Form application written in C#. I noticed recently the following article posted on the MSDN site, http://msdn2.microsoft.com/en-us/library/aa730869(VS.80).aspx. However, there is an easier way. Create the settings you want to persist in the projects settings page as normal. Then, rather than hand coding the mapping between the setting file and your UI controls go to the form designer. In the properties of the UI control select Application Settings->Property Bindings. Map the appropriate property (e.g. Text) to the required setting value. All done, well not quite. If you want to persist the changes you need to add the following to the forms closed event…

Properties.Settings.Default.Save();

There all done, persisted settings with only one line of code….nice.

Generic dictionary indexer behaves differently

Today I discovered, the hard way, that if you ask for a key value that doesn’t exist in a generic dictionary you get an exception, whereas for specialised dictionaries (or your own derived ones) you get null. This was especially annoying has I have a load of code expecting null and a colleague changed the dictionary to a generic one. So I had to change the indexer to do a quick "contains key" to return null if the key doesn’t exist.

Who changed that file?

Writing a file watcher program at the moment but I’ve hit a problem, I can’t seem to discover who changed the file last. I’m sure Windows keeps the information but I can’t find it. Ok, so the users can turn on file auditing so I guess it’s no big deal but I can’t help thinking I’m just missing something. The other bit of information I was trying to locate is the ‘File Version’ of a DLL. After following seemingly countless dead ends looking at FileInfo, FileAttributes, etc I discovered that that this information is…under System.Diagnostics!  Obvious really!?

ASP.NET why doesn’t error?

Ok it is a strange title but…

One of my the most problematic areas of ASP.NET is the combination of Viewstate and the Page Life-Cycle. If you attempt to access the Viewstate before it’s ready then not only do you get incorrect results for that call but you corrupt the state for subsequent calls too. So given that ASP knows where it is in the life cycle and that you’re trying to access the state, why doesn’t simply raise an exception? If nothing else it would save about 100Gb worth of forum posts!

In a similar vein I was working on a HtmlInputText control the other day and fell for another issue. As a good ASP developer I knew that the ID I’ve given the control will be changed to some odd unique name with lots of "ctl_" text stuck in-front of it. (If I say I want to uniquely name it and take that responsibility then it should only use my ID, grrrr). So I when I wanted to generate some Javascript to access the control I passed in myControl.ClientID. However, my Javascript failed saying the object was null. Odd. A quick review of the code I noticed that I was accessing the ClientID before I’d added the control to the page. Ok, that makes sense, but again why is the ClientID populated with the name of the ID only before it’s been added to the page? Surely if you access the ClientID before the *page* has correctly populated it, then it should error? Oh well, just yet another pitfall to side-step.

URI or Windows file format?

I’ve been writing a component that streams a file to the user based up a supplied path. The path can either be a Uniform Resource Idendfier (URI) or a standard Windows path, e.g. C:\My Documents\MyDoc.doc
 
The problem is that the majority of the streaming enabled .net components accept either a URI or a file path but not both. Therefore my code has to understand if the passed in string contains a URI or a file path. My first port of call was Uri.IsWellFormedUriString which returns true if the string contains a URI. So if it’s a valid URI then I use the URI Streaming components otherwise I’ll use the FileStream components…however, what if they’ve supplied a URI but have simply messed up the encoded, this would fail and then attempt to supply a dodgy URI to the file streaming code. I thought I was going to have do some exception catching (yuk) but to my suprise File.Exists doesn’t seem to care about the format of the file path, either it can see it or it can’t, regardless of what rubbish you enter. So I can happily assume a file path for any invalid URI and providing I check that the file exists I don’t have to do any nasty exception handling
 
I also encountered some slightly quirky behaviour to URI.TryCreate that creates a URI or fails without raising an exception. I started to use this but discovered that it always seemed to successfully create a URI (using the file:// schema) no matter what invalid text I threw at it. So be careful when using that method.
 
 

Serializable Dictionary

Whilst writing a WinForm with a TreeView I came across ye olde problem of using components that don’t support Serialization. In my case I was shadowing the TreeNodes with my own Dictionary object, actually a generic myDictionary<string, myObject> only to discover that Dictionary doesn’t support Serialization either
 
So faced with writing some custom serialization code I quickly reached for Google and found…
 
So now I had a serializable dictionary I just had to sort out my components. The first annoying problem was that my component contains a field of type TreeNode. So like a good .net developer I added the NonSerialable attribute to the field. But when I went to serialize the component it complained it couldn’t find out what a TreeNode was, grrr. So the mere fact of exposing a public property of TreeNode, even though the resulting serialization won’t use it, is enough to fail the XmlSerializer. I’ve not thought too much about a solution to this since I only use this class internally so I changed the property from Public to Internal and that did the trick…although what if I did need to expose that as a public method? So the code now happily writes my dictionary of objects to disk.

Extension methods

After watching a Dot Net Rocks TV show about LINQ I’ve become a bit concerned about some of the supporting changes to the underlying compilers. The first of these changes is the ability to create a class on the fly without any strong-typing, at least as far as the compiler is concerned – intellisense still works. I can just about swallow that on the grounds that it should only be used to speed up development in very specific cases…actually I’m not sure I can. But then came Extension Methods. From what I can gather the idea is that you can write a new method that acts upon a specific class and then you can inject or "extend" the class with your new method. So for example I could write:
 void function AppendGoodBye(ref string message){message+=" goodbye"}
 
which would mean I’d call it like:
string message = "I say ";
AppendGoodBye(ref message);
 
With an Extended method (and I’m not 100% on the exact syntax) you write something like:
void function AppendGoodBye(this string message){message+=" goodbye"}
 
you’d then call it like:
string message = "I say ".AppendGoodBye();
 
i.e. you’ve extended the string class.
 
Now at face value that’s all very clever, but I’m worried it’s gonna’ break the OO wide open. If I want to maintain that code where do I go looking for it? Normally I’d be looking in the string class, but where do I look for it now? Seems like a step in the wrong direction to me, I need to read a bit more about this.