Hugoware

The product of a web developer with a little too much caffeine

Archive for July 2010

Cobalt Progress

with 2 comments

CobaltMVC is coming along really well. I’ve been dog fooding it myself for the past few weeks in some projects and it fits nicely. I’ve discovered (and fixed) a lot of flaws and bugs along the way, so overall it has been a good experience.

I started a new site to be the dedicated home for CobaltMVC, which also happens to be on the same domain as my new website, at cobaltmvc.hugoware.com.

The site isn’t complete yet – I have a lot of documentation to write along with getting additional work done on my ‘personal’ part of the website, but overall it is a good example of what the finished site will look like.

Additionally, the site itself is powered by CobaltMVC… what a coincidence!

Written by hugoware

July 28, 2010 at 7:41 pm

Quirks Of Using For Each

leave a comment »

Collections can be tricky sometimes when you’re writing code. This is especially true when you need to modify them while you’re looping through them. Let’s look at a couple examples that can get you into trouble.

//create a typical list of items
List<string> items = new List<string> {
    "first", "second", "third", "fourth"
};

//now clear the list
foreach (string item in items) {
    items.Remove(item);
}

Of course, this won’t work. Why?

InvalidOperationException: Collection was modified; enumeration operation may not execute

Once our loop has started the boundaries of the collection have been defined. Adding or removing items will change those boundaries and create errors. Naturally, most languages aren’t going to like this and will crash.

Fortunately, we do get an Exception message (which is the best kind of error message). However, we should be more concerned about subtle problems that could arise if we change a collection while looping through it. For example, consider the ForEach method attached to Generic Lists…

//get a list of the employees that 
//should be deleted from the system
List<string> firedEmployees = new List<string> {
    "jeff", "blake", "steve"
};

//and delete them
firedEmployees.ForEach(employee => {
    EmployeeSystem.Delete(employee);
    firedEmployees.Remove(employee);
});

Everyone deleted? Nope…

I don’t know about you, but I was surprised to find that one employee remained on this list after the code was run (the second employee at that). ForEach made sure to keep track of our collection as it changed but unfortunately it created an undesirable result.

To take it a step further, if you were to add a new item each time then you’d end up with an infinite loop, an error that would be caught sooner but a problem all the same.

This straight forward code has potential for some serious problems.

So, abandon the framework! Move to Java! .NET is doomed!

…Or we can just write an extension method to take care of both problems at the same time.

public static class EnumerableExtensions {

    /// <summary>
    /// Safely enumerates through a collection
    /// </summary>
    public static IEnumerable<T> Each<T>(this IEnumerable<T> collection, Action<T> action) {

        //move the collection into its own list and
        //perform the work on each item
        collection.ToList().ForEach(action);
        return collection;

    }

}

The fix itself isn’t very impressive. One additional call to ToList() and we’re pretty much okay. But this does keep the original collection safe while we enumerate through the protected one.

Written by hugoware

July 22, 2010 at 11:03 pm

Almost Sorta Real Dynamic in .NET

with 8 comments

This post discusses the basics of writing your own dynamic type – If you’re interested in the finished code make sure to download the source.

The new dynamic keyword is a great way to create and modify a dynamic object in your .NET code – For example, check out this bit of code.

dynamic counter = new {
    sent = 0,
    received = 0
};
counter.sent++;

… Oh… wait… That doesn’t actually work…

That’s because even though you have an object declared as dynamic, it is still just the same old object it always was under the hood. Maybe not the dynamic utopia we were expecting. Seems like plain ol’ Reflection with a slightly cleaner syntax.

Bummer…

However, Microsoft was awesome enough to actually allow us to create our own dynamic types by simply inheriting from the DynamicObject class. This post looks at how we can create a semi-dynamic object by handling the binding methods ourselves.

[Source Code: Dynamic.cs]

Our goal is to create an object that we can add, remove and change values on the fly. It ends up being a little easier than we expect. Let’s look at the minimum code we are going to need to get started.

public class SimpleDynamic : DynamicObject {

    //contains the values to use
    private Dictionary<string, object> _Values = new Dictionary<string, object>();

