Silverlight 1.0 Mandelbrot Set Generator

Silverlight 2 Comments »

While reading the Mandelbrot set chapter in Dewdney’s The New Turing Omnibus, I realized that this would be a great test application for Microsoft’s new interactive Web application framework Silverlight. Below is the component, its source code, and a few things I learned along the way.

Beware: the Mandelbrot set is computationally expensive and may appear to lock up your web browser. If a “Stop running this script?” dialog pops up, please click no to allow the calculations to finish.
Read the rest of this entry »

XmlTextWriter Can Produce Invalid XML

C# 1 Comment »

XmlTextWriter is .NET’s class for writing XML in a forward-only streaming manner. It is highly efficient and is the preferred way to generate XML in .NET in most circumstances. I find XmlTextWriter so useful I wrote a partial C++ implementation of it in Implenting IXmlWriter Series.

Unfortunately, XmlTextWriter isn’t quite as strict as it could be. It will let slip some invalid XML such as duplicate attributes, invalid Unicode characters in the range 0×0 to 0×20, and invalid element and attribute names. You can read about XmlTextWriter’s limitations in the article Customized XML Writer Creation.

If these limitations are an issue for you, I suggest following the instructions in “Customized XML Writer Creation” by writing a custom writer that extends the current XmlTextWriter and adds this functionality. This class can be used directly or passed to any functions which are designed to use XmlTextWriter.

Managed Wrappers and Hidden Interdependencies

C#, C++ 2 Comments »

Let’s say you have the following unmanaged code:

  1. #pragma unmanaged
  2.  
  3. class Stream {}; // Conceptual stream class
  4.  
  5. class StreamWriter
  6. {
  7. public:
  8.     StreamWriter(Stream* pStream) : m_pStream(pStream) {}
  9.     ~StreamWriter() { /* Use m_pStream in some way */ }
  10.  
  11.     …
  12. private:
  13.     Stream* m_pStream;
  14. };
  15.  
  16. void f()
  17. {
  18.     Stream stream;
  19.     StreamWriter streamWriter(&stream);
  20.  
  21.     // Use streamWriter
  22.  
  23.     // streamWriter is destroyed
  24.     // stream is destroyed
  25. }

Note that StreamWriter’s destructor uses m_pStream (perhaps by flushing the stream). This means that the order of destruction is importantStreamWriter must be destroyed before its underlying Stream is.

Now let’s try to write and use some simple managed C++ wrappers for these classes:

  1. #pragma managed
  2.  
  3. public __gc class ManagedStream
  4. {
  5. public:
  6.     ManagedStream() : m_pStream(new Stream) {}
  7.  
  8.     // NOTE: This is a finalizer, not a determinstic destructor  
  9.     ~ManagedStream() { delete m_pStream; }
  10.  
  11. public private: // Make accessible by ManagedStreamWriter
  12.     Stream __nogc* m_pStream;
  13. };
  14.  
  15. public __gc class ManagedStreamWriter
  16. {
  17. public:
  18.     ManagedStreamWriter(ManagedStream* pStream) :
  19.         m_pStreamWriter(new StreamWriter(pStream->m_pStream)) {}
  20.  
  21.     // NOTE: This is a finalizer, not a determinstic destructor  
  22.     ~ManagedStreamWriter() { delete m_pStreamWriter; }
  23.  
  24. private:
  25.     StreamWriter __nogc* m_pStreamWriter;
  26. };
  27.  
  28. void f()
  29. {
  30.     ManagedStream stream = __gc new ManagedStream();
  31.     ManagedStreamWriter streamWriter =
  32.         __gc new ManagedStreamWriter(stream);
  33.  
  34.     // Use streamWriter
  35.  
  36.     // GC will clean up stream and streamWriter
  37. }

See the problem?

Read the rest of this entry »

C# Locking Rules

C# No Comments »

While they have been oft repeated, the following C# locking rules deserve at least one more go around:

Never lock a value type (e.g. ints and structs).

Value types will be boxed into objects, and multiple boxings will not result in the same object, so mutual exclusion will not be assured.

Never lock this.

It opens up the possibility for deadlock, as in the following code:

class A
{
    public void f()
    {
        lock (this)
        {
            // Do work
        }
    }
}

class B
{
    public void g()
    {
        A a = new A();
        lock (a)
        {
            a.f(); // Deadlock!
        }
    }
}
Never lock string instances.

