Windows Vista Changes

Win32 No Comments »

The next version of Windows, Windows Vista, has a new security feature called User Account Control (UAC) (nee User Account Protection (UAP) nee Least-privileged User Account (LUA)), which basically means that users will no longer have full Administrator privileges by default. Microsoft has produced an overview of the new security features, a Developer Best Practices guide, and a blog to help inform developers about the upcoming changes.

If your application currently runs correctly as a non-Administrator, no development effort should be required for Vista. If you perform any privileged operations (such as writing to Program Files\ or opening a HKEY_LOCAL_MACHINE key in the registry with write privileges), your application will likely continue to work but the user experience may be suboptimal.

Here is how to perform some common development tasks while working in a least-privileged environment:

  • Need to read from a HKEY_LOCAL_MACHINE key in the registry? Use RegOpenKeyEx() (not RegOpenKey()) and request KEY_READ (not KEY_ALL_ACCESS) privileges.
  • Need to save per-user data which will roam with the user (i.e. may be replicated to the network)? Get the path to the Application Data\ folder by either retrieving the value of the environment variable %APPDATA% or calling SHGetFolderPath() with the parameter CSIDL_APPDATA. The recommended directory in which to store files appears to be %APPDATA%\<Vendor>\<Product>\, e.g. %APPDATA%\Microsoft\Office\.
  • Need to save per-user data which will not roam with the user (e.g. a web browser cache)? Call SHGetFolderPath() with the parameter CSIDL_LOCAL_APPDATA.
  • Need to save per-machine data (e.g. machine-wide game high scores)? Use %ALLUSERSPROFILE% or SHGetFolderPath() with the parameter CSIDL_COMMON_APPDATA.
  • Need a place to store a temporary file? Use %TEMP% or GetTempPath(). GetTempFileName() may also be useful.

To help with the transition, Microsoft’s Application Verifier may prove a useful tool.

Disabling Default XSLT Templates

XSLT No Comments »

As XSLT developers quickly learn, the W3C XSLT Recommendation requires for all XSLT processors to implement a number of built-in rules. Per the spec, these are the built-in rules:

<xsl:template match="* | /">
  <xsl:apply-templates />
</xsl:template>

All XML elements apply child templates recursively

<xsl:template match="* | /" mode="m">
  <xsl:apply-templates mode="m" />
</xsl:template>

All XML elements apply child templates recursively for every processing mode m

<xsl:template match="text() | @*">
  <xsl:value-of select="." />
</xsl:template>

All text nodes and attributes return the value of their contents

<xsl:template match="processing-instruction() | comment()" />

All comments and processing instructions are ignored

The net effect of these implicit rules is that an XSLT stylesheet without any templates defined will simply return the string values of all child elements in the XML document concatenated together. Attribute values are ignored because <xsl:apply-templates /> only applies to child elements and text nodes, not attribute nodes.

There are many instances where these default templates are useful, but I often find they mask bugs in my stylesheet (e.g. when I mistype a template match expression). Instead, I usually prefer that the stylesheet fails if it comes across an unanticipated XML element (hopefully loudly). I use the following XSLT fragment to achieve this behavior:

<xsl:template match="*">
  <xsl:message terminate="yes">
    <xsl:text>ERROR: Unhandled XML element: </xsl:text>
    <xsl:value-of select="name(.)" />
  </xsl:message>
</xsl:template>

When I desire the default apply-templates behavior, I add an explicit handler:

<!-- Enable default apply-templates behavior for these elements -->
<xsl:template match="/a/b/c | /a/d/e | ...">
  <xsl:apply-templates />
</xsl:template>

Data-Driven Programming

C, C++ No Comments »

While this is mentioned in an offhand way in the Assert Yourself chapter of Writing Solid Code by Steve Maguire (an excellent, if dated, read), consider using data-driven programming to simplify unwieldly if and switch blocks. For example, have you ever written code like this?

const char* GetString(int indx)
{
    if (indx == 1) {
        return "foo";
    } else if (indx == 2) {
        return "bar";
    } else if (indx == 3) {
        return "baz";
    } ...
}

The problem with this code is that it is repetitive, makes adding or changing entries difficult, and it can quickly get out of hand. For example, imagine trying to manage over 100 entries in this if block. Now imagine trying to change the indx search method, or the type of indx, or adding many other data points also searchable by indx.

