comments edit

David Meyer recently published a .NET class library that enables duck typing (also sometimes incorrectly described as Latent Typing as Ian Griffiths explains in his campaign to disabuse that notion) for .NET languages.

The term duck typing is popularly explained by the phrase

If it walks like a duck and quacks like a duck, it must be a duck.

For most dynamic languages, this phrase is slightly inaccurate in describing duck typing. To understand why, let’s take a quick look at what duck typing is about.

Duck Typing Explained

duck-rabbit-philDuck typing allows an object to be passed in to a method that expects a certain type even if it doesn’t inherit from that type. All it has to do is support the methods and properties of the expected type in use by the method.

I emphasize that last phrase for a reason. Suppose we have a method that takes in a duck instance, and another method that takes in a rabbit instance. In a dynamically typed language that supports duck typing, I can pass in my object to the first method as long as my object supports the methods and properties of duck in use by that method. Likewise, I can pass my object into the second method as long as it supports the methods and properties of rabbit called by the second method. Is my object a duck or is it a rabbit? Like the above image, it’s neither and it’s both.

In many (if not most) dynamic languages, my object does not have to support all methods and properties of duck to be passed into a method that expects a duck. Same goes for a method that expects a rabbit. It only needs to support the methods and properties of the expected type that are actually called by the method.

The Static Typed Backlash

Naturally, static typing proponents have formed a backlash against dynamic typing, claming that all hell will break loose when you give up static typing. A common reaction (and I paraphrase) to David’s duck typing project goes something like

Give me static types or give me death!

Now I love compiler checking as much as the next guy, but I don’t understand this attitude of completely dismissing a style of programming that so many are fawning over.

Well, actually I do understand…kinda. So many programmers were burned by their days of programming C (among other languages) and its type unsafety which caused many stupid runtime errors that it’s been drilled into their heads that static types are good, just, and the American way.

And for the most part, it’s true, but making this an absolute starts to smell like the monkey cage experiment in that we ignore changes in software languages and tooling that might challenge the original reasons we use static types because we’ve done it this way for so long.

I think Bruce Eckel’s thoughts on challenging preconceived notions surrounding dynamic languages are spot on (emphasis mine).

What I’m trying to get to is that in my experience there’s a balance between the value of strong static typing and the resulting impact that it makes on your productivity. The argument that “strong static is obviously better” is generally made by folks who haven’t had the experience of being dramatically more productive in an alternative language. When you have this experience, you see that the overhead of strong static typing isn’t always beneficial, because sometimes it slows you down enough that it ends up having a big impact on productivity.

The key point here is that static typing doesn’t come without a cost. And that cost has to be weighed on a case by case basis against the benefits of dynamic languages.

C# has used duck typing for a long time

Interestingly enough, certain features of C# already use duck typing. For example, to allow an object to be enumerated via the C# foreach operator, the object only needs to implement a set of methods as Krzystof Cwalina of Microsoft points out in this post

Provide a public method GetEnumerator that takes no parameters and returns a type that has two members: a) a method MoveNext that takes no parameters and return a Boolean, and b) a property Current with a getter that returns an Object.

You don’t have to implement an interface to make your object enumerable via the foreach operator.

 

A Very Useful Use Case For When You Might Use Duck Typing

 

If you’ve followed my blog at all, you know that I’ve gone through all sorts of contortions to try and mock the HttpContext object via the HttpSimulator class. The problem is that I can’t use a mock framework because HttpContext is a sealed class and it doesn’t implement an interface that is useful to me.

Not only that, but the properties of HttpContext I’m interested in (such as Request and Response) are sealed classes (HttpRequest and HttpResponse respectively). This makes it awful challenging to mock these objects for testing. More importantly, it makes it hard to switch to a different type of context should I want to reuse a class in a different context such as the command line. Code that uses these classes have a strong dependency on these classes and I’d prefer looser coupling to the System.Web assembly.

The common approach to breaking this dependency is to create your own IContext interface and then create another class that implements that interface and essentially forwards method calls to an internal private instance of the actual HttpContext. This is effectively a combination of the composition and adapter pattern.

The problem for me is this is a lot more code to maintain just to get around the constraints caused by static typing. Is all this additional code worth the headache?

With the .NET Duck Typing class, I can reduce the code by a bit. Here’s some code that demonstrates. First I create interfaces with the properties I’m interested. In order to keep this sample short, I’m choosing two interfaces each with one property..

public interface IHttpContext
{
  IHttpRequest Request { get;}
}

public interface IHttpRequest
{
  Uri Url { get;}
}

Now suppose my code had a method that expects an HttpContext to be passed in, thus tightly coupling our code to HttpContext. We can break that dependency by changing that method to take in an instance of the interface we created, IHttpContext, instead.

public void MyMethod(IHttpContext context)
{
  Console.WriteLine(context.Request.Url);
}

The caller of MyMethod can now pass in the real HttpContext to this method like so…

IHttpContext context = DuckTyping.Cast<IHttpContext>(HttpContext.Current);
MyMethod(context);

What’s great about this is that the code that contains the MyMethod method is no longer tightly coupled to the System.Web code and does not need to reference that assembly. Also, I didn’t have to write a class that implements the IHttpContext interface and wraps and forwards calls to the private HttpContext instance, saving me a lot of typing (no pun intended).

Should I decide at a later point to pass in a custom implementation of IHttpContext rather than the one in System.Web, I now have that option.

Yet another benefit is that I can now test MyMethod using a mock framework such as RhinoMocks like so…

MockRepository mocks = new MockRepository();
IHttpContext mockContext;
using (mocks.Record())
{
  mockContext = mocks.DynamicMock<IHttpContext>();
  IHttpRequest request = mocks.DynamicMock<IHttpRequest>();
  SetupResult.For(mockContext.Request).Return(request);
  SetupResult.For(request.Url).Return(new Uri("http://haacked.com/"));
}
using (mocks.Playback())
{
  MyMethod(mockContext);
}

