Archive for the ‘.NET’ Category
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.
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
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 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.
- 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.
- C# WebServer is an open source project on CodePlex. It’s been around for two years, but the pace of development seems slow.
- 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.
Visual Studio 2008 and the CopyLocal setting
Though the Microsoft marketing drums have begun beating to the rhythm of Visual Studio 2010, most of us workaday code monkeys are still using Visual Studio 2008. And while VS 2008 is a great IDE for development — especially once you add ReSharper — it has a few configuration quirks that drive me up the wall.
Most of these quirks are hidden from the typical developer and only appear once you try to package and deploy your software. It’s the dreaded Works on My Machine syndrome.
And if there’s one Visual Studio build configuration setting that causes me to scream in anguish, it’s the CopyLocal property.
Feel my pain
When you add a reference to another .dll in Visual Studio 2008, some default settings get applied.

The CopyLocal setting on the reference properties panel.
Here’s how the settings look after I added log4net to one of my projects. As you can see, the CopyLocal setting is set to True. Or is it?
If you move your solution to your build server, you might be surprised to find that CopyLocal isn’t actually copying the .dll. I was certainly surprised to find that my builds failing for inexplicable reasons.
It took me a while to figure out that Visual Studio 2008 is a dirty liar when it comes to CopyLocal. Let’s have a look at our .csproj file, shall we? You can load the XML in the .csproj file by following these directions.
Ah, there’s the contents of our csproj file. And there’s our reference to log4net, but…

Where's the CopyLocal setting?
The CopyLocal setting isn’t there! Within the log4net reference, we should see an XML element called Private. It should look like this:
-
<Private>True</Private>
But it’s clearly not there. Uh oh.
And because it’s not there, it might work on your machine but not on other machines. Even though the Visual Studio IDE represents CopyLocal as a Boolean value, it’s actually a ternary value. Where Booleans have two states, usually represented as True/False, Yes/No, or 1/0 pairs, ternary logic has three states:
- True
- False
- Um… uh… Other?
Yikes! That’s a classic interface failure mode.
It turns out that the default for the CopyLocal setting is… something not quite True and not quite False. If you read the documentation for how to set the CopyLocal property, it mentions the weird logic Visual Studio uses to determine what the “default” should be. Argh.
Manual repairs
To fix the problem, we reload our project in Visual Studio again. Then we toggle the CopyLocal setting from “not quite True, exactly” to “False” and then back to “totally, literally True”.
With apologies to the Violent Femmes, when I say CopyLocal, you best CopyLocal, motherf***er!!!
And now it’s really, truly TRUE. Honest. Take a look at our .csproj file now.

