# Sunday, December 14, 2008

Just a small note on a problem I just had.  ASP.Net provides an ID for the current session which can be especially useful for tracking statistics about the user.  Normally you expect all requests from a single user to come in with the same session ID however that was not the behaviour I was seeing today.

It turns out that unless you make a change to the session data, the session will not be persisted and a new one will be generated for the next request.  Something like this placed in you Global.asax file should do the trick:

    public class Global : HttpApplication

    {

        protected void Session_Start(object sender, EventArgs e)

        {

            Session["PersistMe"] = true;

        }

Sunday, December 14, 2008 6:37:53 AM (GMT Standard Time, UTC+00:00)  #    Disclaimer  |  Comments [1]  | 
# Friday, December 05, 2008

I've just downloaded NDepend for the first time and I'm going to make notes here as I work my way through it.  Please note that I'm a complete beginner with the tool so this is first impressions only, not a comprehensive review.

I've heard lots about the tool and seen lots of interesting posts on what it does, but have never really been sure if it would give me any value.  My first concern looking through Patrick's blog is that there are a lot of crazy numbers, graphs and blobs of something going on.  It doesn't seem very approachable at first glance, let's see how it works out.

The .zip file doesn't contain an installer which always makes me wonder where to put it, I'm not sure if that's a good or a bad thing.  I watched a quick demo but I like to dive right in so I'm ignoring the documentation for now.  I've got a nice small project I've recently started so I'll drop in the .exe and see what it says...

Stuff, Lots Of It!

Loading my .exe I get a screen filled with lots of, er, stuff.  I should point out that I'm not looking for any particular piece of information here, I'm looking to see what the tool can do for me and apparently that's a lot.  Having a quick scan around I see this in the lower right:

NDepend

That's surprising.  I don't comment very heavily so I would expect a lot more complaints!  Apparently the filter ignores small methods which makes sense.  Opening up the method in Visual Studio shows that it doesn't have any comments at all.  A quick refactor breaks the method in two using the method name to explain what's going on.

I jump back to NDepend to see what it says but have a mouse spasm and drag one of the many panels out of place and can't figure out how to get it back where it was.  Fortunately the View menu comes to the rescue with Reset Views.  I run the analysis again and it takes 15 seconds, which seems a bit long for such a small project, but being in a malnourished VM it's not a very fair measurement.

The warning is gone, my code is cleaner, one point for NDepend.

CQL Queries

I take NDepend's point back for the bad pun, this panel looks interesting though:

CQL

This looks a lot like FxCop and many of the rules are the same.  Looking through the rules it seems I'm going to need to customise them heavily to suit my code, the first things I see are:

  • It complains that all my WPF controls are too big, not much I can do about that.
  • It wants to mark protected, internal or private a bunch of methods I expose for unit testing.
  • It wants to name all my instance variables with the dreaded m_.
  • It wants me to seal all my classes, maybe I should but no one else is using this and I just don't care.

Back To Work

My dependency matrix is far to small to be interesting at this stage so I'm not spending any time with it, everything seems good so far though.  There's this crazy thing with the blobs but it's hard to see what it actually tells me and I only have 30 or so blobs so it can wait.  I've got features to build so that's all for today.

First impressions?  There's a lot here and it's going to take time to figure it all out.  I can see real value in using it to maintain the quality of large code bases, especially where teams are involved.  For the little project I'm working on right now it's a lot to take in and I don't know if it will work out, perhaps it will just help keep me honest for the moment.

Next time I want to clean up those CQL queries to see if I can get all the lights to go green, then maybe see if I can get something useful out of those... blobs.

Friday, December 05, 2008 3:11:18 AM (GMT Standard Time, UTC+00:00)  #    Disclaimer  |  Comments [0]  | 
# Thursday, December 04, 2008

My blog is named after one of the most frustrating types of errors we get in programming, the generic one.  This particularly nasty specimen is a common one from .Net:

A generic error occured in GDI+.

Since I've seen a few Google searches head my way looking for a fix I thought I'd give a few tips.  Here's the code that I used to generate this error:

    static void Main()

    {

        Image image = Image.FromFile("Sample.jpg");

        image.Save("ConsoleApplication1.exe");

    }

Wow, that's a pretty cryptic error for 2 lines of code.  The key is the filename passed in the second line, "ConsoleApplication1.exe", it's the name of the application we're running and of course you are not going to be able to save an image to it...

The most common cause of "A generic error occurred in GDI+" is that the application does not have permission to write to the filename you gave it.

In my experience of course.  Here's some common things to check if you think this is your problem:

  • Is the file in use.
  • Does the user your application is running as have write permission to the file / folder.
  • Are you running in a restricted environment (e.g. ASP.Net medium trust), and trying to write to somewhere you shouldn't (e.g. the Windows folder).
  • Is there enough disk space.

Generic errors are especially nasty because not only do they present a problem with no hint of a solution, they also give you the impression that the original developer didn't know either.  This case seems common enough that the developer should have been able to provide a better error message.  In my opinion it's a serious twinkie denial condition for Microsoft.

If you've encountered any other interesting generic errors I've love to hear about them.

Thursday, December 04, 2008 6:49:45 AM (GMT Standard Time, UTC+00:00)  #    Disclaimer  |  Comments [0]  | 
# Tuesday, November 18, 2008

Today I began using the first version of the WPF data grid available on CodePlex.  So far everything is making sense but I got caught out by an unexpected behaviour with one of the new C# 3.0 features, object initializers.  The problem arose when I was trying to create columns in the data grid programmatically:

    dataGrid.Columns.Add(new DataGridTextColumn

    {

        Header = "First",

        Binding = new Binding("Length")

    });

Despite my insistence that the computer should accept this without complaint it threw up the following error:

A TwoWay or OneWayToSource binding cannot work on the read-only property 'Length' of type 'System.String[]'.

OK so it doesn't like binding to a read only property.  I found a few forum posts that indicated setting IsReadOnly on the column would cause it to become a one way binding which is what I really wanted:

    dataGrid.Columns.Add(new DataGridTextColumn

    {

        Header = "Length",

        Binding = new Binding("Length"),

        IsReadOnly = true

    });

This had no effect whatsoever.  A little confused, I went for a walk to puzzle over what I was doing and when I came back I made one simple change that solved the problem:

    dataGrid.Columns.Add(new DataGridTextColumn

    {

        Header = "Length",

        IsReadOnly = true,

        Binding = new Binding("Length")

    });

So there are two things I learnt today.

First, the properties you set in object initializers are set just like normal properties, in the order that you specify.  In general I would say that if you are making properties where the ordering is important, you might want to rethink your API if possible.  This little detail seems obvious now that I know it.

Second, WPF data binding is very eager and will try to apply any changes you make right away.  This is a big difference from ASP.Net data binding which is a very lazy and badly behaved beast.  If you want to mess with the setup of a WPF control in code, it might be easiest to do it before you bind any data to it.

Tuesday, November 18, 2008 6:25:12 AM (GMT Standard Time, UTC+00:00)  #    Disclaimer  |  Comments [0]  | 
# Monday, November 17, 2008

In this post I explain why FlashGot combined with Free Download Manager is a great combination and try to use it as an example of good object oriented design.

Downloading large files from web browsers has never been much fun.  None of the major browsers has a download tool that really works for me so instead I pass files over to a little application called Free Download Manager which deals with resuming, acceleration, scheduling and so on.

Recently I wanted to save some web casts to disk so that I wouldn't have to open my web browser and stream them down each time I wanted to to watch them.  The web casts in question were delivered in the same way that YouTube videos are, an embedded Flash player which links to another video file, usually a .FLV or a .MP4.

Firefox

The main reason I'm a Firefox user is the impressive add on community built up around it.  Initially I looked at an add on with a promising name and a large number of positive reviews, Video Download Helper.  When it detects a video being downloaded it highlights a button in your toolbar which lets you download the video as a normal file, using the standard Firefox download tool.

This works fine but leaves me a little frustrated as I have already installed another program to get away from the standard download tool.  I put up with this for a little while and eventually figured out that once I had the download going in Firefox, I could right click it to copy the link, add it manually to the Free Download Manager and then go and cancel and clear the Firefox version.  It works but it's way to many manual clicks for such a simple task.

A Better Plug In

The Mozilla site has done a great job of gathering all their extensions into a single place and giving you different ways to navigate them.  Having a quick poke around I found myself looking at the most popular download management add-ons.  Right at the top of the list is a little piece of magic, FlashGot.  Like Video Download Helper this one gives you a simple icon to click when there is a video available for download, but the reason it really stands out is this little menu:

FlashGot

See that there?  FlashGot automatically detects downloads managers I have installed and gives me the option to pass any URLs to them to deal with!  Downloading now becomes a single click process, nice!

While writing this it occurred to me that this is a great demonstration of software design principles but on a larger scale than I normally talk about:

  • Firefox has been built to be open for extension, without any knowledge of what those extensions might be doing.
  • Free Download Manager is a well defined component with a single responsibility, take a URL and download it as fast as possible.  It doesn't care where the URL came from or why.
  • FlashGot provides a simple bridge between the two and makes the system as a whole much more valuable to me.

This could be used as an example of several different design patterns, anyone care to have a go at naming one?

Monday, November 17, 2008 11:19:19 PM (GMT Standard Time, UTC+00:00)  #    Disclaimer  |  Comments [0]  | 
# Wednesday, October 08, 2008

I've become quite a fan of Eric Evans book, Domain Driven Design.  Well, the first half at least.  Part of my recent work has been been moving towards the persistence ignorance people in this space push for so much.  All this really means is creating a domain layer that is not aware of, and has no dependency on the way it is stored.

Microsoft recently released the ADO.Net Entity Framework which was lots of fun for the ALT.NET crowd because it gave them something new to complain about.  One of the things that kept coming up was that Microsoft's new framework wasn't going to support the kind of persistence ignorance many of us are looking for, though apparently it will move towards this in version two.  One of the most cited alternatives is NHibernate, the .Net port of Hibernate, the popular Java ORM (object relational mapping) tool.

Though I've used a few ORM tools in the past I haven't used NHibernate, so I thought I would give it a try so I could get the most enjoyment out of the enthusiastic debate over Microsoft's latest toy.  When I began using the library I already had some domain objects in place and was pretty happy with how they were sitting.  The following are observations made while converting my repositories (data access layer for those not hip with DDD) over to use NHibernate.  Note that I am using the library directly, rather than through another layer such as Active Record.

No Dependencies

True to it's word NHibernate lets you create your domain classes without doing any of the following:

  • Inheriting from a particular class.
  • Implementing a particular interface.
  • Attaching any attributes.
  • Referencing the NHibernate DLL in any way.

This is really rather refreshing after working with some alternate products that do place these restrictions on you and make it very difficult to move to a different storage mechanism in future.  In my case this is particularly useful as I have some data stored in SQL Server, some data accessed via web services and some data on disk but would like to hide that from my application and present it all through the same set of domain classes.

Some Restrictions

While your domain will be free of direct dependencies on the NHibernate library, it does enforce a couple of interesting design decisions on you.

The first thing I ran into was that all of the objects being mapped are required to have a visible default constructor, i.e. one that takes no parameters and is not private.  There are sound technical reasons behind this restriction but it did run against the way I had set up my domain.  In the end I settled for having my default constructor protected for the mapping and my normal constructor public for the users of the domain.  I would like to see an option to specify a mapping to a non default constructor though I'm not sure how feasible this would be to add to the library.

The second thing required of my domain classes was that all of the properties I was mapping had to be virtual.  This seems a little odd at first suggestion but it is how you enable NHibernate to perform some of it's more advanced functions such as using proxies and lazy loading.  The extra keyword on each property makes negligible difference and is possibly a good idea in some cases anyway.  Apparently it is possible to disable this restriction if you are willing to sacrifice some functionality.

So yes, you can write persistence ignorant domain classes, but be prepared to still make some small concessions.  In some ways I question whether these requirements are a dependency in disguise but because they are based on the fundamentals of .Net, they are general enough not to bother me.  It seems like the only way we are going to get total freedom from the database is by letting go of our tried and trusted statically typed languages.

Flexible Mappings

Most of my ORM experience has been with older or simpler tools where the structure of your objects is really determined by how you lay out your SQL tables.  Though it's certainly not unique in this regard, NHibernate gives you plenty of mapping options which let you have distinctly different models for your domain and database objects.

One pleasing feature is the ability to map a custom concept in your domain, such as a class called Kilograms, to one or more SQL columns within a table, such as an integer.  This allows you to provide a very strong domain model while still maintaining that automatic mapping back to the basic SQL types.  Doing this does require creating a small mapping object derived from IUserType but the pay off is worth it in my case.  I need to explore a little more in this area because I suspect much of the IUserType implementation is generic is the simple cases.

Though I haven't used it yet there is also an ability to map part of a SQL table to a separate class to help simplify large objects.  The usual example is mapping columns such as Street, Suburb and City to and Address object.

Session Integrity

One of the reasons I hadn't looked into the library was based on faulty assumptions that it would have the same flaws other ORM products I used had.  In past projects a common source of weird an unusual behaviour has been the data in the database not keeping up to date with changes that had been made to the data in memory.  A simple example is a query to select all items not including new items that have been created but not committed yet.

NHibernate refers to those in memory copies of the data as the current session and solves the problem by automatically flushing any changes to the database whenever it detects these sorts of issues may arise.  This means as long as you are using transactions, which you should be, you shouldn't have any issues.  You also get a couple of niceties along with it such as generated primary keys being updated as soon as you make NHibernate aware of new objects.

NHibernate, Good Times

Overall a big thumbs up from me and I will continue to use NHibernate in future.  I'm especially interested to see the upcoming version which is expected to include LINQ querying support.
Wednesday, October 08, 2008 8:16:29 AM (GMT Daylight Time, UTC+01:00)  #    Disclaimer  |  Comments [0]  | 
# Tuesday, September 23, 2008

Lately I've deleted a number of half finished posts and not put much live so this bit of advice is for myself...  stop rambling.  If I can't keep myself interested long enough to actually finish writing the posts there's no way you lot are going to read them.  Most of the missing posts have been the longer essay type that stray from technical issues into pure dribble about software development politics.  These tend to be the posts that make my eyes glaze over when reading other technical blogs which is a bad sign.

In future I will stick to posts that are either technical, short and / or ridiculous.  In case you were wondering here is a short list of titles you've missed out on:

  • University sucks, I'm a better teacher (and modest too)
  • BOOB (an essay on the pitfalls of Building Out Of the Box)
  • Stop f*cking doing that (a tribute to dumbasses everywhere)
  • Agile (our excuse for everything)

If you do want to hear more from me I now have both RSS and Email subscriptions running as you can see in the top right of the page.  RSS is probably the better option but Email works well for those that aren't mashing it up already.

I'd also be interested to hear about what effect blogging has had on peoples writing and communication skills, could it be beneficial in general?

Tuesday, September 23, 2008 10:58:58 AM (GMT Daylight Time, UTC+01:00)  #    Disclaimer  |  Comments [0]  | 
# Saturday, September 06, 2008

As you can see I am currently upgrading this blog from the Blogger platform to dasBlog.  Most things seem to be working OK and the content is all in tact so I'm happy.  The main reason I'm moving away from Blogger is to get more control over the site.  There are quite a few changes I will be making here over the next few weeks and having the blog as a real ASP.Net application will make this much easier.  I had a few issues getting to this point so if you ever want to make this move read on to save yourself some pain.

64bit dasBlog and IIS7

Both my development machine and my web host are running 64bit IIS7.  This causes issues with the default distribution of dasBlog as it relies on a 32bit DLL for it's date picker and does not work in IIS7's new integrated pipeline mode.  If you want to know all the details of why this happens Scott Hanselman talks about it in his post on migrating dasBlog to 64bit.

Unfortunately the link Scott provides no longer lists the 64bit version of the DLL however it is included in the source distribution of dasBlog.  Look in the lib folder for BasicFrame.WebControls.BasicDatePicker.dll.64bit.  I have recompiled dasBlog with the new DLL but have not yet updated my web.config to deal with the new integrated pipeline.

Importing Content From Blogger

My biggest concern about the upgrade was whether the content would survive.  As you can see it's gone pretty well but there were a few hiccups.  I used the utility provided by Nick Schweitzer to process the content.  He provides instructions on getting Blogger to export your blog to a nice XML format and they almost work.  Fortunately Nick provides the source to his utility so I was able to make a couple of small tweaks.

The first problem was since Blogger still thinks it's exporting HTML it does not correctly encode   for us.  A simple string replace to convert these characters to   did the trick.  The second problem was that Blogger exported dates in month/day/year format but Nicks code was (correctly) using the culture set on my machine which expected day/month/year format.  I added a single line of code to force the culture to en-US and everything worked fine.

Work Left To Do

There is one more thing left to move away from Blogger and that is all my images.  Once this done I'll be working through all the site settings, making sure things are set up as I want.  I also need to check the RSS feeds are working and that FeedBurner has picked them up.

This is my first post to the new blog and I'm using Windows Live Writer so hopefully everything goes smoothly...

Saturday, September 06, 2008 3:27:38 AM (GMT Daylight Time, UTC+01:00)  #    Disclaimer  |  Comments [1]  |