You might wonder if I can go the opposite direction. Can I write my own version of HttpContext and using duck typing cast it to HttpContext? I tried that and it didn’t work. I believe that’s because HttpContext is a sealed class and I think the Duck Typing Project generates a dynamic proxy that inherits from the type you pass in. Since we can’t inherit from a sealed class, we can’t simply cast a compatible type to HttpContext. The above examples work because we’re duck type casting to an interface.

With C#, if you need a class you’re writing to act like both a duck and a rabbit, it makes sense to implement those interfaces. But sometimes you need a class you didn’t write and cannot change (such as the Base Class Libraries) to act like a duck. In that case, this duck typing framework is a useful tool in your toolbox.

Technorati tags: Duck Typing, Dynamic Languages, C#, Dynamic Types

comments edit

Not too long ago, Jeff Atwood lowered the overall productivity of software developers everywhere when he wrote about Desktop Tower Defense, a game that he calls fiendishly addictive.

I chose not to play the game as I had too much going on. But now I have family visiting and my brother (Hey Brian!) introduced me to yet another fiendishly addictive flash game, Line Rider. Damn you brother!

It’s not even really a game in the sense that there’s no objective other than to build really cool courses. It’s quite similar to a physics drawing tool. You simply start drawing lines and hit play to watch a some little dude with a red scarf sled down your course.

engin2.162.swf (applicationx-shockwave-flash Object) - Mozilla
Firefox(2)

The tools themselves are simple. You have a free-hand pencil tool and a line tool. There are 3 colors of lines you can draw.

  • Blue - Draws a line where the sledder can sled at a normal pace.
  • Red - Draws a line that accelerates the sledder.
  • Green - Draws a line that doesn’t affect the sledder.

Using this simple set of tools, you can create some very interesting courses across a limitless canvas.

I was quite pleased with myself for executing a loop-de-loop until my brother showed me some of the amazing stuff that people have put together on YouTube like these two videos:

Sadly, I am completely hooked.

comments edit

UPDATE: Using Coral CDN to serve up my images and stylesheets ended up being a mistake and actually slowed down my site. I’d recommend using Amazon S3 instead if you need high bandwidth fast serving of static content. Coral CDN is probably better for cases when you want to serve up a large file (mp3, mpeg, etc…) and save on your bandwidth usage. It doesn’t seem ready to be a general purpose CDN for speeding up your site. I’ll add the ability to this code to use S3. In the meanwhile, this code is still useful by simply restricting the extensions in the config file to perhaps this list “mpg,mp3,mpeg,wmv,avi,zip”. Hat tip to Jon Galloway for pointing that out.

Yahoo recently released the ever so popular YSlow add-on for Firebug used to help locate bottlenecks for web pages. From their developer network site we learn…

YSlow analyzes web pages and tells you why they’re slow based on the rules for high performance web sites. YSlow is a Firefox add-on integrated with the popular Firebug web development tool. YSlow gives you:\

    * Performance report card\     * HTTP/HTML summary\     * List of components in the page\     * Tools including JSLint

YSlow provides a nice report card for your site. Here you can see the unfortunate grade my blog gets at the time of this writing.

Haacked.com YSlow
Score

Naturally I couldn’t just sit there while some unknown Yahoo disdainfully gives my blog an F. I decided to start digging into it and start attacking specific items.

I decided to start with #2 Use a CDN which stands for Content Distribution Network. The Yahoo YSlow help page has this to say about CDNs.

A content delivery network (CDN) is a collection of web servers distributed across multiple locations to deliver content more efficiently to users. The server selected for delivering content to a specific user is typically based on a measure of network proximity. For example, the server with the fewest network hops or the server with the quickest response time is chosen.

That certainly sounds useful, but the CDNs listed by Yahoo include Akamai, Mirror Image Internet, and LimeLight Networks. These might be great for big companies like Yahoo, but they’re a bit cost prohibitive for small fries like us bloggers.

Coral to the Rescue

That’s when I remembered the Coral Content Distribution Network. Jon Galloway wrote about this a long time ago as a means to save on bandwidth. The one fatal flaw at the time was that the network only worked over port 8090. Fortunately, that little issue has been corrected and Coral now works over port 80.

And the wonderful thing about Coral is that it’s trivially easy to use it. All you have to do is append your domain name with **.

So this:

http://example.com/my/really/big/file.mpeg

becomes

http://example.com.nyud.net/my/really/big/file.mpeg

And now your really big file is being served up by hundreds of geographically distributed servers. You just need to keep that file on your server at the original location so Coral can find it when adding it to its network.

Tell YSlow about Coral

By default, YSlow doesn’t recognize Coral as a CDN, which means implementing Coral CDN won’t affect your YSlow grade. YSlow only recognizes the CDNs in use by Yahoo. Fortunately, it’s pretty easy to add Coral to the list. Just follow these steps:

  1. Go to about:config in Firefox. You’ll see the current list of preferences.
  2. Right-click in the window and choose New and String to create a new string preference.
  3. Enter extensions.firebug.yslow.cdnHostnames for the preference name.
  4. For the string value, enter the hostname of your CDN, for example, nyud.net. Do not use quotes. If you have multiple CDN hostnames, separate them with commas.

Here’s a screenshot of the domains I added to YSlow. I’m sure I’ll think of more to add later.

YSlow CDN
Configuration

How can I automate this?

You knew I wasn’t going to write about this without providing some means for automating this conversion, did ya? There are two approaches I could take:

  1. Rewrite URLs to static files on incoming posts.
  2. Rewrite URLs on the way out.