To simplify, we can separate the action from the data by using data-driven programming — put the data into a data structure (I chose a static array, but you could use a binary tree, a hash table, or even an external file) and have the code search this data structure to determine the action to perform. For example:

#define ARRAYSIZE(x) ( sizeof(x) / sizeof(x[0]) )

struct GetStringEntry
{
    int indx;
    const char* str;
};

// These values should be set at compile-time, so no run-time
// costs of setting up the array (which may not be true for other
// data structures).
static GetStringEntry[] g_entries =
{
    { 1, "foo" },
    { 2, "bar" },
    { 3, "baz" },
    ...
};

const char* GetString(int indx)
{
    // Search for the entry with the correct index
    for (GetStringEntry* entry = g_entries;
         entry != g_entries + ARRAYSIZE(g_entries);
         ++entry)
    {
        if (entry->indx == indx)
            return entry->str;
    }

    // Handle error
}

Yes, there’s a lot of boilerplate code (much of which becomes unnecessary with other languages), but it allows great flexibility. Adding a record becomes trivial, and seeing the relationship between an individual indx and str is easy. Want to speed up searching g_entries? Make sure g_entries is sorted and use a binary search algorithm (such as STL’s lower_bound). Want to change indx to a string? Change the type of indx in struct GetStringEntry from an int to a const char*, the indx values in g_entries to strings, and the == comparison in GetString() to strcmp() — far less work than it would be for the original. Want to add another data point searchable by indx? Add a member to struct GetStringEntry, the new values to g_entries, and write another accessor function.

You can use this technique in even more complicated scenarios. For example, imagine a message dispatching system in which each struct contains the message identifier and a pointer to the function that will be executed when the message is received. Imagine searching for an entry by testing to see if the provided value has certain bits set (by using bitwise-and) rather than performing an equality comparison. Future maintenance programmers will thank you as they discover how easy it is to manage, add and modify records, and improve upon code which uses this technique.

How Return XML From ASPX in ASP.NET 1.1

C#, XML No Comments »

I’m not sure if this is the “canonical” way to do it but here’s a description of how to write an ASP.NET 1.1 ASPX page which returns a XML document (e.g. when writing a home-brewed web service).

First, create a new Web Form (I will call it WebService.aspx). As we will be progamatically generating the XML in the HTTP response rather than sending the (processed) content of the ASPX file, delete everything from the ASPX file but the @Page directive, so that it looks something like:

<%@ Page language="c#" Codebehind="WebService.aspx.cs" AutoEventWireup="false"
    Inherits="WebService.WebService" %>

Next, open up the code-behind file WebService.aspx.cs. Within the Page_Load event handler, add the following code block:

private void Page_Load(object sender, System.EventArgs e)
{
    Response.ContentType = "text/xml";
    Response.ContentEncoding = Encoding.UTF8;

    using (TextWriter textWriter = new StreamWriter(Response.OutputStream,
                                                    Encoding.UTF8))
    {
        XmlTextWriter xmlWriter = new XmlTextWriter(textWriter);
        // Write XML using xmlWriter
    }
}

Notice the use of the HttpResponse.OutputStream property which allows us to write directly to the HTTP response body. Also notice that I explicitly set the Content-Type and Content-Encoding HTTP response headers, and that the encoding for both the response and the StreamWriter must match.

Once you have this block in place, you can use whatever technique you like to write XML to the xmlWriter object. For example, you can call XmlWriter methods by hand, pass xmlWriter as a parameter to XslTransform.Transform(), or use the XmlSerializer.

Update 2006-02-26 1:41 PM: In this comment, dbt suggests writing the XML in the page’s Render() method to avoid problems with chunking encountered when using Page_Load().

XSLT Number Formatting Notes

XSLT No Comments »

When using XSLT’s format-number() function to format a decimal, consider using a zero in the least significant place of the decimal part of your format string. This will allow a number with a 0 integer part to display correctly.

For example:

Number format-number using #,### format-number using #,##0
12345 12,345 12,345
5 5 5
0 No output! 0

This also applies to decimals:

Number format-number using #.00 format-number using 0.00
5 5.00 5.00
0 .00 (Note no leading 0) 0.00
0.1234 .12 (Note no leading 0) 0.12
WP Theme & Icons by N.Design Studio
Entries RSS Comments RSS Log in