Archive for the ‘.NET’ Category

Reflecting on reflection in .NET

I cringe whenever I spot code that uses System.Reflection. It’s a powerful weapon in our arsenal of .NET programming techniques — and a dangerous one.

In two previous posts, I talked about the misuse of dependency injection and the problems with the service locator pattern. I should include factories among the list of dangerous patterns too.

These patterns get overused in many .NET frameworks and toolkits. Some of that stems from a desire to avoid complex configuration. Some of it comes from the natural envy programmers in stuffy statically typed languages feel regarding their freewheeling counterparts using dynamically typed languages.

(Wikipedia has a good article exploring the differences in type checking in computer language type systems, if you’re curious about the different paradigms. But I digress.)

On reflection

System.Reflection two main uses, as Marc Gravell points out in his answer regarding what problems Reflection solves on StackOverflow:

  1. Investigating type information
  2. Metaprogramming

These two capabilities allow you to shoehorn dynamic or late-binding features into C# applications. In other words, it’s a clever hack.

Want to enable Ruby-style convention over configuration in your C# framework? Use reflection! Want to reach into private or internal methods for unit testing? Use reflection! Want to add some duck typing goodness to your statically typed language? Use reflection!

But on further reflection

The System.Reflection API has some big drawbacks. The performance penalty incurred by reflection is well known. Less well known is that the Reflection API is really difficult to use, especially when inspecting and creating constructor method parameters. So most framework developers skip the hard bits.

This means that most of these frameworks will insist on your using constructors without parameters in your classes. (Sometimes people call parameter-less constructors “default constructors” though it isn’t the same thing.)

But if you can’t use parameters in the constructors of your objects, you’re doing object-oriented programming with one hand tied behind your back.

For example, it’s difficult to achieve object immutability without using a constructor. You’ll also have a hard time enforcing business rules without constructors. And if you’re a fan of dependency injection, you’ll have to implement it via Init() methods or property setters, both of which can cause significant headaches.

So if you work with a framework or API that makes heavy use of reflection, and thus restricts the sort of constructors you use, prepare yourself for significant pain.

The Service Locator pattern is the new global variable

Mark Seeman, author of an upcoming book about dependency injection, writes that Service Locator is an anti-pattern. He shows several code examples illustrating the difficulty of configuring and troubleshooting various implementations of the Service Locator pattern. His observations tally with my thoughts about the awkwardness of service locator implementations.

As I was wrestling with yet another third-party software component that made heavy use of an inversion-of-control (IoC) container, I realized that service locators are the new global variable.

Global variables are a code smell and should be used sparingly.

This means that you should use a service locator only as a last resort, not as the default way of wiring bits of your application together.

And if you’re using an IoC container, make sure that you are using it to inject dependencies through your object constructors, rather than calling its static Resolve() methods from within your classes.

Avoiding the “new”

In January, Robert Martin posted an article about the overuse of dependency injection in many open source frameworks. At the time, I had only an academic interest in the subject. (And Uncle Bob’s rants are always a fun read.)

But that was before I started taking a look at several open source frameworks for WPF. Now I’m feeling ranty too!

Dependency Injection is an important principle of software design, but it can be abused. My biggest concern with overusing inversion-of-control (IoC) containers is that it makes learning a framework ten times harder than it needs to be.

First, you can’t tell precisely when an object gets created. Sure, it’s nice that your framework provides control over the lifetime of objects, but this should be an optional feature for advanced scenarios. Not every solution requires lazy loading. Sometimes a simple “new” will do.

Second, by placing all the wiring and object discovery in the container or service locator, you hide important information about how the framework components fit together. Yes, the global object factory knows what classes go with what types, but you don’t. That information is hidden among all the framework plumbing.

For similar reasons, Microsoft cautions against using factory methods in place of constructors in its Framework Design Guidelines:

Prefer constructors to factories, because they are generally more usable, consistent, and convenient than specialized construction mechanisms.

I think that goes double for dependency injection and IoC containers. Eliminating constructors makes for less readable code. I can’t tell what classes other classes depend on to do their jobs.

My errors should get thrown from my code

Sure, IoC containers are great when everything gets wired together automagically. But when an error occurs, I want it to be thrown from my code, as close to the source of the error as possible. (Like Jeff Atwood, I assume it’s always my fault.)

Instead, frameworks that overuse dependency injection throw most of these setup, configuration, and instantiation from its internal IoC container, usually with some horribly generic error message.

Then it’s up to me to find which dependency failed to resolve, which constructor failed to bind, or which concrete implementation didn’t get registered. And in order to do that, I have to go spelunking in the framework code — which I don’t know well — rather than the code I was trying to write, which I know quite well.

Frameworks that rely on dependency injection and IoC containers practically require you to have the framework source available and for you to become an expert in its mysterious inner workings. If I need to step through the framework code or use reflector on it, the framework has failed me.