The first approach rewrites the URL as you are posting content to your blog. This has the distinct disadvantage that should you decide to change the distribution network, you need to go through and rewrite those URLs.

The second approach rewrites the URLs as they are being output as part of the the HTTP response. The issue there is to do it properly requires buffering up the entire output (rather than letting IIS and ASP.NET stream it) so you can perform your regex replacements and whatnot. This can impair performance on a large page.

I decided to go with option #1 for now for performance reasons, though option #2 would be quite easy to implement. I wrote an HttpModule in the same style as my Windows Live Writer crap cleaner which rewrites an incoming MetaWeblog API post to append nyud.net to the domain.

The code here only works with Windows Live Writer and BlogJet (untested in the latter case) but can be easily modified to allow posts for any blog client (I just got lazy here) by modifying the user agent within the method IsMetaweblogAPIPost.

The reason I didn’t write this as a WLW plugin is that it’s not yet possible to hook into pipeline and rewrite content just before WLW posts it to the blog. That may be coming in the future though, according to this comment by Joe Cheng of the WLW team.

Download and Use It

You can download the code here (binaries are included in the bin dir) in a project called HtmlScrubber. I simply added this HttpModule to the same code as the WLW Crap Cleaner module mentioned earlier. To use it simply add the following to your web.config.

<httpModules>
  <add type="HtmlScrubber.CoralCDNModule, HtmlScrubber" 
    name="CoralCDNModule" />
</httpModules>

This filter works by looking at the file extension of a referenced file. If you’d like to change the list of extensions, you can add the following configuration.

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
    <section name="CoralCDNConfigSection" 
      type="HtmlScrubber.CoralCDNConfigSection, HtmlScrubber" 
      allowDefinition="Everywhere" 
      allowLocation="true" />
  </configSections>
  
  <CoralCDNConfigSection 
    extensions="mpg,mp3,mpeg,wmv,avi,zip" />
</configuration>

The list of extensions shown are the default, so you don’t need to add this configuration section unless you want to change that list. Please enjoy and let me know if you put this to good use. Hope this makes your blog faster than mine.

As for me, I’m moving on to looking into using JSMin, JSLint, and merging CSS files etc…

Technorati tags: WLW, Windows Live Writer, YSlow, Firebug, Performance, Web Development

comments edit

Joe Cheng, member of the Windows Live Writer team, just unveiled his first publicly available Windows Live Writer plugin…

I’ve just released my first (publicly available) Windows Live Writer plugin: Dynamic Template. It lets you write mini-plugins from snippets of C# and HTML, and reuse them within Windows Live Writer.

It’s sort of a meta-plugin plugin. He has a screencast on how to use it, but I’ll post a few screenshots of it in action here.

The plugin adds a new Insert Template option in the sidebar.

Insert Template
Option

Clicking on this brings up a dialog with a list of templates.

Insert
Template

Click New to bring up the template editor. I’m going to create one for wrapping sections of html with the <code></code> tags.

First, I’ll name the template.

Naming the New
Template

Then I’ll edit the template. Since this template just adds HTML around a selection and doesn’t require that I ask for user input, I don’t need to create a variable.

Editing the
Template

And now I can just select some text, click on Insert Template… and double click Code. Nice!

Another useful template is one that Joe calls Htmlize.

Edit Template
Htmlize

As you can see, you can call some functions from within a template. This one is useful for converting something like <sup>blah</sup> into ^blah^ while in the Web Layout or Normal mode.

Watch Joe’s Screencast for a demo of a template that takes in user input as part of the template. There’s also some documentation located here. This is a pretty handy plugin that’ll be great for automating a variety of html snippets I use often.

Technorati tags: Windows Live Writer, WLW, Plugins

comments edit

Run, don’t walk, over to .NET Rocks and download their interview with yours truly (as in me, not any other yours truly).

I had a real blast chatting with Carl Franklin and Richard Campbell. We covered all my favorite topics (well except soccer) which include Software Development, Open Source, and Subtext!

I’m still here in Redmond on the Microsoft campus so I haven’t had the cringeworthy experience of listening to myself talk. ;)

Technorati tags: .NET Rocks, Subtext

comments edit

A coworker of mine ran into some problems using WATIN to test our website. Specifically issues with Javascript and AJAX. Yes, I know there’s Selenium out there, but I hoped for something we could run from within NUnit/MbUnit, so that it’s nicely and easily integrated into our build process and development environment.

He did a bit of digging and found this free web automation infrastructure product by Art Of Test Inc. called WebAii (they also have a blog). It seems to do everything we want and more. Check out some of these features (the full feature list is much longer).

  • Supports IE and Firefox
  • Supports DOM actions and pure UI Mouse/Keyboard actions for Ajax Testing
  • For ASP.NET testing, you can use an In-Process Host for fast browser-less testing without a webserver
  • Use ASP.NET Development Server (aka Cassini) to run tests without IIS
  • Use name, id, xpath identifications. (Need to see if they support Regex too)
  • Unit test your JavaScript by calling JS methods from your .NET code.
  • Extensions for NUnit and VS Team Test (I’ll ping them to build one for MbUnit)

These are just a small sampling of the many features. It sounds like this would be a killer web testing app. Does anyone have experience with it?

We’re going to evaluate it and I’ll keep you posted, but I thought I’d mention it here because it sounds great.

Features I’d Like To See In A Web Unit Testing Tool

  • Ability to set the UserAgent and Referrer
  • Ability to set request headers
  • Ability to hook into and verify the status of a redirect. For example, if a page redirects, I want to be able to assert that the HTTP Status code for the redirect

Technorati Tags: Unit Testing, TDD, Web Testing, Web Automation, WATIN, WebAii

comments edit

I mentioned I’ll be at the Microsoft campus next week. Scott Koon (aka LazyCoder) pinged me about meeting up for a drinky drink and geeky geek conversation and Sunday works best for him.