This is how CopyLocal=True ought to look.
And there it is, the CopyLocal setting. The way it should be. The way it should have been all along.
Conclusion
I don’t know whether Visual Studio 2010 fixes this problem. I haven’t looked at the VS 2010 Beta release to find out. I’m too busy manually editing all my .csproj files to get our Infovark builds working. But I really, really, really hope that the folks at Microsoft have done something to address the problem.
Here’s the simple interface design rule: If it isn’t a Boolean setting, it shouldn’t look like a Boolean setting.
Unless of course, you want to make the pages of The Daily WTF.
Validation in Domain Driven Design
There’s a great discussion on Jeff Palermo’s blog about entity validation patterns. Jeff takes the position that your domain objects (or entities) should not have validation logic “baked-in” to the class itself. Instead, you should separate the validation routines into separate classes that you can use to validate the object on demand.
There are two advantages to this approach. The first is that you can use different validators for the same object in different circumstances. For example, the validation you might perform prior to storing the domain object in a persistence layer could be different than the validation routine used to validate input from the GUI layer.
The second advantage is that separating the validation logic from the data itself makes it easier to work with ORM or serialization frameworks. Most of these frameworks encourage the use of Plain Old Objects, that is, objects without special attributes or interfaces that help with these mapping and serialization tasks. (See Wikipedia’s article on Plain Old Java Objects, for example.)
Those are powerful arguments, but I’m still not convinced.
Trade-offs
As a practical matter, Jeff’s advice is sound. It’s much easier to move business logic into the helper classes that surround your entity model. You get better tool support and more flexibility. But there’s two things about his approach that bother me. Judging by some of the excellent comments on his article, other programmers are bothered by them as well.
First, stripping away behavior from your domain objects is a recognized anti-pattern in object oriented code. Martin Fowler calls it the Anemic Domain Model. It harkens back to the days of procedural programming, where data and business logic were strictly separated. If you’re an OO purist, this is a red flag.
From an OO perspective, the need to validate the same object in different ways suggests that what you actually need to do is create more objects. Rather than pass a stripped-down data-transfer object (DTO) all the way from your data storage layer up to your GUI, you should have a bunch of intermediate objects to help transition the data and enforce proper behavior.
But I’m not an OO snob. Writing a whole bunch of extra classes to move information between tiers in my application is a hassle. I’ve done it before, and we’re doing it now with Infovark, but for most projects it just isn’t justified. Especially if you have to wrestle with various application frameworks to deal with correctly modeled but more complicated domain objects.
The second objection I have is that if we follow Jeff’s advice, we have to accept that bad data will creep into our domain. Jeff knows that this is a hard sell. It’s why he titled his article “The fallacy of the always-valid entity.”
Whew. That’s rough. That requires a whole different programming mindset. What about the problem of Garbage In, Garbage Out? Can we really create programs robust enough to handle business objects that might, at any moment, contain meaningless gibberish?
I don’t know. For now, as appealing as Jeff’s idea is, I’ll stick to always-valid approach. What do you think?
Review: Framework Design Guidelines
I’m almost embarrassed to admit that I really enjoyed Framework Design Guidelines by Krzysztof Cwalina and Brad Abrams. I mean, it’s a book about coding standards.
Maybe I ought to get out more… but before I leave the glare of my monitor behind, I’ll type up my review.
Code is literature, not language
Computing languages, just like human languages, have grammar and syntax. There are correct ways to form sentences and paragraphs, with well-defined rules (and exceptions). Just like word processors can check spelling and verify basic sentence structure, most IDEs today can ensure your code will compile and run.
That doesn’t mean that your story or program is an easy or enjoyable read, though. Most newspapers have accumulated extensive guidelines for matters of style and substance, and most software companies have their own guides as well. If you’re writing as part of a team project, or writing programs intended to be used by other programmers, it’s important to make your code consistent, clear, and direct.
Just like many journalists keep a copy of The Associated Press Stylebook or the New York Times Manual of Style and Usage handy — even if they don’t actually work for the New York Times or the AP — lots of programmers keep a copy of Microsoft’s Framework Design Guidelines as reference.
Or they should. That’s probably my roots as a maintenance programmer showing.
Know your genre
Ideally, you’d want any code you write for other Windows programmers’ use to look as if it came from Microsoft itself. That is, you want it to feel like a natural extension of the .NET framework and not some third-party bolt-on with odd stylistic touches. You’d also like your code to use the full power and expressiveness of .NET, and not appear like some watered-down Java-esque port. (Far too many open source projects retain awkward Java-isms after being converted to .NET, in my opinion. NUnit is a notable exception.)
This helps your fellow programmers gain a better understanding of your code in less time. And it can also make your programming tasks easier, too. Just like design patterns can help you lay out your application architecture, programming guidelines can help you structure your code at the class or method level.
About the book
The Framework Design Guidelines covers a lot of ground in its 400 pages. It describes what conventions Microsoft uses when designing types, methods, and exceptions. It also describes the naming and design patterns that Microsoft uses in their public APIs. The topics are grouped by category and heavily cross referenced, making it easy to find your way around. The rationale of each guideline is explained, and the authors indicate the strength of each recommendation by marking it with the terms Do, Consider, Avoid or Do Not.
But the best part of the book is the stories and comments given by members of the Microsoft team. These are sprinkled throughout the book and give insight into why the guideline exists. Some of these discuss lessons Microsoft learned the hard way, places in the .NET Framework where the rules are violated, and how real-world programmers feel about certain guidelines. You can get a flavor of these by checking out the Framework Design Guidelines section of Brad Abrams‘ blog.
If you find his posts interesting or helpful, you’ll feel the same way about the book. Highly recommended.
Visual Studio 2008 and its CopyLocal setting
Our build server wasn’t producing the same results as our local development machines. The same C# code yielded two different sets of code libraries. After much head-banging and hand-wringing, we finally traced the problem to an obscure error in the way Visual Studio 2008 handles .csproj files.
Basically, the Visual Studio IDE doesn’t handle the CopyLocal setting properly. This post from paraesthesia set us on the right track.
I have no idea what caused the problem. We had the same versions of the .NET Framework and Visual Studio 2008 installed on all our machines. The code was exactly the same. Apart from the build machine being Windows Server 2003 and out development machines being Windows XP, I can’t think of any other differences. But somehow the code libraries weren’t getting copied in the same way.
Just another adventure on our way toward the Beta release…