This is exactly what Uncle Bob was decrying in his article. I don’t want to become an expert in the XYZ framework for ABC. I just want to get my stuff done.

Check out proposed enhancements to .NET core classes

Almost two years ago, I wrote a post expressing my frustration with the way that .NET handles long filenames. Yesterday, the Base Class Library (BCL) team at Microsoft announced that they have launched a BCL CodePlex site to gather feedback on proposed enhancements and extensions to core .NET components.

One of the first four features on preview is a new Long Path wrapper class, which will hopefully make some of the awkward hacks we’ve used in the past obsolete. Hooray!

The code is available for download, and they have documentation and samples as well.

I plan on giving the new Long Path class a thorough test drive.

3 Useful Visual Studio Tricks for Spark Templates

This issue on the Spark discussion board inspired several tweaks to my Visual Studio setup. Gordon and I have found these quite useful, so we’d thought we’d share them here.

Spark template file icons

First, I made a couple registry files to give Spark templates a spiffy icon.

Visual Studio gets its icons from the same registry setting used in Windows Explorer. So all we need to do is register the file extension and associate it with a default icon.

I found a free-for-noncommercial-use “S”-shaped lightning bolt icon and used the instructions in this StackOverflow question to create the necessary registry entries.

Add an icon for Spark templates in Visual Studio 2008

Add an icon for Spark templates in Visual Studio 2008

You can download the SparkFile.zip package I created from Codeplex. Place the .ico file in C:\Program Files\Spark, and run the two .reg files, and you’ll have a nifty spark icon inside Visual Studio.

(All the usual caveats apply regarding modifying your registry.)

Visual Studio template

Next, I created an item template to use in the Visual Studio Add New Item menu, using this guide to creating item templates.

You can download my SparkVSTemplate.zip package from Codeplex as well. Place the SparkVSTemplate.zip file in My Documents\Visual Studio 2008\Templates\ItemTemplates\Visual C#\Web and you’ll be able to create a basic template from the VS menu. You don’t need to unzip it.

HTML syntax highlighting

Finally, I wanted to apply the standard syntax highlighting used for HTML pages.

In Visual Studio 2008, go to Tools | Options, then choose Text Editor, then associate files ending in .spark with the HTML editor.

Set up Spark View Engine templates to use the HTML Editor in Visual Studio 2008

Set up Spark View Engine templates to use the HTML Editor in Visual Studio 2008

This will set all the colors properly. Unfortunately, it will also flag any Spark-specific attributes or elements as HTML validation errors. I figure this is a small price to pay for proper syntax highlighting.

What’s missing?

I’d really like to get intellisense working for Spark. Though I tried the Visual Studio Integration Package, it won’t work right outside of VS Web projects. Syntax highlighting seems like the best I can do for the moment.

If you’ve got other tips and tricks for using Spark inside Visual Studio, I’d love to hear them.

Introducing the SparkServer Project

It’s less than two weeks since I began my experiment using the Spark View Engine with C# WebServer. Even though it’s put a kink in our development schedule, I’m confident it was the right move. It’ll save us a lot of time in the long run.

After posting messages to the Spark project and C# WebServer project forums, I decided there was enough interest to make sharing my integration code worthwhile.

You can find it at: http://code.google.com/p/sparkserver/

If you’d like to participate in the project, please let me know. Comments, suggestions, and especially fixes are always welcome!

Better ways to Encode HTML in C#

Our move from Windows Communication Foundation to C# WebServer once again raised the difficult question of HTML character encoding.

Since we’re not using Microsoft IIS, we wanted to avoid a dependency on System.Web, which has the popular but flawed HttpUtility.HtmlEncode() method.

In my research, I discovered Rick Strahl’s post about Html and Uri String Encoding without System.Web. He points out the problems and inconsistencies in the mainstream encoding methods available in the .NET framework, and ultimately decided to roll his own encoding method.

But in this StackOverflow question on HTML Encoding in C#, several folks suggested using Microsoft’s anti-cross-site scripting library, AntiXSS.

After spending some time working with the library, it seems like just the thing to solve the problem of web encoding.

The AntiXSS Library includes helpful methods for encoding HTML, URLs, JavaScript, and XML. It’s based on a secure whitelist model, so anything not allowed in the specifications is prohibited.