Anyone have a good recommendation for a place to get a good drink in or near Redmond? Perhaps BillG’s hidden stash on campus? Anybody want to join us? I think 10 or 10:30 PM works for me.

It’s standard procedure for me to roll into the morning session of a conference completely sleep deprived and trashed from the previous night’s celebrations. It just wouldn’t be right to not continue that tradition.

I’m also free Monday night as far as I know.

Technorati tags: Redmond, Bar, Drink, Recommendations

comments edit

Image from This is Broken:
http://www.goodexperience.com/tib/archives/2004/03/microsoft_campu.html Working at a VSIP partner has its privileges. I’ll be up in Redmond at the Microsoft Campus for a two day VSIP Partner Meeting on August 5^th^ and August 6^th^. We’ll be looking at ways to make the Koders Visual Studio plugins provide a great and well integrated experience.

I’m flying into Seattle on that Sunday to spend time with some friends and do a bit of sightseeing (oh look, that’s what rain looks like!). Hopefully my schedule won’t be too full so I can butt my head in a few offices here and there to bother folks and stir up trouble.

August 7

This is more of a state of mind than a physical location as I’ll be making an appearance on DotNetRocks! I hope you enjoy it.

October 27th and 28th

I’ll be speaking on Writing Automated Unit Tests for your Website with WATIN at the Silicon Valley Code Camp. This’ll be my first time speaking at a Code Camp so wish me luck. I wanted to give two talks, but decided to take it easy for my first time.

November 6-9

I’ll be in attendance and on two panels at the DotNetNuke OpenForce conference. I’ve mentioned this one already in my blog. I’m pretty excited about this one.

Technorati tags: Open Source, Microsoft, DNN, DotNetRocks

comments edit

First, let me start off with some praise. I really really like Windows Live Writer. I’ve praised it many times on my blog. However, there is one thing that really annoys me about WLW, it’s utter disregard for web standards and the fact that injects crap I don’t want or need into my content.

Of particular annoyance is the way that WLW adds attributes that are not XHTML compliant. For example, when you use the Insert Tags feature, it creates a div that looks something like:

<div class="wlWriterEditableSmartContent" 
  id="guid1:guid2" 
  contenteditable="false" 
  style="padding-right: 0px; display: inline; padding-left: 0px; 
  padding-bottom: 0px; margin: 0px; padding-top: 0px">

What’s the problem? Let me explain. 

  1. First of all, the ID is a GUID that starts with a number. Unfortunately XHTML doesn’t allow the id of an element to start with a number.
  2. The contenteditable attribute is not recognized in XHTML.
  3. The style tag is superfluous and unnecessary. At the very least, it should have been reduced to style=”padding:0; display: inline;”

The purpose of the special class and the contenteditable attribute is to inform WLW that the html tag is editable. In the Web Layout view (F11), you can see a hashed box around the tags like so.

image

Clicking on the box changes the right menu to let you enter tags.

image

Because I actually care about web standards and being XHTML compliant and I’m totally anal, I’ve always gone in and manually changed the HTML after the fact.

Today, out of pure laziness and getting fed up with this extra work I have to do, I decided to write an HttpModule to do this repetitive task for me via a Request Filter. A Request Filter modifies the incoming request.

But to make things interesting, I made sure that the HttpModule makes the changes in an intelligent manner so that no information is lost. Rather than simply removing the cruft, I moved the cruft into the class attribute. Thus the HTML I showed above would be transformed into this:

<div class="wlWriterEditableSmartContent id-guid1:guid2 
  contenteditable-false">

Notice that I simply removed the style tag because I don’t need it.

I also created a Response Filter to modify the outgoing response when the client is Windows Live Writer. That allows the module to convert the above html back into the format that WLW expects. In that manner, I don’t break any WLW functionality.

Other Cool Cleanups

Since I was already writing this module, I decided to make it clean up a few other annoyances.

  • Replaces a single   between two words with a space. So this is cool gets converted to this is cool.
  • Replaces <p> </p> with an empty string.
  • Replaces an apostophre within a word with a typoghraphical single quote. So you can’t say that becomes you can’t say that.
  • Replaces atomicselection=”true”with an empty string. I don’t re-insert this attribute back into the content yet, as I’m not sure if it is even necessary.

Try it out!

This module should work with any ASP.NET blog engine that uses the MetaWeblog API. It only responds to requests made by Windows Live Writer, so it shouldn’t interfere with anything else you may use to post to your blog.

To use it is as easy as dropping the assembly in the bin directory and modifying your web.config to add the following to the httpModules section:

<httpModules>
  <add type="HtmlScrubber.WLWCleanupModule, HtmlScrubber" 
    name="HtmlScrubber" />
</httpModules>

I’m also including the source code and unit tests, so feel free to give it a try. Please understand that this is something I hacked together in a day, so it may be a bit rough around the edges and I give no warranty. Having saidthat, I’m pretty confident it won’t screw up your HTML.

I have plans to add other features and cleanups in the future. For example, it wouldn’t be hard to add a configuration section that allows one to specify other regular expressions and replacement patterns to apply.

If you have any “cleanups” I should include, please let me know. If you’re reading this post, then you know the module worked.

[Download Binaries] [Download Source]

I thought about adding this to CodePlex, but I’m hoping that the next version of Windows Live Writer makes this module irrelevant. I’m not holding my breath on that one though.

Technorati tags: WLW, Windows Live Writer, ASP.NET

comments edit

A year ago on this day, I wrote a blog post about the demise of NDoc and issued a challenge for users of Open Source Software to contribute to their favorite projects.

So I offer the following challenge. First, ask yourself these two questions:
  1. How much money do I save because of Open Source Software?
  2. Considering how many people spend three bucks for a useless ring tone, is a single dollar too much to contribute to a useful Open Source project?

