A while ago, I posted about integrating the xsd.exe tool into the build process within Visual Studio or MSBuild. This time around, we’ll look at generating the code for the XML Serialization object model and making a few tweaks as part of the process. Here I will specifically look at retrieving the comments in the xsd:documentation elements and applying them to code elements as XML comments. We’ll break this down into four key steps along with some closing comments and source code.
Category Archives: C#
DBML Fixup Preview
Back in February I blogged about DBML Fixup—a tool whose goal was to sync LINQ to SQL models with their respective database schemas from within the Visual Studio environment, as well as to handle running various fixup tasks on models. Now it’s six months later, and I have a much clearer vision of what the tool is meant to be as well as a firmer command on VSX. The following screencast is a preview of the features of DBML Fixup.
Here are some previous posts which (briefly) describe the domain:
http://blogs.rev-net.com/ddewinter/2008/02/16/the-linq-to-sql-model/
http://blogs.rev-net.com/ddewinter/2008/02/16/linq-to-sql-and-database-schema-sync/
Any ideas about directions for the tool? Or maybe something that wasn’t covered in the screencast? I’d love to hear your ideas.
Generate Serialization Classes As Part of Your Build (Part 1)
Yes, I am back from the grave. The past two months have been infuriatingly busy for me (and you’ll see why in a later post), but I finally have some time to write again. The topic? Generating serialization classes as part of your build process (Part 1) and in your own way (Part 2).
I might reach only a niche of .NET developers with this post, but it’s something that niche should be aware of. There is a tool in the .NET framework called xsd.exe, and one of its functions is to generate code, specifically .NET classes, from an XML Schema file (XSD). The tool decorates these classes with XML serialization attributes such that when .NET serializes an instance of the generated class that represents the root element, the output conforms to that XML schema. Often, developers using XML schemas will need to change them throughout the course of a project. Leveraging xsd.exe in a project thus requires the generated classes to be updated when an XML schema is updated. This is a bit dangerous in larger projects because not all developers may realize that the tool must be re-run, especially in the case of extremely minor changes to the schema.
Wouldn’t it be better to have a tighter integration among the XML schema, the generated classes, and the build environment? Fortunately, we can achieve this with a few simple steps, thanks to the MSBuild system for projects inside Visual Studio.
The ExceptionMessageBox
Ever seen this in your application?

