Thursday, March 29, 2007

How to remove empty elements from an XML document

Since this is kind of universally useful, I recently was able to perfect a little snippet of XSL to remove empty elements from an XML document. This only removes elements that have no inner content or attributes. (In case you're wondering, I did this to handle special legacy XML documents for serialization.)


<?xml version="1.0" encoding="UTF-8" ?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output omit-xml-declaration="no" indent="no"/>
<xsl:strip-space elements="*" />
<xsl:template match="*[not(node()) and not(./@*)]"/>
<xsl:template match="@* | node()">
<xsl:copy>
<xsl:apply-templates select="@* | node()"/>
</xsl:copy>
</xsl:template>
</xsl:stylesheet>


And in case you're not familiar with how to apply XSL in .NET:

C#:

XmlDocument xsl = new XmlDocument();
xsl.LoadXml(XSL_REMOVE_EMPTY_NODES); // constant contains the XSL above

StringWriter writer = new StringWriter();
XslCompiledTransform transform = new XslCompiledTransform();
transform.Load(xsl);
transform.Transform(new XmlNodeReader(xml.doc), null, writer);
writer.Flush();

string transformedXml = writer.ToString();


VB.NET:

Dim xsl As XmlDocument = New XmlDocument()
xsl.LoadXml(XSL_REMOVE_EMPTY_NODES) ' constant contains the XSL above

Dim writer As StringWriter = New StringWriter()
Dim transform As XslCompiledTransform = New XslCompiledTransform()
transform.Load(xsl)
transform.Transform(New XmlNodeReader(xml.doc), Nothing, writer);
writer.Flush()

Dim transformedXml As String = writer.ToString()


You can also use a Stream or XmlWriter in place of a TextWriter like I have above. I just used a StringWriter since I needed a String for the final result.

Friday, March 23, 2007

"The project you are trying to open is a Web project. You need to open it by specifying its URL path."

I hate it when I get this error even when I am opening the project from a URL. Luckily, there's a simple solution.

In the same folder as the project file (.csproj or .vbproj) of the web project you are trying to open, make a new file with the same name as the project file with .webinfo tacked on the end.

Thus, if you have a project called MyWebProject.csproj, you create a new file called MyWebProject.csproj.webinfo. In that file, it needs a short XML snippet:


<VisualStudioUNCWeb>
<Web URLPath="http://localhost/MyWebProject/MyWebProject.csproj" />
</VisualStudioUNCWeb>


Obviously, you need to replace the URLPath value with the actual value for your web project file. Once you have this hint in place, Visual Studio should be able to load your web project without a hitch.

This seems to be Visual Studio .NET 2003 problem. I've not seen it manifest itself in Visual Studio .NET 2005 yet.

Sunday, February 4, 2007

Trust in ADO.NET

In reviewing some C# code for a project at work, I'm constantly running across the following construct in the code (and this is from different developers, not just one):


DataSet ds = SqlHelper.ExecuteDataSet(sConn, CommandType.StoredProc, sProc, aParams);
// ... snip ...
DataRow row = ds.Tables[0].Rows[0];
int someInt = Int32.Parse(row["intColumn"].ToString());


Now, while this code works like you would expect, there's still something wrong with it. You're basically wasting cycles on mindless conversions.

Whenever you use ADO.NET DataRow objects, it is true that the return from the indexer is a generic Object, so something needs to happen to get the result into a strongly-typed value. But, if the database column is a SQL int, ADO.NET already returned you an Int32!

What's written above is basically the same as this:


int a = 1;
int b = Int32.Parse(a.ToString());


You're wasting cycles first converting the Int32 to a String and then using Int32.Parse to get it back to the Int32 that it was in the first place. Trust in ADO.NET!


DataSet ds = SqlHelper.ExecuteDataSet(sConn, CommandType.StoredProc, sProc, aParams);
// ... snip ...
DataRow row = ds.Tables[0].Rows[0];
int someInt = (int)row["intColumn"];


There we go, much better. If you want something that feels a little "safer" than a direct cast, feel free to use Convert.ToInt32; it at least knows not to waste time doing needless conversions if it's already passed an Int32.

As a final thought, I'll leave you this completely failed code to think about:


DataSet ds = SqlHelper.ExecuteDataSet(sConn, CommandType.StoredProc, sProc, aParams);
// ... snip ...
DataRow row = ds.Tables[0].Rows[0];
bool someBool = (row["bitColumn"].ToString() == "1");


(Hint: The reason this code didn't work like the developer expected is because the DataRow already returned a Boolean.)

Merge Modules

In my previous post, I mentioned a method for automating the addition of features (specifically properties) to a Windows Installer package generated by Visual Studio. After doing some more research, I encountered the wonderful land of merge modules.

Merge modules are just what they sound like; they allow you to merge features into a Windows Installer package that you are creating. Among other things, you can set default properties by including a Property table in the merge module.

Creating a merge module is not difficult but requires a bit of knowledge. Once again, you need the lovely Orca tool from the Windows Platform SDK.

Orca, from what I found, doesn't seem to be able to create a blank merge module template. So I had to do it by hand. Starting with a blank new file, you will need to add the following schema:

TableColumnPKTypeNullable
ComponentComponentXString (72)N
ComponentId String (38)Y
Directory String (72)N
Attributes Short IntN
Condition String (255)Y
Key Path String (72)Y
DirectoryDirectoryXString (72)N
Directory_Parent String (72)Y
Default_Dir Local String (255)N
FeatureComponentsFeature_XString (38)N
Component_ String (72)N
ModuleComponentsComponentXString (72)N
ModuleIDXString (72)N
LanguageXShort IntN
ModuleSignatureModuleIDXString (72)N
LanguageXShort IntN
Version String (32)N


Some of these tables are predefined in Orca, so you won't need to enter all of them by hand. Most of the tables don't actually have to have data, they just need to exist for the file to be considered a valid merge module.

The only table that requires data is the ModuleSignature table. It must contain at least one row identifying the merge module. The format for the ModuleID is a GUID separated by underscores (_). The Language is 1033 for US English; you will need to look this code up if you are using other locales. Version is the typical Windows Installer version format: n.nn.nnnn.

Once you have that basic structure in place, you can enter your additions into the merge module. The merge module can have pretty much anything a full install package can have. Once you're done, save the file with a .msm extension. You can then go in to Visual Studio and add the merge module to your deployment project.

Technically, there is one more thing you really should have in your merge module: a _Validation table. While not strictly necessary for use, this table is used by Orca to run validation against the merge module.

One caveat I did find with using a merge module to preset properties in deployment project builds: you can't use a merge module to override existing entries in the Property table. You can only create new properties. I was able to get the majority of the setup I wanted done automatically, I still have to go in a manually edit my final .msi file to accommodate all of my requirements.

Monday, January 29, 2007

Working with Setup projects

One thing I don't have much experience with is the Setup project type in Visual Studio. Most of my previous experience comes from writing web applications, so there was no real need to write an installer package.

But now that I've been tasked over the past 6 months or so with writing a desktop application, I've had to learn a lot of new tricks. The Windows Installer is one of those tricks. Unfortunately, the documentation for the actual Setup project type itself is rather abysmal and mostly just links into documentation for the Windows Installer SDK.

So today I was trying to figure out how to set default values for my custom properties. Unfortunately, the interface inside Visual Studio has no means for doing this. I did some reading, and I found that the tool I want is called Orca.

Orca is part of the Windows Platform SDK. It's no small download, but it contains lots of useful tools and documentation, of which the Windows Installer SDK is a part. Orca is a handy little editor that lets you modify the tables inside a .MSI package (among other things).

To set defaults for my properties, I just compile my .MSI package as normal within Visual Studio. Then I can open it with Orca, go to the "Property" table, and create the properties I need.

One thing to note as well: the case of properties makes a difference. A property that is in all uppercase (like PROPERTYNAME) is considered a "public" property; public properties can be adjusted at install-time using command line switches, like follows:



msiexec /i Example.msi PROPERTYNAME=VALUE



A property with at least one lower case letter (like PropertyName) is considered "private" and cannot be modified at install-time by the user.

There's also another type of property you might find useful, called "restricted public." These are just like public properties, except that their values can only be modified by a system administrator. To make a restricted public property, just define it as a public property. Then, create a new property called SecureCustomProperties (or edit it if it exists). Set the value of this property to the names of the public properties you want to restrict, separated by semicolons if there is more than one.

Anyways, thats' the basic run-down. In the future I'm going to look into ways to automate this process.