So let’s ban together and declare today, July 26, 2006, Contribute To Open Source Day.

In looking back at my original challenge, I now believe the emphasis I placed on monetary contribution to be slightly misguided. While I agree to that monetary contributions are helpful for infrastructure support costs (hosting websites, build servers etc…), there are many other means of contributing that are even more valuable, if you have the time. Money is just the easiest way to contribute.

Consider the following options…

  1. Contribute a bug fix
  2. Help verify bug reports
  3. Submit a unit test to help provide code coverage
  4. Test
  5. Write documentation
  6. Submit feature requests
  7. Help answer questions in the forums
  8. Tell the developers how much you appreciate the product

I think #8 is often lost in the shuffle. I’m quick to submit a bug report, but I forget to tell the developers of a fine product such as WinMerge how much I appreciate the product.

There are many projects that could use your help. For example, Andrew Stopford just announced a request for developers willing to help MbUnit out. What a great opportunity to work on some really cool code.

Subtext is always looking for contributors, especially now that my commit frequency is down due to my wonderful newborn son. We could use new blood to help pick up the slack until my son cuts his teeth (once he has them) on C# and ASP.NET (or perhaps IronRuby by then).

So again, please consider contributing to Open Source today in whatever way, shape, or form you see fit. This is not a plea to guilt you into it. Rather, consider this a friendly reminder for those of you who would do so anyways, but forget to due to busyness, like myself.

comments edit

Microsoft just unveiled a new web property intended to clarify its position on Open Source as well as provide a one-stop location to find out what Microsoft is doing in the Open Source space.

Despite all the (perhaps well deserved) criticism of how Microsoft has not supported Open Source in the past, I think the behemoth is slowly starting to get it. Or at least groups within Microsoft are starting to see that if they don’t embrace Open Source, Microsoft will get left behind, much like they did for a while with the web revolution. Embracing Open Source makes good long term business sense for Microsoft.

As a big company, Microsoft moves slowly, but there are concrete signs of progress.

  • The Ms-PL License (Microsoft Permissive License)
  • The introduction of CodePlex
  • Port25, the Open Source Software Lab (ugly site, but chock full of info)
  • Sam Ramji, whose official title is Director of Platform Technology Strategy but is for all intents and purposes, the Director of Open Source at Microsoft and heads the Open Source Lab there.
  • Garret Serack who holds the title Open Source Community Lead at Microsoft.
  • And various informal shows of support.

Sure, there is much more to do and I’m sure many will remain skeptical and wary of Microsoft’s slow movement into this area. However, I see the signs of progress and believe there will be bigger things to come.

asp.net comments edit

ELMAH, which stands for Error Logging Modules and Handlers for ASP.NET, is an open source project which makes it easy to log and view unhandled exceptions via its pluggable architecture.

elmah

Having been around a while, a lot has already been written on it so I won’t rehash all that information. For more details, you can read the following:

All you need to know for the purposes of this post is that ELMAH is implemented as two key components:

  • An HTTP Module Used To Log Exceptions
  • An HTTP Handler for viewing Exceptions

In the sample web.config file that is included with the ELMAH download, the HTTP handler is configured like so:

<httpHandlers>
  <add verb="POST,GET,HEAD" path="elmah.axd" 
    type="Elmah.ErrorLogPageFactory, Elmah" />
</httpHandlers>

This allows you to view the error log from the URL http://your-site/elmah.axd. There’s one big problem with this…you do not want to deploy this to your production site.

This would allow any joker with a browser to view your exceptions and potentially gain information that would allow someone to hack your site.

Personally, I think that the sample web.config should have elmah.axd be secured by default. It’s quite easy to do. Here’s what I did:

First, I changed the HttpHandler section to look like this:

<httpHandlers>
  <add verb="POST,GET,HEAD" path="/admin/elmah.axd" 
    type="Elmah.ErrorLogPageFactory, Elmah" />
</httpHandlers>

Notice that all I did was add admin to the path attribute.

I then added the following location element to my web.config.

<!-- Deny unauthenticated users to see the elmah.axd -->
<location path="admin">
  <system.web>
    <authorization>
      <deny users="?"/>
    </authorization>
  </system.web>
</location>

IMPORTANT: It’s important to note that I’m securing everything in the admin directory and that I’m making sure that elmah.axd is served from the root /admin URL. If the httpHandler “path” element was just “admin/elmah.axd” or “elmah.axd” I could inadverdently expose Elmah information.

Troy Hunt has a great write-up of the perils of getting ELMAH configuration wrong. In his post he shows a more robust way to secure elmah.axd. Put the httpHandlers section within the location section.

<location path="elmah.axd">
  <system.web>
    <httpHandlers>
      <add verb="POST,GET,HEAD" path="elmah.axd" 
        type="Elmah.ErrorLogPageFactory, Elmah" />
    </httpHandlers>
    <authorization>
      <allow roles="Admin" />
      <deny users="*" />
    </authorization>
  </system.web>
  <system.webServer>
    <handlers>
      <add name="Elmah" path="elmah.axd" verb="POST,GET,HEAD"
        type="Elmah.ErrorLogPageFactory, Elmah"
        preCondition="integratedMode" />
    </handlers>
  </system.webServer>
</location>

To demonstrate this in action, I’ve created a solution containing a Web Application project with ELMAH and authentication fully implemented.

The point of this sample app is to demonstrate how to set this all up. So for example, the login page has a button to auto-log you in. In the real world, you’d probably use a real login form. You can also change the authentication from Forms authentication to Windows authentication depending on your needs. That might make sense in many scenarios.

The app demonstrates in principle how to setup and secure the elmah.axd page. If you have SQL Express installed, you should be able to compile and run the demo without any extra steps to see ELMAH in action.

[Download the demo]

comments edit