    //handles getting values from our object
    public override void TryGetMember(GetMemberBinder binder, out object result) {
        //...
    }

    //handles assigning values to our object
    public override bool TrySetMember(SetMemberBinder binder, object value) {
        //...
    }

}

Note: If you downloaded the source code above you might be wondering why these examples don’t look the same. The source code is the complete Dynamic class while this post only goes over the basics of using the DynamicObject class.

In order to create our dynamic object we must handle getting and setting values. We can use a simple Dictionary<string,object> to hold our values until we need them.

//handles getting values from our object
public override void TryGetMember(GetMemberBinder binder, out object result) {
    return this._Values.TryGetValue(binder.name, out result);
}

//handles assigning values to our object
public override bool TrySetMember(SetMemberBinder binder, object value) {
    this._Values.Remove(binder.name);
    if (value is object) { this._Values.Add(binder.name, value); }
    return true;
}

Not much code, but now our dynamic object is a little more dynamic than it was before. We can now work with properties a lot easier.

//create the new object
dynamic simple = new SimpleDynamic();

//add and update some values
simple.red = "#f00";
simple.green = "#0f0";
simple.count = 10;
simple.add = new Action<int>(value => simple.count += value);

//and check the values
Console.WriteLine(simple.red); // #f00
Console.WriteLine(simple.green); // #0f0
Console.WriteLine(simple.count); // 10

//invoke methods
simple.add(5);
Console.WriteLine(simple.count); // 15

Of course this class isn’t that helpful since it’s only regular Dictionary without string indexes but it is interesting to see how you can make a ‘dynamic’ object with only a few lines of code.

As for the included source code, it has a few extra features that this class doesn’t have.

  • Use Anonymous Types directly to build out entire objects.
  • Support for the += operator.
  • Enumeration through member names.
  • String indexes (for both single and nested properties).

Here are a few examples the Dynamic.cs class can do.

//create using anonymous types (and nested anonymous types)
dynamic info = new Dynamic(new {
    name = "Hugo",
    age = 30,
    settings = new {
        color = "orange",
        homepage = "website.com"
    }});

//add values using +=
info.create = new { value = false; }
info.nested.value.allowed = 55;

//enumeration of properties
foreach(string prop in info) {
    Console.WriteLine("{0}: {1}", prop, info[prop]);
}

I’d caution against using this a lot in your projects, but it is really interesting to see the kind of control Microsoft has built into the new DynamicObject class.

[Source Code: Dynamic.cs]

Written by hugoware

July 15, 2010 at 12:32 am

Dead ASP.NET Debugger? It’s All About Location!

leave a comment »

I came across a weird issue working on some code this weekend. Everything had been moving along fine in my project but then I encountered a problem.

Of course, being a big fan of the debugger, I immediately placed a break point in the suspect line of code, pressed F5 and then… nothing.

No debugger, no breakpoint. Just generated markup rendered onto the the page…

Now this was a head scratcher. Could debug in other applications like Console applications. Even other websites were debugging fine. I dug through the project checking for anything that could be the culprit – but everything was turned on as it should be.

As it turns out, the location tag was the source of my grief.

The location tag is a very interesting element for your web.config files. It allows you to set special configurations for different sections of the same site or even inheriting web applications.

It doesn’t appear to be a tag that you use very often so it is possible that you’ve never seen it before. In my case I was using the inheritInChildApplications option so I could install other web applications into the same directory as the main site.

I’ve tried this in Visual Studio 2008 and 2010 with the same results. So if you happen to run into the problem then you might check that first.

So how do you fix this problem so that you can enable debugging and use the location tag…

… well… How?

Yeah, I haven’t figured out how you can fix this problem. As far as I can tell you can’t do much about it. My web.config was already applying the location to the entire site (like a wild card) so if that didn’t do the trick then I’m not entirely sure what will.

I’ll have to mess around with it might be possible to fix this using web.config transforms when you publish your site… I’ll test it and post if it worked or not later.

Written by hugoware

July 11, 2010 at 2:54 pm