Yes? Then this article is for you. If not, you might know what this entry’s going to cover, but perhaps you’ll learn something new.
In tools I’ve been building, I’ve always been dissatisfied with this sort of "error reporting" (outside of logging, of course), but none of us have had the time to build something really spectacular to handle exceptions. And I have to say–thank goodness we didn’t! Yesterday I read about the ExceptionMessageBox class, and this is the sort of thing I’ve been waiting for! (Except it’s been out for well over a year…but that’s another story).
Since pictures speak better than words, the same exception from the first image is thrown again and is handled with the ExceptionMessageBox under default settings:
Much cleaner, huh? Not only does it give you the original exception, but it gives you all of the inner exception detail as well. When you click on the "Show Technical Details" icon in the toolbar (the button on the right) you’ll see a much appreciated stack trace for each of the exceptions in your chain.
All of this is accomplished with two lines of code:
/// <summary>
/// Handles and logs the specified <see cref="Exception"/>.
/// </summary>
/// <param name="exception">The <see cref="Exception"/> to handle.</param>
private static void HandleException(Exception exception)
{
ExceptionMessageBox mbox = new ExceptionMessageBox(exception);
mbox.Show(null);
}
Very simple, indeed. The ExceptionMessageBox class is in the Microsoft.SqlServer.MessageBox namespace in the Microsoft.ExceptionMessageBox assembly. That assembly is available for download on this page. (Search for "Exception Message Box.")
In addition, the ExceptionMessageBox supports a fair number of properties that should be touched on. We’ll cover the highlights here:
Properties
- Beep (Boolean) – Specifies whether the ExceptionMessageBox beeps when it is launched (similar to a normal MessageBox).
- Buttons (ExceptionMessageBoxButtons) – Specifies the type of buttons used by the ExceptionMessageBox. You can also use Custom buttons, a nice touch on top of the original MessageBoxButtons enumeration.
- Caption (String) – The caption/title of the ExceptionMessageBox form.
- CustomDialogResult (ExceptionMessageBoxDialogResult) – Specifies the button that was clicked when using custom buttons.
- CustomSymbol (Bitmap) – Specifies a custom image to display instead of the normal Asterisk, Error, Warning, Information, etc.
- DefaultDialogResult (DialogResult) – Specifies the result of user action on the dialog when not using custom buttons.
- IsCheckBoxChecked (Boolean) – Specifies whether a check box for "Do not show this dialog again" was checked.
- Message (Exception) – The original exception passed into the ExceptionMessageBox constructor.
- MessageLevelDefault (Int32) – Specifies the maximum number of exceptions shown in the dialog. For example, if an exception is thrown that has two inner exceptions, and the MessageLevelDefault property is set to 2, then only the top-level exception and the first inner exception will be shown in the dialog.
- Options (ExceptionMessageBoxOptions) – Enables various options like right-to-left reading or right alignment.
- ShowCheckBox (Boolean) – Specifies whether to show the checkbox which enables developers to hook into users’ preferences on whether they want to show the dialog again.
- ShowToolBar (Boolean) – Specifies whether to show the toolbar (which allows copying text from the message and showing technical details).
- Symbol (ExceptionMessageBoxSymbol) – The symbol to show in the message box, like Asterisk, Error, Warning, and so on.
- Text (String) – If the message box is being used for custom text instead of an exception, then this property will be populated with that text.
- UseOwnerFont (String) – If you want to keep a consistent look across your application, you can tell the ExceptionMessageBox to use its owner window’s font instead of the default.
Methods
- SetButtonText – There are a couple of overloads for this method. It’s used to set the text of one to five buttons on the dialog. This only applies if the Buttons property is ExceptionMessageBoxButtons.Custom.
- Show – Where the magic happens. The basic version of this method requires an IWin32Window as an owner window. The nice thing is that you can pass in null. This would be appropriate if the executing code is inside of an event handler for AppDomain.UnhandledException, for example.
Event
- OnCopyToClipboard -This is a pretty interesting event. It’s raised when the user clicks on the copy to clipboard button in the toolbar or presses Ctrl+C. The event supplies a CopyToClipboardEventArgs instance that has two properties: ClipboardText and EventHandled. When the event is raised, the text hasn’t been copied to the clipboard yet. Instead, you get the chance to handle the event separately. If you want to do your own custom processing and not copy the text to the clipboard, then set the EventHandled property to true on the event arguments and the clipboard data will not be changed. I thought this would be useful for doing something extra, like emailing developers with exception information. However, there’s no easy way to change the text on the toolbar button…
So that’s a brief look at the ExceptionMessageBox. One thing I didn’t cover was how to use the multifarious CheckBox-related properties to stop showing the message box to end users. Here are some links that can help you further:
How To: Program The ExceptionMessageBox
Download Page For ExceptionMessageBox (Search for "Exception Message Box")
Null Your DataSources!
I’ve recently been working on an application that mimics a Windows Forms designer–essentially, a toolbox, the design surface itself, and a property grid. One requirement we had is that we needed to save the contents of the design surface (the controls, their sizes, and their child controls) to an XML file, so it could be reloaded at a later point.
The approach a co-worker and I had taken to serialize the data was to write controls and control-specific data in XML and to write serializable objects (business objects that the controls had references to) as binary data. During this process, I had a very painful debugging experience trying to figure out why the BinaryFormatter was trying to serialize a ListBox when I had told it to serialize one of our business objects. The only thing we had done differently before saving was that we had edited a property which showed a dialog which contained a few ListBox objects.
That action was most definitely related to the issue, but we still couldn’t think of why it was trying to serialize the ListBox, especially after the dialog was closed.
After a couple of hours, I was a little astounded at the cause. It turns out that when we set the DataSource property on the ListBoxes in the dialog I mentioned earlier, the WireDataSource() method in the ListControl was called. Since our business entities also implement IComponent (courtesy of .netTiers), the method attaches its DataSourceDisposed method to the Disposed event of the bound object. Thus, when we tried to serialize the object, the link between its Disposed event and the DataSourceDisposed event handler had not been broken, and it had tried to save the containing type of DataSourceDisposed.
The simple fix was to set the DataSource properties on the ListBox to null when the Form closed. Almost a kick in the face after all that.
WF Tracing
Windows Workflow Foundation (http://msdn2.microsoft.com/en-us/netframework/aa663328.aspx) is a relatively new technology released in .NET 3.0 for modeling workflows and business processes.
I’ve recently been working with the rules engine and PolicyActivity in WF. I’ve found that you can log what’s going on with the rules engine with the following configuration in the configuration file:
<configuration>
<system.diagnostics>
<switches>
<add name=“System.Workflow.Activities.Rules“ value=“All“/>
<add name=“System.Workflow.LogToFile“ value=“1“/>
</switches>
</system.diagnostics>
</configuration>
However, it’s also possible to trace using any trace listeners registered with the Trace.Listeners collection using the following:
<configuration>
<system.diagnostics>
<switches>
<add name=“System.Workflow.Activities.Rules“ value=“All“/>
<add name=“System.Workflow.LogToTraceListeners“ value=“1“/>
</switches>
</system.diagnostics>
</configuration>
I mention this because in the context that I found it, I found almost no documentation on this. It’s probably more easily accessible than I think, but it’s here just in case. =)
Implicit Vs. Explicit Interface Method Implementation
In the NORMA project we were encouraged to use Explicit Interface Method Implementation (EIMI). However, after reading a bit of Jeffrey Richter’s CLR via C#, I’ve decided to change the way I implement interfaces.
This entry is also a response to Ben’s blog entry, located here, which you should read first because it explains the difference between the two approaches.
Now…a little about why I disagree that EIMI should be used as often as possible.
- Having to cast an object to the interface just to call the interface method can get a little annoying in code. When you’re working on a team that might not be so familiar with this pattern then it takes extra time for them to get acquainted with it, because it’s a little awkward. However, this may be a superficial reason to some, so let’s continue…
- Regarding that cast, think about a case where you have a value type that has used EIMI to implement an interface. When you cast to the interface you burden your application by forcing a box operation on the value type so it can actually be treated as that interface type.
- Furthermore, with EIMI, if you derive from a class that implements an interface in this manner, you can’t call your base class’s implementation of that interface.
Now, I’m not saying that EIMI is useless. There are some specific cases when it is necessary. Take for instance the following example:
[code lang="csharp"] public interface IWindow
{
object GetMenu();
}
public interface IRestaurant
{
object GetMenu();
}
public class Pizzeria : IWindow, IRestaurant
{
object IWindow.GetMenu() { ... }
object IRestaurant.GetMenu() { ... }
}
[/code]
Here you have to use EIMI because you have two interfaces with the same method names. It doesn’t make sense to call GetMenu() and expect the CLR to infer which interface you’re binding to.
Another case where EIMI can come in handy is to improve compile-time safety. Let’s say you have a struct that implements a non-generic interface, like IComparable:
[code lang="csharp"] public interface IComparable
{
Int32 CompareTo(Object other);
}
public struct SomeValueType : IComparable
{
private int x;
public SomeValueType(Int32 x) { this.x = x; }
public Int32 CompareTo(Object other)
{
return x - ((SomeValueType)other).x;
}
}
// Now in some other method I can call CompareTo like this
public static void Main()
{
SomeValueType v = new SomeValueType(0);
Object o = new Object();
Int32 n = v.CompareTo(v); // Undesired Boxing
n = v.CompareTo(o); // InvalidCastException
}[/code]
So now instead of what’s listed above, you want to enforce some semblance of compile-time safety with your interface method. Here’s something you can do with EIMI:
[code lang="csharp"] public struct SomeValueType : IComparable
{
private int x;
public SomeValueType(Int32 x) { this.x = x; }
Int32 IComparable.CompareTo(Object other)
{
return CompareTo((SomeValueType)other);
}
public Int32 CompareTo(SomeValueType other)
{
return x - other.x;
}
}
// Now in some other method I can call CompareTo like this
public static void Main()
{
SomeValueType v = new SomeValueType(0);
Object o = new Object();
Int32 n = v.CompareTo(v); // No Boxing
n = v.CompareTo(o); // Compile-time Error
}[/code]
Of course, if we box SomeValueType into an IComparable instance then it would throw as above, so this s”olution” only alleviates the problem; in most cases your best bet would be to use a generic interface to enforce type-safety and remove boxing/unboxing operations.
Because of this, I have concluded that I will not use EIMI every chance I get, but instead will focus on using IIMI unless I really need to use EIMI as outlined by cases above.
As, Is, and the Art of Reflection
I’m sure that for all of us there have been times when we want to get the type of an object that we’re using, especially when dealing with abstract classes, interfaces, and inheritance. For this, there’s a right way and a wrong way to do things.
The first way to determine the type of an object instance is to use reflection. You may have heard that reflection causes significant overhead. This is no exception. Here’s an example.
public void Display(IList displayer)
{
if (displayer.GetType() == Type.GetType("System.Collections.ArrayList"))
{
return;
}
// Other processing...
}
It’s bad enough that we’re using reflection for this information (via the GetType() method of displayer), but also that we’re hardcoding the type of the class we’re interested in with “System.Collections.ArrayList.” This can be cleaned up to the following:
public void Display(IList displayer)
{
if (displayer.GetType() == typeof(System.Collections.ArrayList))
{
return;
}
// Other processing...
}
However, it’s still reflection. Instead of using this, consider using the is keyword, which in fact does not use reflection at all but a special MSIL statement which is pretty quick, as far as what I’ve heard.
public void Display(IList displayer)
{
if (displayer is System.Collections.ArrayList)
{
return;
}
// Other processing...
}
Another keyword that is often overlooked is the as keyword. This handles casting on reference types. Although I hope you haven’t, maybe you’ve seen something like this before:
DataSet ds;
try
{
ds = (DataSet)Request.Cache["ds"];
}
catch { }
You don’t even need a try/catch statement here; just use the as keyword! Not only will it handle times when it is impossible to cast to the requested type by setting the value to null, but it also uses the same MSIL instruction as is, so it’s pretty efficient. You can’t use these two keywords with value types because value types and reference types are handled differently in memory.
Here’s one last example:
public void Display(IList«IDisposable» list)
{
int count = list.Count;
for (int i = 0; i < count; ++i)
{
IDisposable item = list[i];
if (item is SqlConnection)
{
(item as SqlConnection).Open();
}
// Other processing...
}
}
Say you wanted to check if a particular item is a SqlConnection object, and if it is, open it. Remember how is and as do basically the exact same thing though? So in this previous block of code you have a double cast. Consider doing something like the following:
public void Display(IList«IDisposable» list)
{
int count = list.Count;
for (int i = 0; i < count; ++i)
{
IDisposable item = list[i];
SqlConnection cnn = item as SqlConnection;
if (cnn != null)
{
cnn.Open();
}
// Other processing...
}
}
Matt’s First Rule of Performance
All of us know a little bit about code for us to be on the RevNet Development Team, but sometimes it takes more than knowing what to do to accomplish something—like reading an XML file and sending an email from the information inside it, or inserting user input into a database—to do it “right.” I came across a concept from NU’s own Matt Curland the other day that looked something like this:
// Matt’s first rule of performance:
// 0 > 1 > 2
So what does that mean? The gist is that if you need to get a result from a property or method, and you need to manipulate that value in more than one place, it’s better to call it once than call it twice. But even so, it’s better not to call anything at all if you can help it.
An example of this in practice was what he was referring to at the time: (beware, ORM jargon approaching!) the Multiplicity property of a Role object. This RoleMultiplicity is a measure of how many times a unique value could go into a fact table representing the role’s opposite role on a binary fact type i.e. if I had the fact type “Person(ID) has PersonName()” with a uniqueness and mandatory role constraint on the side of the Person object, calling the Multiplicity property of the PersonName’s role would give me RoleMultiplicity.ExactlyOne (opposite role’s constraints signify this).
Little did I know that calling this property was an immensely expensive procedure. It has to get the fact type from the model by using VS2005′s “Store” (as its name implies, stores everything that would be on the diagram, and we have know idea how that’s done; could be something of O(n2) complexity; see how Algorithms comes into play?!), and then create a new collection based on the roles from the model. It thens checks the count of the collection which does a lot of other checks (F11 makes you sick), and then does another loop to check for what multiplicity that role actually has. Before investigating all of that for ourselves, this is what our code looked like:
Before the Rule – Notice the properties referenced multiple times.
After the Rule – Notice how things are pulled out.
So remember:
When in doubt, pull it out.