A little while back Scott Watermasysk, preparing for the arrival of his first child, asked for advice on finding a really good compact digital camera.

Funny how having a kid turns a geek’s thought to getting that perfect camera to capture the moment. It was exactly what I did (but after Cody was born) when my wife and I purchased a Canon PowerShot SD850 IS Digital ELPH for Father’s day.

The image
“http://ec1.images-amazon.com/images/I/41HO%2Bdjnm8L._AA280_.jpg”
cannot be displayed, because it contains
errors.Yeah, that’s a bit of a mouthful for a camera name, but the two letters that were important to me were I and Swhich stands for Image Stabilization.

The SD850 combines that with a sensitivity range up to ISO 1600 for better photos in low light, a real problem area with my previous camera due to its suckiness and my incredibly shaky hands. Seriously, you don’t want me doing surgery on you.

833729001_7c7808a0c5The other key features I was looking for was small in size (3.6 x 1 x 2.2 inches) so I can get all secret agent with it and face detection, for better portraiture.

So far, I’m very happy with it. The pictures have been very sharp with good color. I should have known to stick with the ELPH series as my first ELPH took great photos despite only being 2.2 megapixel.

This one boasts 8 megapixels (really more than I need) and 4x optical zoom. That there on the right is a picture of my son in a Brasil jersey given to him by my wife’s Brazillian coworker. Doesn’t he look sharp?

Now you know why Brazil just beat the heavily favored Argentina in the Copa America. Cody Power!

comments edit

One surefire way to sound really really smart is to invoke a law or principle named after some long dead guy (an alive guy is acceptable too, but lacks slightly in smart points).

hammurapisThis realization struck me the other day while I was reading a blog post that made a reference to Postel’s law. Immediately I knew the author of this post must be a highly intelligent card carrying member of MENSA. He was probably sporting some geeky XKCD t-shirt with a lame unix joke while writing the post.

Well friends, I admit I had to look that law up, and in the process realized I could sound just as scary smart as that guy if I just made reference to every eponymous (I’ll wait while you look that one up) “law” I could find.

And as a public service, I am going to help all of you appear smart by posting my findings here! Don’t let anyone ever say I don’t try to make my readers look good. If you look good, I look good.

Make sure to invoke one of these in your next blog post and sound scary smart just like me.

Postel’s Law

The law that inspired this post…

Be conservative in what you send, liberal in what you accept.

Jon Postel originally articulated this as a principle for making TCP implementations robust. This principle is also embodied by HTML which many attribute as a cause of its success and failure, depending on who you ask.

In today’s highly charged political environment, Postel’s law is a uniter.

Parkinson’s Law

Otherwise known as the law of bureaucracy, this law states that…

Work expands so as to fill the time available for its completion.

As contrasted to Haack’s Law which states that

Work expands so as to overflow the time available and spill on the floor leaving a very sticky mess.

Pareto Principle

Also known as the 80-20 rule, the Pareto Principle states…

For many phenomena, 80% of consequences stem from 20% of the causes.

This is the principle behind the painful truth that 80% of the bugs in the code arise from 20% of the code. Likewise, 80% of the work done in a company is performed by 20% of the staff. The problem is you don’t always have a clear idea of which 20%.

Sturgeon’s Revelation

The revelation has nothing to do with seafood, as one might be mistaken to believe. Rather, it states that…

Ninety percent of everything is crud.

Sounds like Sturgeon is a conversation killer at parties. Is this a revelation because that number is so small?

The Peter Principle

One of the most depressing laws in this list, if you happen to have first-hand experience with this via working with incompetent managers.

In a hierarchy, every employee tends to rise to his level of incompetence.

Just read Dilbert (or watch The Office) to get some examples of this in action.

Hofstadter’s Law

This one is great because it is so true. I knew this law and still this post still took longer than I expected.

A task always takes longer than you expect, even when you take into account Hofstadter’s Law.

By the way, you get extra bonus points among your Mensa friends for invoking a self-referential law like this one.

Murphy’s Law

The one we all know and love.

If anything can go wrong, it will.

Speaking of which, wait one second while I backup my computer.

The developer’s response to this law should be defensive programming and the age old boy scout motto, Be Prepared.

Brook’s Law

Adding manpower to a late software project makes it later.

Named after Fred Brooks, aka, Mr. Mythical Man Month. My favorite corollary to this law is the following…

The bearing of a child takes nine months, no matter how many women are assigned.

Obviously, Brook was not a statistician.

Conway’s Law

Having nothing to do with country music, this law states…

Any piece of software reflects the organizational structure that produced it

Put another way…

If you have four groups working on a compiler, you’ll get a 4-pass compiler.

How many groups are involved in the software you are building?

Kerchkhoff’s Principle

This principle is named after a man who must be the only cryptographer ever to have five consecutive consonants in his last name.

In cryptography, a system should be secure even if everything about the system, except for a small piece of information — the key — is public knowledge.

And thus Kerchkhoff raises the banner in the fight against Security through Obscurity. This is the main principle underlying public key cryptography.

Linus’s Law

Named after Linus Torvalds, the creator of Linux, this law states…

Given enough eyeballs, allbugsare shallow.

Where you store the eyeballs is up to you.

Reed’s Law

The utility of large networks, particularly social networks, scales exponentially with the size of the network.

Keep repeating that to yourself as you continue to invite anyone and everyone to be your friend in FaceBook.

Metcalfe’s Law

In network theory, the value of a system grows as approximately the square of the number of users of the system.

I wonder if Reed and Metcalfe hung out at the same pubs.

Moore’s Law

Probably the most famous law in computing, this law states…

The power of computers per unit cost doubles every 24 month.

The more popular and well known version of Moore’s law states…

The number of transistors on an integrated circuit will double in about 18 months.

And we’ve been racing to keep up ever since.