Because strings are interned, two strings with the same contents are the same object and thus correspond to one lock — almost certainly not what you intended. Furthermore, interned strings are shared across application domains.

Never lock Type objects.

See the June 5, 2003 Dr. GUI article for the reason why.

Be careful about holding a lock while calling code you don’t control.

This includes virtual and abstract functions.

Establish and follow a locking order.

Multiple threads grabbing locks in differing orders is a classic recipie for deadlock.

If your class needs a lock, consider creating a private member object to act as one. For example:

class A
{
    private object m_lock = new object();

    public void f()
    {
        lock (m_lock)
        {
            // Do work
        }
    }
}

Hat tip: Threading Tips.

More On IDisposable

C# No Comments »

My posts Deterministic Finalization in Garbage-Collected Languages and Rules for Implementing IDisposable are, in my opinion, a fair introduction to the purpose and use of C#’s IDisposable idiom. However, I would like to propose the following additional guideline for the usage of IDisposable:

The class which creates a disposable object is responsible for calling Dispose().

Ridiculously obvious, right? Yet it has some important implications. Consider this quote from Rules for Implementing IDisposable:

If you write a class which contains a member which implements IDisposable, your class must also implement IDisposable and dispose each member in turn in your Dispose() method.

This is only true if your class created the disposable object. If your class was passed the disposable object in the constructor, you should not call its Dispose() method. Similarly, if you are writing a class which wraps a Stream and provides additional functionality (e.g. BufferedStream or GZipStream), you should not call the underlying Stream’s Dispose() method if you did not create the underlying Stream yourself.

This implies that, in general, passing an object to a constructor of another class is not a transfer of ownership. (For further reflection: Are there cases where this isn’t true? Is there an alternative idiom to express the concept of transfer of ownership?)

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().

Write Functions Which Take Iterators, Not Collections

C#, STL No Comments »

If my experience is typical, this is a very common construct:

ReturnType Function
    (
    const std::vector<T>& container
    )
{
    typedef std::vector<T>::const_iterator iterator_t;
    for (iterator_t iter = container.begin();
         iter != container.end();
         ++iter) {
        // Work with *iter
    }
}

The problem with this construct is that you have forced a container choice upon the user of your function. Slightly better, and basically your only choice when interoping with C, is this:

ReturnType Function
    (
    T* array,
    int numItems
    )
{
    for (int i = 0; i < numItems; ++i) {
        // Work with array[numItems]
    }

    // Or perhaps:
    // for (T* pT = array; pT != array + numItems; ++pT) {
    //     Work with *pT
    // }
}

With the above construct you can pass in any container which uses contiguous storage, such as an array or a std::vector (yes, std::vectors are guaranteed to store the data contiguously). Passing a std::vector to the above function looks like:

std::vector<T> v;
ReturnType ret = Function(v.empty() ? 0 : &v[0], v.size());

However, in C++ its far better to do as the STL does and write your function to accept iterators, as in:

template <class InputIterator>
ReturnType Function
    (
    InputIterator first,
    InputIterator last
    )
{
    for (InputIterator iter = first; iter != last; ++iter) {
        // Work with *iter
    }
}

By using this construct, you allow vast usage flexibility. Try to limit yourself to input iterator expressions on first and last (basically preincrement, dereference, and comparison) to minimize the requirements the InputIterator class must fulfill.

Most (all?) STL containers can pass their contents to Function() by using the containers’ begin() and end() functions, as in:

std::vector<T> v;
ReturnType ret = Function(v.begin(), v.end());

As C pointers are random-access iterators, you can pass arrays to Function() as follows:

const int arraySize = ...;
T array[arraySize];

ReturnType ret = Function(array, array + arraySize);

By the way, this lesson also applies to C#: prefer writing functions which accept IEnumerables rather than collections such as arrays. (In C# 2.0, you should be able to regain the lost typesafety by accepting IEnumerable<T>)

Revisiting Excel Interop

C#, Excel Interop No Comments »

I ran into problem today relating to Excel interop. A coworker made a change to a C# application I wrote and was trying to build it. The program relied on a project which had a reference to the Microsoft Excel 9.0 Object Library which ships with Office 2000. However, the coworker had Office 2003 installed which includes the Excel 11.0 Object Library and not the Excel 9.0 Object Library. Because of this, he could not build the application.