Microsoft has made the source of AntiXSS 3.1 available on Codeplex (http://antixss.codeplex.com/), but you can also get the official release of AntiXSS direct from Microsoft. It includes a sample application and thorough documentation.

It’s exactly the solution I was looking for.

Using Spark View Engine with C# WebServer

I mentioned that we were looking for an IIS alternative that we could embed within our Infovark client installation.

After weighing the options, we decided to move forward with the C# WebServer. Instead of using one of the two rendering engines currently included in the WebServer project, though, we’ve decided to use the Spark View Engine instead.

Spark has a clean template syntax that makes HTML tags stand out. It also has the most sensible design for creating master layout templates I’ve seen. I think it’ll be fairly straightforward to convert our existing XSLT templates into Spark syntax.

Integrating Spark with the C# WebServer will be a challenge, though. Much of the existing Spark documentation assumes you’ll be using the Spark.Web.Mvc classes. Since the C# WebServer project has its own lightweight MVC framework, we’ll need to build our own integration classes.

The C# WebServer project has a way to add alternative template engines, but the hooks provided don’t look like a clean fit with Spark. I think it’ll take some tinkering to get the two to work together seamlessly.

I’ll post some messages to the discussion boards at both open source projects. If you’re interested in helping out with the effort — or would be interested in the results of the project — leave a message in the comments or send an email to info@infovark.com.

Looking for an IIS Alternative

One year ago it became clear that Infovark had outgrown the Windows Communication Foundation (WCF).

We’d decided to use WCF because we wanted Infovark to provide web services, and we liked the fact that we could deploy WCF to client machines. Since WCF is built directly on top of HttpListener, a core part of the Microsoft .NET Framework, we wouldn’t need to use System.Net or Microsoft IIS.

But we’ve struggled with WCF for a variety of reasons. First, we wanted to use a REST model for our web services, and WCF’s support for REST architectures lags behind its SOAP support.

Second, there’s no easy way to return HTML from WCF. We tried transforming our XML with XSLT and returning the XHTML results as a Stream. This works, but the programming experience is frustrating.

Last, because of the previous two reasons, we were left with a website that was way too rigid and programmer-like. It didn’t feel like an organic website. The tool we’d picked was forcing us to compromise on our website design goals.

Infovark’s primary mission is to help human beings, not other computers. That means that the look and feel of the web interface should be our number one priority. Awesome web services are nice to have, but happy users are more important.

Web server alternatives

So for the past few months, we’ve been hunting for an alternative web server. We can’t use IIS because its footprint is too heavy. Most IT departments won’t allow us to install IIS on client machines.

We could use Apache. It has a nice embeddable version, but interacting with it via C# is tricky. We’d prefer something a little more Microsoft-native.

That basically leaves us with one commercial option and two open source options.

  1. UltiDev Cassini is a commercial product that’s been around for some time. We’re sure it could do the job, but the licensing model is cost prohibitive.
  2. C# WebServer is an open source project on CodePlex. It’s been around for two years, but the pace of development seems slow.
  3. Open Rasta is the brain child of Sebastien Lambda, an open source framework for the development RESTful development of web sites and services. It’s been getting a lot of attention recently.
  4. Kayak is a promising open source project, but it hasn’t reached its first public release yet.

(If you know of other web servers worth investigating, please let us know in the comments!)

Making the switch

More important than picking an alternative web hosting framework for Infovark is the timing of the switch. We don’t want to impede future development.

As a stopgap, we might try plugging in the Spark View Engine to replace our current XML-XSLT-XHTML rendering path. Who knows? If it improves our web development flow, we might be able to keep our WCF base after all.

Getting Up to Speed on Windows Installer

In our past jobs, Gordon and I worked as part of larger technical teams. As developers, we never had to worry about the installation routine. It’s a highly specialized area of software development. We had people to do that job for us.

Fortunately I’d had a little experience working with InstallShield but that mainly involved stepped through the wizard and trying not to adjust settings that I didn’t understand. (Which meant most of the settings.)

Working on Infovark, we’ve had to absorb a crash course on Windows Installer. Windows Installer is the official Microsoft sanctioned technology for deploying applications to Windows. If you want to get the compatibility logo on your product, you must use Windows Installer or a tool that generates Windows Installer compatible .MSI files.

Windows Installer has been around for a long time, going back to at least 1998. Version 1.0 shipped with Office 2000. In the time since, it’s gone through many changes and revisions. If you didn’t “grow up” with the technology over the years, it’s a daunting challenge to get up to speed.

We figured our best bet was to pick a software package to help us build our MSI files. But since we didn’t know Windows Installer very well, it was hard to evaluate which one to use.

The best place I found for information about Windows Installer and setup and deployment tools is InstallSite. Finding my way around was a bit tricky, but there’s lots of good information there.

I also found an awesome series of articles written by Robert Flaming about UAC and Windows Installer. There are a few stray articles not included in his table of contents: UAC in MSI.

The series describes the slow evolution of User Account Control and per-user settings from Windows 95 to the present. This helps put all the hacks and kludges in context.

This long history is what makes creating good software installation routines on Windows difficult, especially if you want to support multiple versions of the operating system. The differences between Windows XP and Windows Vista are particularly large.

So if you’re planning to deploy your software to the desktop, make sure to include a lot of time in your development budget for research, testing and troubleshooting. It’s harder than you think.