Rock’s Law

I was unable to find Paper’s Corollary, nor Scissor’s Lemma, so we’re left with only Rock’s law which states…

The cost of a semiconductor chip fabrication plant doubles every four years.

Buy yours now while prices are still low.

Wirth’s law

Software gets slower faster than hardware gets faster.

Ha! Take that Moore’s Law!

Zawinski’s Law

This law addresses software bloat and states…

Every program attempts to expand until it can read mail. Those programs which cannot so expand are replaced by ones which can.

I hear that the next version of calc.exe is going to include the ability to read email. A more modern formulation of this law should replace email with RSS.

Fitt’s Law

This is a law related to usability which states…

Time = a + b log~2~ ( D / S + 1 )

Or in plain English,

The time to acquire a target is a function of the distance to and the size of the target.

A well known application of this law is placing the Start menu in the bottom left corner, thus making the target very large since the corner is constrained by the left and bottom edges of the screen.

Hick’s Law

Has nothing to do with people with bad mullets. I swear. Related to Fitt’s law, it states that…

The time to make a decision is a function of the possible choices he or she has.

Or in plain math,

Time = b log~2~(n + 1)

Seems to me this is also a function of the number of people making the decision, like when you and your coworkers are trying to figure out where to have lunch.

comments edit

Have you ever wanted to take a look at the internals of the .NET Framework? Sure you can (and should) fire up Reflector and see the Base Class Libraries, but what about the fully commented source code? What about the parts implemented in C++?

A while back, Microsoft released the Shared Source Common Language Infrastructure (aka the SSCLI aka Rotor). This is a fully working implementation of the ECMA CLI standard and ECMA C# language specification. So it’s not quite the entire framework, but it is still quite a bit of code.

Traditionally, to look at this code you would download the compressed archive and play around with it locally.

Development-CostBut if you want to just quickly browse the code, you can view all of its nearly three million lines of code on its project page on Koders.com.

Wouldn’t it be fun to compare that development cost estimate with the real number? I doubt Microsoft is interested in disclosing that information.

To search within this project, you just need to set the search scope.

For example, here are the search results for DateTime and here is the page with the DateTime implementation complete with comments.

Koders - datetime.cs - Windows Internet
Explorer

Other Great Projects to Look At

I mentioned a couple of great projects to look at over on the Koders blog, but here are some other great projects of interest to me now included in the Source Code Index.

  • DotNetNuke
    • One of the largest open source projects on the .NET Framework.
  • Subsonic
    • Some think this project should be called Sublime for how it brings fun back to ASP.NET development.
  • Subtext
    • Of course I’m going to mention this!
  • PSP Development Tools
    • Because we all want to write the next great game for the Play Station Portable.

subtext, blogging comments edit

When summer arrives, many like to create a new look via a haircut or new threads. I prefer to change the look of my blog with a new design.

This here design took all of four hours to complete.

haacked-3.0-design

Well that’s not exactly true.

It took all of four hours of my time to complete (give or take a few).

You can probably see where I’m going with this if you’re one of the many to have read The 4-Hour Workweek: Escape 9-5, Live Anywhere, and Join the New Rich recently. Wondering what all the buzz was about I decided to go ahead and purchase the book to see for myself.

What I expected was yet another time management book dispensing tired advice on how to get more done in less time. Instead, the focus of this book, written by Tim Ferriss is all about being more effective with your time by cutting out the cruft. Don’t do more in less time, do less (more effectively) in less time.

In many respects, Tim is savage about cutting out time wasters in your life such as email and reading the newspaper. He’s also a big fan of mini-retirements and outsourcing your personal life. This book is not about time management, it’s really about lifestyle management.

The outsourcing theme is one that particularly resonates with me. When I first graduated from college, I used to always take my clothes to a fluff and fold. Some friends told me I should do it myself since it would “build character”. So would milking cows to gather my own milk, but nobody faults me for picking up milk from Trader Joes. I figured I’d rather spend that time playing soccer, so I would drop off the dirty clothes before soccer and pick up the clean, dry, and folded clothes right after. It felt like a perfect trade.

Fast forward and upon reading this book it occurred to me that I spend a lot of time doing things I either don’t like to do, or things I like to do but suck at. For example, I spent a lot of time trying to redesign my blog to create a unique and polished look, only to come up short. I realized I should look around for a designer interested in getting his own name out there that might give me a discount for a design in exchange for the promotion. This would allow me to spend that time building a strength of mine rather than banging my head against a weakness.

So after browsing various blog design sites I happened to stumble upon Scott Carnett over in Abilene, TX. After pitching him the idea, he was on board and excited to work on the design. I only found out after we started that he’s a Java developer by day and design is a little side thing he’s into. I had it in my head that he was full-time freelancer.

Not that any of that matters. I am very pleased with the design he has created and recommend him highly if you’re looking for a bit of design work. He was extremely pleasant to work with and provided a quick turnaround. I have a few other ideas for the future that I may collaborate with him on.

comments edit

sf-cca-vote A little while ago I pleaded with my readers to nominate Subtext for a SourceForge Community Choice Award.

The good news is that it worked! Subtext is one of the finalists for a Community Choice Award in two categories:

  • Best Project for Communications: The best project for talking to your friends or sharing information. Other nominees include - Miranda, Pidgin, and FileZilla.\
  • Most Collaborative Project: The project most likely to accept your patches and value your input. Other nominees include - Azureus, XOOPS, and Zimbra.

That’s some heady competition we’re up against.

As far as I know, Subtext is one of only two .NET projects to be nominated overall, the other being a corporate sponsored application (not that there’s anything wrong with that).

Why Am I Politicking This?

So here’s the deal. Competitions like this are not about choosing the actual best project. There’s just no way that there are developers out there who have worked on every project in these categories and knows for a fact that Subtext communicates with its users better than FileZilla (we do).