I first considered copying the Excel 2000 executable to his machine to try to make the Excel 9.0 Object Library available, but I decided this was nasty and possibly illegal. I next considered using the Microsoft Office XP Primary Interop Assemblies but ruled them out because I must support Office 2000. I then spent a good amount of time trying to use the Excel 5.0 Object Library (distributed by both Office 2000 and Office 2003) but I ran into some fairly challenging issues relating to the lack of documentation and difficulties with the autogenerated wrapper classes.

My eventual solution was to use the lowest common denominator: my own custom Excel wrapper classes which map directly to objects in the Excel object model but internally use OLE automation (a.k.a. run-time binding a.k.a. IDispatch). The wrapper classes inherit from AutoReleaseComObject to get nice IDisposable-based COM Release() semantics (which is important for Excel!). A sample wrapper class looks something like:

// Maps directly to the Workbooks object in the Excel
// object model.
public sealed class ExcelWorkbooks : AutoReleaseComObject
{
    // Needed for .InvokeMember()
    private Type m_excelWorkbooksType;

    public ExcelWorkbooks(object comObject) : base(comObject)
    {
        m_excelWorkbooksType = comObject.GetType();
    }

    // Maps directly to the Workbooks.Add() method in the
    // Excel object model.
    public ExcelWorkbook Add()
    {
        object o = m_excelWorkbooksType.InvokeMember
            (
            "Add",
            BindingFlags.InvokeMethod,
            null,
            this.ComObject,
            new object[] {}
            );
        return new ExcelWorkbook(o);
    }
}

These IDispatch-based wrapper classes give me maximum flexibility with minimum dependencies (and zero compile-time dependencies) but they are extraordinarily tedious to write. In the future I may experiment with using custom attributes and run-time code generation through System.CodeDom to simplify writing these wrappers. Alternatively, I may look into generating the code at compile-time but that would probably mean moving to a more sophisticated build tool such as NAnt.

Minimize your dependencies is an important rule to keep in mind when programming.

SharpZipLib GZip FEXTRA Bug

C# No Comments »

I have identified and fixed what I believe to be a bug in the way ICSharpCode’s #ziplib 0.83a handles FEXTRA fields in GZIP files. Here are some related links:

C# Utility Class: CompundKey

C# No Comments »

While working in C#, I’ve often found that I want to use more than one variable as a key to a Hashtable. I’ve abstracted this functionality into an object called CompundKey. CompoundKey allows one to combine any number of variables into a single object which, through proper implementation of Equals(), GetHashCode(), and ToString(), can be used as a key to any IDictionary or even System.Web.Caching.Cache.

Usage is very simple. For example:

IDictionary urlUserAccessTimes = new Hashtable();
CompoundKey urlUserKey = new CompoundKey(new Uri("http://www.deez.info/sengelha/", "Steven Engelhardt"));
urlUserAccessTimes[urlUserKey] = DateTime.Now;

Here’s the code:

CompoundKey code
/// <summary>
/// Creates a key for an IDictionary or a System.Web.Caching.Cache
/// out of a collection of values.
/// </summary>
/// <remarks>
/// Each value stored in CompoundKey must implement Equals()
/// correctly.
/// </remarks>
public struct CompoundKey
{
    private object[] m_keyParts;

    public CompoundKey(params object[] keyParts)
    {
        Debug.Assert(keyParts != null);

        m_keyParts = keyParts;
    }

    public override bool Equals(object obj)
    {
        if (!(obj is CompoundKey))
            return false;

        CompoundKey key = (CompoundKey) obj;
        return ArrayUtils.Equals(m_keyParts, key.m_keyParts);
    }

    public override int GetHashCode()
    {
        int hashCode = 0;
        foreach (object keyPart in m_keyParts)
        {
            if (keyPart != null)
            {
                hashCode ^= keyPart.GetHashCode();
            }
        }
        return hashCode;
    }

    /// <remarks>
    /// Unfortunately, System.Web.Caching.Cache uses strings as keys
    /// instead of objects.
    /// </remarks>
    public override string ToString()
    {
        StringBuilder sb = new StringBuilder();

        foreach (object keyPart in m_keyParts)
        {
            if (sb.Length > 0)
                sb.Append(”,”);
            sb.Append(keyPart != null ? keyPart.ToString() : “(null)”);
        }

        return sb.ToString();
    }
}
WP Theme & Icons by N.Design Studio
Entries RSS Comments RSS Log in