I am fully aware that this is purely a popularity contest. Heck, I voted for 7-Zip in almost every category because of how useful I find it, not because I know for a fact that it has the Best Technical Design (it probably does).

As I just wrote, I think that despite the short rift that .NET gets in the broader Open Source Community, it is a great platform for Open Source development.

If you agree, please vote for Subtext and spread the word. I think it’d be neat to have a .NET project (especially one that starts with an “S”) as a community choice winner. Voting ends on July 20^th^. Thanks!

comments edit

I have a confession.

I am an Open Source developer and my platform of choice is the .NET framework by Microsoft. Not only that, I actually believe it is a good thing to support Open Source projects in the Microsoft ecosystem.

Yeah, really. In response to this tidbit, I have heard and am bracing to hear replies such as…

Why would you do that (support Open Source on Microsoft)?

Or

It can’t be Open Source if it’s on the Microsoft platform.

One rationale given is that it ain’t really Open Source unless the entire stack is Open Source. I call this the all or nothing view of Open Source.

the-stack

For example, one popular stack is the LAMP stack. That typically stands for Linux, Apache, MySql, and PHP, each of which are Open Source systems.

Interestingly enough though, the stack appears to end with the software layer. For example, proprietary hardware running the LAMP stack does not invalidate the Open Sourceness of the stack.

In contrast, I have the vacation view of Open Source. While I would love to be on vacation all the time, I’m pragmatic and I’ll take as much as I can get. Some vacation is better than no vacation.

Think About The Developers

Besides, why should PHP scripters have all the fun? There are legions of developers gainfully and productively employed writing software using .NET. Why shouldn’t they get to experience some of the benefits of using Open Source software?

So what if their stack is proprietary. Is it so wrong that these developers are more productive because of tools like Log4Net? Don’t they deserve a bit of Open Source spice in their lives?

But You Lose Out On Freedom!

There are as many flavors of Open Source as there are “developers!” in a Ballmer speech. But what they all share in common is some level of Freedom. In general, the freedom to view and change the code.

The only difference is really in the level of freedom and how that freedom should apply. I wrote before in my guide to Open Source Licensing that with some licenses such as the GPL, the freedom of access to the code is paramount. Any code that makes use of the GPL must itself be Open Source and licensed in a compatible fashion as the GPL.

Whereas with licenses such as the new BSD or MIT license, the freedom of the user of the code is paramount. There are pretty much no restrictions to using the code, even within proprietary systems.

Despite these philosophical differences, most reasonable people agree that they both constitute subsets of Open Source software.

I Have Freedom Where I Most Need It

The stack that I use with Subtext might be called WISC which consists of Windows, IIS, SQL Server, and C#. It sounds like a board game that Elmer Fudd might play on the weekends. Pretty much every layer of that stack is proprietary software. This is where the vacation view comes into play.

On this stack, I’ll never be able to view the Windows source and recompile it with a bug fix. But in truth, I’ll probably never have the need (nor capability) to do so. Often, the part I do need to change on a day to day basis is much higher up the stack. It’s the stuff that more directly applies to my business needs. It’s software like Lucene.NET that I’m more likely going to tweak and build a business on top of it.

This isn’t to say I wouldn’t mind being able to view the source for Windows, but it’s a balancing act. On the one hand, I like Open Source software. On the other hand, I like to feed my family by being productively employed and the Microsoft platform is great for being employed. Sure there are plenty of PHP and Ruby jobs, but I honestly really like writing C# code and the tools available to do so.

Only A Moron Thinks It’s An OxyMoron

In the end, I hold firmly to the belief that .NET is a viable platform for Open Source software. It might not meet everyone’s expectations for what Open Source is supposed to be, but it’s a good thing to many people and it is here to stay.

If you don’t believe me, just look at the list of projects mentioned in the comments to this CodingHorror post. You’ll see that Open Source in the Microsoft Ecosystem is more than just viable, it’s thriving and deserves to be recognized.

comments edit

microsoft-mvpI received an email today informing me that I’ve been awarded the status of Microsoft MVP in the Visual Developer - ASP/ASP.NET category. I was aiming for an MVP for non-visual developers, but my 57 Lynx readers didn’t have enough clout to make that happen.

What does it mean to be a Microsoft MVP? I’m not really fully sure yet. You can read the official blurb about the program here.

In general I think it means I get to use the above logo on my blog and may start blogging about the problems with the MVP program and how the standards aren’t what they used to be now that they let the riff-raff in.

Remember kids. Riff-raff are the people they let into an organization after you’ve been admitted.

In all seriousness though, I appreciate the honor and want to thank Rob Conery for initially nominating me and K. Scott Allen for also nominating me later.

comments edit

Last year when all the hubbub surrounding NDoc was happening, I tried to rally people around the idea of a Contribute to Open Source day on July 26^th^.

Why July 26?

Because I happened to write that post on that day.

coding-horror-official-logo-smallIn any case, it looks like Christmas will come early for some lucky open source projects. Jeff Atwood of CodingHorror fame is teaming up with Microsoft to donate $10,000 in support of open source .NET projects.

Go and nominate the open source project you find most useful in his comments.

What has spurred this recent largesse? Jeff is finally accepting a modest advertisement on his blog which will bring in enough revenue to help give back to the open source community. The hope is to help remedy the fact that…

open source projects are treated as second-class citizens in the Microsoft ecosystem

In the same manner that open source projects themselves are community led initiatives, it’s great to see other initiatives like this sprout from the community. While we may clamor for Microsoft to take a more active role in fostering OSS in the Microsoft ecosystem, we don’t have to wait around and do nothing in the meantime. We can take the lead like these other initiatives.

The good news is that Microsoft is showing itself to be supportive of such initiatives not only in spirit, but also financially.