<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>David DeWinter &#187; C#</title>
	<atom:link href="http://blogs.rev-net.com/ddewinter/category/c-sharp/feed/" rel="self" type="application/rss+xml" />
	<link>http://blogs.rev-net.com/ddewinter</link>
	<description>A Developer's Melting Pot: LINQ to SQL, Entity Framework, .NET Security...</description>
	<lastBuildDate>Thu, 08 Apr 2010 17:32:14 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.9.1</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Generate Serialization Classes As Part of Your Build (Part 2)</title>
		<link>http://blogs.rev-net.com/ddewinter/2008/09/28/generate-serialization-classes-as-part-of-your-build-part-2/</link>
		<comments>http://blogs.rev-net.com/ddewinter/2008/09/28/generate-serialization-classes-as-part-of-your-build-part-2/#comments</comments>
		<pubDate>Sun, 28 Sep 2008 19:12:51 +0000</pubDate>
		<dc:creator>David DeWinter</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[MSBuild]]></category>
		<category><![CDATA[Code Generation]]></category>
		<category><![CDATA[Object Model]]></category>
		<category><![CDATA[Serialization]]></category>
		<category><![CDATA[XML]]></category>
		<category><![CDATA[xsd.exe]]></category>

		<guid isPermaLink="false">http://blogs.rev-net.com/ddewinter/2008/09/28/generate-serialization-classes-as-part-of-your-build-part-2/</guid>
		<description><![CDATA[A while ago, I posted about integrating the xsd.exe tool into the build process within Visual Studio or MSBuild. This time around, we&#8217;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 [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://blogs.rev-net.com/ddewinter/2008/07/08/generate-serialization-classes-as-part-of-your-build-part-1/">A while ago</a>, I posted about integrating the xsd.exe tool into the build process within Visual Studio or MSBuild. This time around, we&#8217;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&#8217;ll break this down into four key steps along with some closing comments and source code.</p>
<p> <span id="more-123"></span>
<ul>
<li><a href="#creating-the-schema">Creating the Schema</a> </li>
<li><a href="#generating-the-code">Generating the Code</a> </li>
<li><a href="#making-your-modifications">Making Your Modifications (xs:documentation comments to XML comments)</a> </li>
<li><a href="#integrating-with-msbuild">Integrating with MSBuild</a> </li>
<li><a href="#let-the-buyer-beware">Let the Buyer Beware</a> </li>
<li><a href="#source-code">Reference Source Code</a> </li>
</ul>
<h3 id="creating-the-schema">Creating the Schema</h3>
<p>Before we start, we&#8217;ll need a schema to work with. For simplicity, we&#8217;ll use the same schema as last time with the addition of xsd:documentation elements to provide descriptions for some elements and attributes. The complex types are also no longer anonymous.</p>
<div class="cf">
<p style="margin: 0px"><span style="color: blue">&lt;?</span><span style="color: #a31515">xml</span><span style="color: blue"> </span><span style="color: red">version</span><span style="color: blue">=</span>&quot;<span style="color: blue">1.0</span>&quot;<span style="color: blue"> </span><span style="color: red">encoding</span><span style="color: blue">=</span>&quot;<span style="color: blue">utf-8</span>&quot;<span style="color: blue">?&gt;</span></p>
<p style="margin: 0px"><span style="color: blue">&lt;</span><span style="color: #a31515">xs:schema</span><span style="color: blue"> </span><span style="color: red">id</span><span style="color: blue">=</span>&quot;<span style="color: blue">SampleSchema</span>&quot;</p>
<p style="margin: 0px"><span style="color: blue">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; </span><span style="color: red">targetNamespace</span><span style="color: blue">=</span>&quot;<span style="color: blue">http://schemas.example.com/SampleSchema.xsd</span>&quot;</p>
<p style="margin: 0px"><span style="color: blue">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; </span><span style="color: red">elementFormDefault</span><span style="color: blue">=</span>&quot;<span style="color: blue">qualified</span>&quot;</p>
<p style="margin: 0px"><span style="color: blue">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; </span><span style="color: red">xmlns</span><span style="color: blue">=</span>&quot;<span style="color: blue">http://schemas.example.com/SampleSchema.xsd</span>&quot;</p>
<p style="margin: 0px"><span style="color: blue">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; </span><span style="color: red">xmlns:xs</span><span style="color: blue">=</span>&quot;<span style="color: blue">http://www.w3.org/2001/XMLSchema</span>&quot;<span style="color: blue">&gt;</span></p>
<p style="margin: 0px"><span style="color: blue">&#160; &lt;</span><span style="color: #a31515">xs:element</span><span style="color: blue"> </span><span style="color: red">name</span><span style="color: blue">=</span>&quot;<span style="color: blue">root</span>&quot;<span style="color: blue"> </span><span style="color: red">type</span><span style="color: blue">=</span>&quot;<span style="color: blue">rootType</span>&quot;<span style="color: blue">/&gt;</span></p>
<p style="margin: 0px"><span style="color: blue">&#160; &lt;</span><span style="color: #a31515">xs:complexType</span><span style="color: blue"> </span><span style="color: red">name</span><span style="color: blue">=</span>&quot;<span style="color: blue">rootType</span>&quot;<span style="color: blue">&gt;</span></p>
<p style="margin: 0px"><span style="color: blue">&#160;&#160;&#160; &lt;</span><span style="color: #a31515">xs:sequence</span><span style="color: blue">&gt;</span></p>
<p style="margin: 0px"><span style="color: blue">&#160;&#160;&#160;&#160;&#160; &lt;</span><span style="color: #a31515">xs:element</span><span style="color: blue"> </span><span style="color: red">name</span><span style="color: blue">=</span>&quot;<span style="color: blue">first</span>&quot;<span style="color: blue"> </span><span style="color: red">type</span><span style="color: blue">=</span>&quot;<span style="color: blue">firstType</span>&quot;<span style="color: blue"> /&gt;</span></p>
<p style="margin: 0px"><span style="color: blue">&#160;&#160;&#160;&#160;&#160; &lt;</span><span style="color: #a31515">xs:element</span><span style="color: blue"> </span><span style="color: red">name</span><span style="color: blue">=</span>&quot;<span style="color: blue">second</span>&quot;<span style="color: blue"> </span><span style="color: red">type</span><span style="color: blue">=</span>&quot;<span style="color: blue">secondType</span>&quot;<span style="color: blue">/&gt;</span></p>
<p style="margin: 0px"><span style="color: blue">&#160;&#160;&#160; &lt;/</span><span style="color: #a31515">xs:sequence</span><span style="color: blue">&gt;</span></p>
<p style="margin: 0px"><span style="color: blue">&#160; &lt;/</span><span style="color: #a31515">xs:complexType</span><span style="color: blue">&gt;</span></p>
<p style="margin: 0px">&#160;</p>
<p style="margin: 0px"><span style="color: blue">&#160; &lt;</span><span style="color: #a31515">xs:complexType</span><span style="color: blue"> </span><span style="color: red">name</span><span style="color: blue">=</span>&quot;<span style="color: blue">firstType</span>&quot;<span style="color: blue">&gt;</span></p>
<p style="margin: 0px"><span style="color: blue">&#160;&#160;&#160; &lt;</span><span style="color: #a31515">xs:annotation</span><span style="color: blue">&gt;</span></p>
<p style="margin: 0px"><span style="color: blue">&#160;&#160;&#160;&#160;&#160; &lt;</span><span style="color: #a31515">xs:documentation</span><span style="color: blue">&gt;</span>Describes the first element in the document.<span style="color: blue">&lt;/</span><span style="color: #a31515">xs:documentation</span><span style="color: blue">&gt;</span></p>
<p style="margin: 0px"><span style="color: blue">&#160;&#160;&#160; &lt;/</span><span style="color: #a31515">xs:annotation</span><span style="color: blue">&gt;</span></p>
<p style="margin: 0px"><span style="color: blue">&#160;&#160;&#160; &lt;</span><span style="color: #a31515">xs:attribute</span><span style="color: blue"> </span><span style="color: red">name</span><span style="color: blue">=</span>&quot;<span style="color: blue">name</span>&quot;<span style="color: blue"> </span><span style="color: red">type</span><span style="color: blue">=</span>&quot;<span style="color: blue">xs:token</span>&quot;<span style="color: blue">&gt;</span></p>
<p style="margin: 0px"><span style="color: blue">&#160;&#160;&#160;&#160;&#160; &lt;</span><span style="color: #a31515">xs:annotation</span><span style="color: blue">&gt;</span></p>
<p style="margin: 0px"><span style="color: blue">&#160;&#160;&#160;&#160;&#160;&#160;&#160; &lt;</span><span style="color: #a31515">xs:documentation</span><span style="color: blue">&gt;</span>The name of the first element.<span style="color: blue">&lt;/</span><span style="color: #a31515">xs:documentation</span><span style="color: blue">&gt;</span></p>
<p style="margin: 0px"><span style="color: blue">&#160;&#160;&#160;&#160;&#160; &lt;/</span><span style="color: #a31515">xs:annotation</span><span style="color: blue">&gt;</span></p>
<p style="margin: 0px"><span style="color: blue">&#160;&#160;&#160; &lt;/</span><span style="color: #a31515">xs:attribute</span><span style="color: blue">&gt;</span></p>
<p style="margin: 0px"><span style="color: blue">&#160;&#160;&#160; &lt;</span><span style="color: #a31515">xs:attribute</span><span style="color: blue"> </span><span style="color: red">name</span><span style="color: blue">=</span>&quot;<span style="color: blue">value</span>&quot;<span style="color: blue"> </span><span style="color: red">type</span><span style="color: blue">=</span>&quot;<span style="color: blue">xs:token</span>&quot;<span style="color: blue">&gt;</span></p>
<p style="margin: 0px"><span style="color: blue">&#160;&#160;&#160;&#160;&#160; &lt;</span><span style="color: #a31515">xs:annotation</span><span style="color: blue">&gt;</span></p>
<p style="margin: 0px"><span style="color: blue">&#160;&#160;&#160;&#160;&#160;&#160;&#160; &lt;</span><span style="color: #a31515">xs:documentation</span><span style="color: blue">&gt;</span>The value of the first element.<span style="color: blue">&lt;/</span><span style="color: #a31515">xs:documentation</span><span style="color: blue">&gt;</span></p>
<p style="margin: 0px"><span style="color: blue">&#160;&#160;&#160;&#160;&#160; &lt;/</span><span style="color: #a31515">xs:annotation</span><span style="color: blue">&gt;</span></p>
<p style="margin: 0px"><span style="color: blue">&#160;&#160;&#160; &lt;/</span><span style="color: #a31515">xs:attribute</span><span style="color: blue">&gt;</span></p>
<p style="margin: 0px"><span style="color: blue">&#160; &lt;/</span><span style="color: #a31515">xs:complexType</span><span style="color: blue">&gt;</span></p>
<p style="margin: 0px">&#160;</p>
<p style="margin: 0px"><span style="color: blue">&#160; &lt;</span><span style="color: #a31515">xs:complexType</span><span style="color: blue"> </span><span style="color: red">name</span><span style="color: blue">=</span>&quot;<span style="color: blue">secondType</span>&quot;<span style="color: blue">&gt;</span></p>
<p style="margin: 0px"><span style="color: blue">&#160;&#160;&#160; &lt;</span><span style="color: #a31515">xs:attribute</span><span style="color: blue"> </span><span style="color: red">name</span><span style="color: blue">=</span>&quot;<span style="color: blue">origin</span>&quot;<span style="color: blue"> </span><span style="color: red">type</span><span style="color: blue">=</span>&quot;<span style="color: blue">xs:token</span>&quot;<span style="color: blue"> /&gt;</span></p>
<p style="margin: 0px"><span style="color: blue">&#160; &lt;/</span><span style="color: #a31515">xs:complexType</span><span style="color: blue">&gt;</span></p>
<p style="margin: 0px"><span style="color: blue">&lt;/</span><span style="color: #a31515">xs:schema</span><span style="color: blue">&gt;</span></p>
</p></div>
<p>The descriptions here are nonsensical, but this example is small enough to demonstrate the power of what we can do with custom code generation. We still aim to generate classes at build time, but first we have to implement the logic that the build step will use. The next sections describe what we need to do.</p>
<h3 id="generating-the-code">Generating the Code</h3>
<p>The first step is to import the schema into the code.</p>
<div class="cf"><span style="color: #2b91af">XmlSchemas</span> schemaSet = <span style="color: blue">new</span> <span style="color: #2b91af">XmlSchemas</span>();</div>
<div class="cf"><span style="color: #2b91af">XmlSchema</span> xsd = <span style="color: blue">null</span>;</div>
<p class="cf" style="margin: 0px"><span style="color: blue">using</span> (<span style="color: #2b91af">XmlReader</span> reader = <span style="color: #2b91af">XmlReader</span>.Create(mySourceXsdFile))</p>
<p class="cf" style="margin: 0px">{</p>
<p class="cf" style="margin: 0px">&#160;&#160;&#160; xsd = <span style="color: #2b91af">XmlSchema</span>.Read(reader, <span style="color: blue">null</span>);</p>
<p class="cf" style="margin: 0px">&#160;&#160;&#160; schemaSet.Add(xsd);</p>
<p class="cf" style="margin: 0px">}</p>
<p>We instantiate a new instance of the <span class="cf">System.Xml.Serialization.<span class="cb2">XmlSchemas</span></span> (in System.Xml.dll) class and add the schema file to that schema set. In the code above, <span class="cf">mySourceXsdFile</span> is a field which is set during the construction of the object which contains this code. The next step is to translate the schema definition into a CodeDom <span class="cf"><span class="cb2">CodeNamespace </span></span>and then export that <span class="cf"><span class="cb2">CodeNamespace </span></span>instance to code. Simple, right?</p>
<p>Fortunately for us, there are classes built into the framework to handle this. First we set up a schema importer and a code exporter:</p>
<div class="cf">
<p style="margin: 0px"><span style="color: green">// Load the XSD into the importer</span></p>
<p style="margin: 0px"><span style="color: #2b91af">XmlSchemaImporter</span> importer = <span style="color: blue">new</span> <span style="color: #2b91af">XmlSchemaImporter</span>(schemaSet);</p>
<p style="margin: 0px">&#160;</p>
<p style="margin: 0px"><span style="color: green">// Set up the objects needed for code export.</span></p>
<p style="margin: 0px"><span style="color: #2b91af">CodeNamespace</span> ns = <span style="color: blue">new</span> <span style="color: #2b91af">CodeNamespace</span>(<span style="color: blue">this</span>.Namespace);</p>
<p style="margin: 0px"><span style="color: #2b91af">XmlCodeExporter</span> exporter = <span style="color: blue">new</span> <span style="color: #2b91af">XmlCodeExporter</span>(ns);</p>
</p></div>
<p>The argument for the <span class="cf"><span class="cb2">CodeNamespace</span></span> constructor takes a string representing the desired namespace name for the generated code. The translation between these objects occurs using an <span class="cf">System.Xml.Serialization.<span class="cb2">XmlTypeMapping</span></span> instance to connect the two. To create the type mapping, we&#8217;ll need an <span class="cf">System.Xml.<span class="cb2">XmlQualifiedName</span></span> representing the root element of the schema. The exporter can then export that type mapping to a CodeDom representation, which we can utilize to write the code output to a file. The result looks something like this:</p>
<div class="cf">
<p style="margin: 0px"><span style="color: #2b91af">XmlSchemaObjectCollection</span> xsdObjects = xsd.Items;</p>
<p style="margin: 0px"><span style="color: blue">int</span> xsdObjectCount = xsdObjects.Count;</p>
<p style="margin: 0px"><span style="color: blue">for</span> (<span style="color: blue">int</span> i = 0; i &lt; xsdObjectCount; ++i)</p>
<p style="margin: 0px">{</p>
<p style="margin: 0px">&#160;&#160;&#160; <span style="color: #2b91af">XmlSchemaObject</span> xsdObject = xsdObjects[i];</p>
<p style="margin: 0px">&#160;</p>
<p style="margin: 0px">&#160;&#160;&#160; <span style="color: #2b91af">XmlSchemaElement</span> xsdElement = xsdObject <span style="color: blue">as</span> <span style="color: #2b91af">XmlSchemaElement</span>;</p>
<p style="margin: 0px">&#160;&#160;&#160; <span style="color: blue">if</span> (xsdElement != <span style="color: blue">null</span>)</p>
<p style="margin: 0px">&#160;&#160;&#160; {</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: green">// Import the mapping</span></p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: #2b91af">XmlTypeMapping</span> mapping = importer.ImportTypeMapping(</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">new</span> <span style="color: #2b91af">XmlQualifiedName</span>(xsdElement.Name, xsd.TargetNamespace)</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; );</p>
<p style="margin: 0px">&#160;</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; exporter.ExportTypeMapping(mapping);</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">break</span>;</p>
<p style="margin: 0px">&#160;&#160;&#160; }</p>
<p style="margin: 0px">}</p>
<p style="margin: 0px">&#160;</p>
<p style="margin: 0px"><span style="color: green">// Build code generator</span></p>
<p style="margin: 0px"><span style="color: #2b91af">CSharpCodeProvider</span> codeProvider = <span style="color: blue">new</span> <span style="color: #2b91af">CSharpCodeProvider</span>();</p>
<p style="margin: 0px">&#160;</p>
<p style="margin: 0px"><span style="color: blue">using</span> (<span style="color: #2b91af">StreamWriter</span> sw = <span style="color: blue">new</span> <span style="color: #2b91af">StreamWriter</span>(<span style="color: #a31515">&quot;OutputFile.cs&quot;</span>))</p>
<p style="margin: 0px">{</p>
<p style="margin: 0px">&#160;&#160;&#160; codeProvider.GenerateCodeFromNamespace(ns, sw, <span style="color: blue">new</span> <span style="color: #2b91af">CodeGeneratorOptions</span>());</p>
<p style="margin: 0px">}</p>
</p></div>
<p>The code above iterates over items in the schema until the root element (<span class="cf"><span class="cb2">XmlSchemaElement</span></span>) is found, at which the importer will import the type mapping, and the exporter will export it to the <span class="cf"><span class="cb2">CodeNamespace </span></span>defined earlier. At the end of the for loop, the CodeNamespace object contains all of the types representing the XML schema. At the end, we tell a <span class="cf"><span class="cb2">CSharpCodeProvider </span></span>to generate code from the types in the namespace to an output file, ready for consumption. The code is very simple; however, we are not utilizing the CodeDom APIs to their full potential. Because the types are accessible before generating the code, we can make <em>any changes we desire</em> before writing the code. This is the crux of this post&#8212;being able to customize the generated code.</p>
<h3 id="making-your-modifications">Making Your Modifications</h3>
<p>If you are familiar with the CodeDom APIs, then at this point you can probably start making your own modifications. But, just in case you aren&#8217;t, I will quickly walk through how to generate XML documentation comments on the generated code members. Re-examining the loop over the objects in the XML schema, we can reasonably infer <em>based on our specific schema</em> that there is more than one object in the collection. In this case, the other named complex types are part of this collection; consequently, we can modify the code in the loop to consider elements and attributes:</p>
<div class="cf">
<p style="margin: 0px"><span style="color: green">// Cached copy of the types as IEnumerable&lt;T&gt; to use LINQ queries on.</span></p>
<p style="margin: 0px"><span style="color: #2b91af">IEnumerable</span>&lt;<span style="color: #2b91af">CodeTypeDeclaration</span>&gt; codeTypes = <span style="color: blue">null</span>;</p>
<p style="margin: 0px">&#160;</p>
<p style="margin: 0px"><span style="color: #2b91af">XmlSchemaObjectCollection</span> xsdObjects = xsd.Items;</p>
<p style="margin: 0px"><span style="color: blue">int</span> xsdObjectCount = xsdObjects.Count;</p>
<p style="margin: 0px"><span style="color: blue">for</span> (<span style="color: blue">int</span> i = 0; i &lt; xsdObjectCount; ++i)</p>
<p style="margin: 0px">{</p>
<p style="margin: 0px">&#160;&#160;&#160; <span style="color: #2b91af">XmlSchemaObject</span> xsdObject = xsdObjects[i];</p>
<p style="margin: 0px">&#160;</p>
<p style="margin: 0px">&#160;&#160;&#160; <span style="color: #2b91af">XmlSchemaElement</span> xsdElement = xsdObject <span style="color: blue">as</span> <span style="color: #2b91af">XmlSchemaElement</span>;</p>
<p style="margin: 0px">&#160;&#160;&#160; <span style="color: blue">if</span> (xsdElement != <span style="color: blue">null</span>)</p>
<p style="margin: 0px">&#160;&#160;&#160; {</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: green">// Import the mapping</span></p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: #2b91af">XmlTypeMapping</span> mapping = importer.ImportTypeMapping(</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">new</span> <span style="color: #2b91af">XmlQualifiedName</span>(xsdElement.Name, xsd.TargetNamespace)</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; );</p>
<p style="margin: 0px">&#160;</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; exporter.ExportTypeMapping(mapping);</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; codeTypes = ns.Types.Cast&lt;<span style="color: #2b91af">CodeTypeDeclaration</span>&gt;();</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">continue</span>;</p>
<p style="margin: 0px">&#160;&#160;&#160; }</p>
<p style="margin: 0px">&#160;</p>
<p style="margin: 0px">&#160;&#160;&#160; <span style="color: #2b91af">XmlSchemaComplexType</span> xsdComplexType = xsdObject <span style="color: blue">as</span> <span style="color: #2b91af">XmlSchemaComplexType</span>;</p>
<p style="margin: 0px">&#160;&#160;&#160; <span style="color: blue">if</span> (xsdComplexType != <span style="color: blue">null</span>)</p>
<p style="margin: 0px">&#160;&#160;&#160; {</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">string</span> complexTypeName = xsdComplexType.Name;</p>
<p style="margin: 0px">&#160;</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: green">// We should throw (with First) if we can&#8217;t find a type with this complex type&#8217;s name.</span></p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: #2b91af">CodeTypeDeclaration</span> codeTypeDeclaration = </p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; codeTypes.First(ct =&gt; ct.Name == complexTypeName);</p>
<p style="margin: 0px">&#160;</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: green">// Get documentation specifically for the complex type.</span></p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">string</span> documentation = GetDocumentation(xsdComplexType);</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; SetSummaryComment(codeTypeDeclaration, documentation);</p>
<p style="margin: 0px">&#160;</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: green">// Now get documentation for the attributes</span></p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: #2b91af">XmlSchemaObjectCollection</span> attributes = xsdComplexType.Attributes;</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">int</span> attributeCount = attributes.Count;</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">for</span> (<span style="color: blue">int</span> j = 0; j &lt; attributeCount; ++j)</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; {</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: #2b91af">XmlSchemaAttribute</span> xsdAttribute = (<span style="color: #2b91af">XmlSchemaAttribute</span>)attributes[j];</p>
<p style="margin: 0px">&#160;</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">string</span> attributeName = xsdAttribute.Name;</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: #2b91af">CodeMemberProperty</span> property = codeTypeDeclaration.Members.OfType&lt;<span style="color: #2b91af">CodeMemberProperty</span>&gt;().First(</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; prop =&gt; prop.Name == attributeName);</p>
<p style="margin: 0px">&#160;</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">string</span> attributeDocumentation = GetDocumentation(xsdAttribute);</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; SetSummaryComment(property, attributeDocumentation);</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; }</p>
<p style="margin: 0px">&#160;&#160;&#160; }</p>
<p style="margin: 0px">}</p>
</p></div>
<p>There are a few significant changes here. First, immediately after the type mapping is exported, we cast all of the <span class="cf"><span class="cb2">CodeNamespace</span></span>&#8217;s types to <span class="cf cb2">CodeTypeDeclaration</span>s for use later in the loop. On subsequent iterations of the loop, we anticipate running into <span class="cf"><span class="cb2">XmlSchemaComplexType</span></span> objects. The code then retrieves the appropriate <span class="cf cb2">CodeTypeDeclaration</span> which matches that complex type, retrieves the documentation for that type, and sets the summary comment. The pattern is repeated for the attributes in each complex type.</p>
<p>The <span class="cf">GetDocumentation</span> and <span class="cf">SetSummaryComment</span> methods are fairly simple and involve manipulating the object models of XML Schema and CodeDom, respectively, to achieve their goals. Fortunately for the <span class="cf">GetDocumentation</span> method, there is a base class in the object model which encapsulates all elements which can be annotated.</p>
<div class="cf">
<p style="margin: 0px"><span style="color: blue">private</span> <span style="color: blue">static</span> <span style="color: blue">string</span> GetDocumentation(<span style="color: #2b91af">XmlSchemaAnnotated</span> annotatedElement)</p>
<p style="margin: 0px">{</p>
<p style="margin: 0px">&#160;&#160;&#160; <span style="color: green">// Look inside the Annotation element</span></p>
<p style="margin: 0px">&#160;&#160;&#160; <span style="color: #2b91af">XmlSchemaAnnotation</span> annotation = annotatedElement.Annotation;</p>
<p style="margin: 0px">&#160;&#160;&#160; <span style="color: blue">if</span> (annotation != <span style="color: blue">null</span>)</p>
<p style="margin: 0px">&#160;&#160;&#160; {</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: #2b91af">XmlSchemaObjectCollection</span> annotationItems = annotation.Items;</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">if</span> (annotationItems.Count &gt; 0)</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; {</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: #2b91af">XmlSchemaDocumentation</span> xsdDocumentation =</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; annotationItems[0] <span style="color: blue">as</span> <span style="color: #2b91af">XmlSchemaDocumentation</span>;</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">if</span> (xsdDocumentation != <span style="color: blue">null</span>)</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; {</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: #2b91af">XmlNode</span>[] markup = xsdDocumentation.Markup;</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">if</span> (markup.Length &gt; 0)</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; {</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">return</span> markup[0].InnerText;</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; }</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; }</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; }</p>
<p style="margin: 0px">&#160;&#160;&#160; }</p>
<p style="margin: 0px">&#160;</p>
<p style="margin: 0px">&#160;&#160;&#160; <span style="color: blue">return</span> <span style="color: #2b91af">String</span>.Empty;</p>
<p style="margin: 0px">}</p>
</p></div>
<p>Above we assume that the xsd:documentation element will be the first one within the xsd:annotation element. <strong>This is not a safe assumption for all schemas.</strong></p>
<div class="cf">
<p style="margin: 0px"><span style="color: blue">private</span> <span style="color: blue">static</span> <span style="color: blue">void</span> SetSummaryComment(<span style="color: #2b91af">CodeTypeMember</span> codeTypeMember, <span style="color: blue">string</span> comment)</p>
<p style="margin: 0px">{</p>
<p style="margin: 0px">&#160;&#160;&#160; <span style="color: blue">if</span> (comment == <span style="color: blue">null</span> || <span style="color: #2b91af">String</span>.Empty.Equals(comment, <span style="color: #2b91af">StringComparison</span>.Ordinal))</p>
<p style="margin: 0px">&#160;&#160;&#160; {</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">return</span>;</p>
<p style="margin: 0px">&#160;&#160;&#160; }</p>
<p style="margin: 0px">&#160;</p>
<p style="margin: 0px">&#160;&#160;&#160; <span style="color: #2b91af">CodeCommentStatementCollection</span> comments = codeTypeMember.Comments;</p>
<p style="margin: 0px">&#160;</p>
<p style="margin: 0px">&#160;&#160;&#160; <span style="color: blue">if</span> (comments.Count == 0)</p>
<p style="margin: 0px">&#160;&#160;&#160; {</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; comments.Add(<span style="color: blue">new</span> <span style="color: #2b91af">CodeCommentStatement</span>(<span style="color: #2b91af">String</span>.Empty, <span style="color: blue">true</span>));</p>
<p style="margin: 0px">&#160;&#160;&#160; }</p>
<p style="margin: 0px">&#160;</p>
<p style="margin: 0px">&#160;&#160;&#160; comments[0].Comment.Text = <span style="color: #2b91af">String</span>.Format(</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: #a31515">&quot;&lt;summary&gt;{0} {1}{0} &lt;/summary&gt;&quot;</span>,</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: #2b91af">Environment</span>.NewLine,</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; comment);</p>
<p style="margin: 0px">}</p>
</p></div>
<h3 id="integrating-with-msbuild">Integrating with MSBuild</h3>
<p>The final step is to integrate this code generator with MSBuild. If you are familiar with creating custom tasks in MSBuild, then this will be review for you. However, the steps are as follows:</p>
<ol>
<li>(Optional) Encapsulate the business logic laid out above into a separate, re-usable class. </li>
<li>Create a class inheriting from <span class="cf">Microsoft.Build.Utilities.<span class="cb2">Task</span></span> (in Microsoft.Build.Utilities.dll or Microsoft.Build.Utilities.v3.5.dll). </li>
<li>Create properties for each parameter that the task uses to accomplish its goal. (You may consider items like XsdFileLocation or DestinationFile.) </li>
<li>Override the Execute method to carry out your custom logic, utilizing the properties as necessary. </li>
</ol>
<p>A sample implementation could look like this:</p>
<div class="cf">
<p style="margin: 0px"><span style="color: blue">public</span> <span style="color: blue">class</span> <span style="color: #2b91af">XsdGen</span> : <span style="color: #2b91af">Task</span></p>
<p style="margin: 0px">{</p>
<p style="margin: 0px">&#160;&#160;&#160; <span style="color: blue">public</span> <span style="color: blue">string</span> DestinationFile</p>
<p style="margin: 0px">&#160;&#160;&#160; {</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">get</span>;</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">set</span>;</p>
<p style="margin: 0px">&#160;&#160;&#160; }</p>
<p style="margin: 0px">&#160;</p>
<p style="margin: 0px">&#160;&#160;&#160; [<span style="color: #2b91af">Required</span>]</p>
<p style="margin: 0px">&#160;&#160;&#160; <span style="color: blue">public</span> <span style="color: blue">string</span> Namespace</p>
<p style="margin: 0px">&#160;&#160;&#160; {</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">get</span>;</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">set</span>;</p>
<p style="margin: 0px">&#160;&#160;&#160; }</p>
<p style="margin: 0px">&#160;</p>
<p style="margin: 0px">&#160;&#160;&#160; [<span style="color: #2b91af">Required</span>]</p>
<p style="margin: 0px">&#160;&#160;&#160; <span style="color: blue">public</span> <span style="color: blue">string</span> XsdLocation</p>
<p style="margin: 0px">&#160;&#160;&#160; {</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">get</span>;</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">set</span>;</p>
<p style="margin: 0px">&#160;&#160;&#160; }</p>
<p style="margin: 0px">&#160;</p>
<p style="margin: 0px">&#160;&#160;&#160; <span style="color: blue">public</span> <span style="color: blue">override</span> <span style="color: blue">bool</span> Execute()</p>
<p style="margin: 0px">&#160;&#160;&#160; {</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">try</span></p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; {</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: #2b91af">XsdCodeGenerator</span> generator = <span style="color: blue">new</span> <span style="color: #2b91af">XsdCodeGenerator</span>(XsdLocation, Namespace);</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; generator.DestinationFile = DestinationFile;</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; generator.Generate();</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">return</span> <span style="color: blue">true</span>;</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; }</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">catch</span> (<span style="color: #2b91af">Exception</span> ex)</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; {</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; Log.LogErrorFromException(ex, <span style="color: blue">false</span>);</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">return</span> <span style="color: blue">false</span>;</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; }</p>
<p style="margin: 0px">&#160;&#160;&#160; }</p>
<p style="margin: 0px">}</p>
</p></div>
<p>Once the task is created, we can go back to editing the project file as we did in the <a href="http://blogs.rev-net.com/ddewinter/2008/07/08/generate-serialization-classes-as-part-of-your-build-part-1/">first post in the series</a>. As a reminder, here is what we had before:</p>
<div class="cf">
<p style="margin: 0px"><span style="color: blue">&lt;</span><span style="color: #a31515">Target</span><span style="color: blue"> </span><span style="color: red">Name</span><span style="color: blue">=</span>&quot;<span style="color: blue">GenerateSerializationClasses</span>&quot;<span style="color: blue"> </span><span style="color: red">Inputs</span><span style="color: blue">=</span>&quot;<span style="color: blue">SampleSchema.xsd</span>&quot;<span style="color: blue"> </span><span style="color: red">Outputs</span><span style="color: blue">=</span>&quot;<span style="color: blue">SampleSchema.cs</span>&quot;<span style="color: blue">&gt;</span></p>
<p style="margin: 0px"><span style="color: blue">&#160; &lt;</span><span style="color: #a31515">Exec</span><span style="color: blue"> </span><span style="color: red">Command</span><span style="color: blue">=</span>&quot;<span style="color: red">&amp;quot;</span><span style="color: blue">C:\Program Files\Microsoft SDKs\Windows\v6.0\Bin\xsd.exe</span><span style="color: red">&amp;quot;</span><span style="color: blue"> SampleSchema.xsd /classes</span>&quot;<span style="color: blue"> /&gt;</span></p>
<p style="margin: 0px"><span style="color: blue">&lt;/</span><span style="color: #a31515">Target</span><span style="color: blue">&gt;</span></p>
<p style="margin: 0px"><span style="color: blue">&lt;</span><span style="color: #a31515">Target</span><span style="color: blue"> </span><span style="color: red">Name</span><span style="color: blue">=</span>&quot;<span style="color: blue">BeforeBuild</span>&quot;<span style="color: blue"> </span><span style="color: red">DependsOnTargets</span><span style="color: blue">=</span>&quot;<span style="color: blue">GenerateSerializationClasses</span>&quot;<span style="color: blue">&gt;</span></p>
<p style="margin: 0px"><span style="color: blue">&lt;/</span><span style="color: #a31515">Target</span><span style="color: blue">&gt;</span></p>
</p></div>
<p>And here is what we have now:</p>
<div class="cf"><span style="color: blue">&lt;</span><span style="color: #a31515">UsingTask</span><span style="color: blue"> </span><span style="color: red">AssemblyFile</span><span style="color: blue">=</span>&quot;<span style="color: blue">DeWinter.XsdGen.dll</span>&quot;<span style="color: blue"> </span><span style="color: red">TaskName</span><span style="color: blue">=</span>&quot;<span style="color: blue">XsdGen</span>&quot;<span style="color: blue"> /&gt;</span></div>
<div class="cf"><span style="color: blue"></span><span style="color: blue">&lt;</span><span style="color: #a31515">Target</span><span style="color: blue"> </span><span style="color: red">Name</span><span style="color: blue">=</span>&quot;<span style="color: blue">GenerateSerializationClasses</span>&quot;<span style="color: blue"> </span><span style="color: red">Inputs</span><span style="color: blue">=</span>&quot;<span style="color: blue">SampleSchema.xsd</span>&quot;<span style="color: blue"> </span><span style="color: red">Outputs</span><span style="color: blue">=</span>&quot;<span style="color: blue">SampleSchema.g.cs</span>&quot;<span style="color: blue">&gt;</span></div>
<p class="cf" style="margin: 0px"><span style="color: blue">&#160; &lt;</span><span style="color: #a31515">XsdGen</span><span style="color: blue"> </span><span style="color: red">DestinationFile</span><span style="color: blue">=</span>&quot;<span style="color: blue">SampleSchema.g.cs</span>&quot;<span style="color: blue"> </span><span style="color: red">Namespace</span><span style="color: blue">=</span>&quot;<span style="color: blue">DeWinter.Samples.Serialization</span>&quot;<span style="color: blue"> </span><span style="color: red">XsdLocation</span><span style="color: blue">=</span>&quot;<span style="color: blue">SampleSchema.xsd</span>&quot;<span style="color: blue"> /&gt;</span></p>
<p class="cf" style="margin: 0px"><span style="color: blue">&lt;/</span><span style="color: #a31515">Target</span><span style="color: blue">&gt;</span></p>
<p class="cf" style="margin: 0px"><span style="color: blue">&lt;</span><span style="color: #a31515">Target</span><span style="color: blue"> </span><span style="color: red">Name</span><span style="color: blue">=</span>&quot;<span style="color: blue">BeforeBuild</span>&quot;<span style="color: blue"> </span><span style="color: red">DependsOnTargets</span><span style="color: blue">=</span>&quot;<span style="color: blue">GenerateSerializationClasses</span>&quot;<span style="color: blue">&gt;</span></p>
<p class="cf" style="margin: 0px"><span style="color: blue">&lt;/</span><span style="color: #a31515">Target</span><span style="color: blue">&gt;</span></p>
<p>Before the actual compilation step, MSBuild will execute the GenerateSerializationClasses target, locate the XsdGen task in DeWinter.XsdGen.dll, and then call the Execute method on that task. This will generate the XML Schema object model as desired (notice the XML comments below):</p>
<p><a href="http://blogs.rev-net.com/ddewinter/wp-content/uploads/2008/09/image.png"><img style="border-top-width: 0px; border-left-width: 0px; border-bottom-width: 0px; border-right-width: 0px" height="316" alt="XML Schema Object Model" src="http://blogs.rev-net.com/ddewinter/wp-content/uploads/2008/09/image-thumb.png" width="649" border="0" /></a> </p>
<h3 id="let-the-buyer-beware">Let the Buyer Beware</h3>
<p>The ironic part about writing this post is that the more I wrote, the less appealing this method was. Think about it; you are essentially writing a <em>replacement</em> for xsd.exe. The more generalized you want to make it the more difficult it becomes. In this post I accounted for named complex types only. What about anonymous complex types? Complex types that are extensions or restrictions of other complex types? Other facets like enumerations? XML Schema has a multitude of different elements, and building a suitable replacement for xsd.exe that suits your needs <em>just isn&#8217;t worth it</em> most of the time.</p>
<p>The other problem I have with it is just that there is so little gain to justify the amount of work you would put into it. My original justification for investigating this method was that it made the object model much nicer to work with, because it was well-commented and not as awkward to use as the normally generated OM (object model). But that&#8217;s really subjective!</p>
<p>My personal opinion, though, is that the object model generated by xsd.exe is fine. If you really want an object model that is &quot;better&quot; to work with (whatever &quot;better&quot; means to you), then build an abstraction layer on top of the generated OM and have a service class translate between the two. In my next post on serialization I&#8217;ll cover this.</p>
<h3 id="source-code">Reference Source Code</h3>
<p>This was my reference for this post, and there quite a few more features included, like stripping suffixes from type names and &quot;correcting&quot; the casing of the generated classes. (Hmm, that is becoming a theme among my work now, isn&#8217;t it&#8230;?). But it is not complete and probably works only against very limited situations. I would advise you to use this for reference only. And of course, the disclaimer&#8230;</p>
<p><strong style="color: red">Disclaimer</strong>: This software is provided as is, and I am not responsible or liable for any damages arising in any way out of the use of this software, even if advised of the possibility of such damage.</p>
<p><a href="http://blogs.rev-net.com/ddewinter/wp-content/uploads/2008/09/DeWinter.XsdGen.zip">Download</a></p>
]]></content:encoded>
			<wfw:commentRss>http://blogs.rev-net.com/ddewinter/2008/09/28/generate-serialization-classes-as-part-of-your-build-part-2/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>DBML Fixup Preview</title>
		<link>http://blogs.rev-net.com/ddewinter/2008/08/24/dbml-fixup-preview/</link>
		<comments>http://blogs.rev-net.com/ddewinter/2008/08/24/dbml-fixup-preview/#comments</comments>
		<pubDate>Mon, 25 Aug 2008 03:41:44 +0000</pubDate>
		<dc:creator>David DeWinter</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[DBML Fixup]]></category>
		<category><![CDATA[LINQ to SQL]]></category>
		<category><![CDATA[VSX]]></category>
		<category><![CDATA[Visual Studio 2008]]></category>
		<category><![CDATA[DBML]]></category>
		<category><![CDATA[DBML Sync]]></category>
		<category><![CDATA[LINQ]]></category>
		<category><![CDATA[LINQ to SQL Designer]]></category>
		<category><![CDATA[Schema Sync]]></category>
		<category><![CDATA[Visual Studio]]></category>

		<guid isPermaLink="false">http://blogs.rev-net.com/ddewinter/2008/08/24/dbml-fixup-preview/</guid>
		<description><![CDATA[Back in February I blogged about DBML Fixup&#8212;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&#8217;s six months later, and I have a much clearer vision of what the [...]]]></description>
			<content:encoded><![CDATA[<p>Back in <a href="http://blogs.rev-net.com/ddewinter/2008/02/16/linq-to-sql-and-database-schema-sync/">February</a> I blogged about DBML Fixup&#8212;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&#8217;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.</p>
<p>&#160;</p>
<div id="media"><object id="csSWF" codebase="http://active.macromedia.com/flash7/cabs/ swflash.cab#version=9,0,28,0" height="498" width="640" classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000"><param name="_cx" value="16933"><param name="_cy" value="13176"><param name="FlashVars" value=""><param name="Movie" value="http://blogs.rev-net.com/ddewinter/wp-content/screencasts/dbmlfixup/DBMLFixupAug08.swf"><param name="Src" value="http://blogs.rev-net.com/ddewinter/wp-content/screencasts/dbmlfixup/DBMLFixupAug08.swf"><param name="WMode" value="Window"><param name="Play" value="0"><param name="Loop" value="-1"><param name="Quality" value="High"><param name="SAlign" value=""><param name="Menu" value="-1"><param name="Base" value=""><param name="AllowScriptAccess" value="always"><param name="Scale" value="ShowAll"><param name="DeviceFont" value="0"><param name="EmbedMovie" value="0"><param name="BGColor" value="1A1A1A"><param name="SWRemote" value=""><param name="MovieData" value=""><param name="SeamlessTabbing" value="1"><param name="Profile" value="0"><param name="ProfileAddress" value=""><param name="ProfilePort" value="0"><param name="AllowNetworking" value="all"><param name="AllowFullScreen" value="true"><embed name="csSWF" src="http://blogs.rev-net.com/ddewinter/wp-content/screencasts/dbmlfixup/DBMLFixupAug08.swf" width="640" height="498" bgcolor="#1a1a1a" quality="best" allowscriptaccess="always" allowfullscreen="true" scale="showall" flashvars="autostart=false" pluginspage="http://www.macromedia.com/shockwave/download/index.cgi?P1_Prod_Version=ShockwaveFlash"></embed></object></div>
<p>&#160;</p>
<p>Here are some previous posts which (briefly) describe the domain:</p>
<p><a title="http://blogs.rev-net.com/ddewinter/2008/02/16/the-linq-to-sql-model/" href="http://blogs.rev-net.com/ddewinter/2008/02/16/the-linq-to-sql-model/">http://blogs.rev-net.com/ddewinter/2008/02/16/the-linq-to-sql-model/</a></p>
<p><a title="http://blogs.rev-net.com/ddewinter/2008/02/16/linq-to-sql-and-database-schema-sync/" href="http://blogs.rev-net.com/ddewinter/2008/02/16/linq-to-sql-and-database-schema-sync/">http://blogs.rev-net.com/ddewinter/2008/02/16/linq-to-sql-and-database-schema-sync/</a></p>
<p>&#160;</p>
<p>Any ideas about directions for the tool? Or maybe something that wasn&#8217;t covered in the screencast? I&#8217;d love to hear your ideas.</p>
]]></content:encoded>
			<wfw:commentRss>http://blogs.rev-net.com/ddewinter/2008/08/24/dbml-fixup-preview/feed/</wfw:commentRss>
		<slash:comments>13</slash:comments>
		</item>
		<item>
		<title>Generate Serialization Classes As Part of Your Build (Part 1)</title>
		<link>http://blogs.rev-net.com/ddewinter/2008/07/08/generate-serialization-classes-as-part-of-your-build-part-1/</link>
		<comments>http://blogs.rev-net.com/ddewinter/2008/07/08/generate-serialization-classes-as-part-of-your-build-part-1/#comments</comments>
		<pubDate>Tue, 08 Jul 2008 12:58:56 +0000</pubDate>
		<dc:creator>David DeWinter</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[MSBuild]]></category>
		<category><![CDATA[Visual Studio 2008]]></category>
		<category><![CDATA[.NET]]></category>
		<category><![CDATA[Automating]]></category>
		<category><![CDATA[Serialization]]></category>
		<category><![CDATA[XML]]></category>
		<category><![CDATA[xsd.exe]]></category>

		<guid isPermaLink="false">http://blogs.rev-net.com/ddewinter/2008/07/08/generate-serialization-classes-as-part-of-your-build-part-1/</guid>
		<description><![CDATA[Yes, I am back from the grave. The past two months have been infuriatingly busy for me (and you&#8217;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 [...]]]></description>
			<content:encoded><![CDATA[<p>Yes, I <em>am</em> back from the grave. The past two months have been infuriatingly busy for me (and you&#8217;ll see why in a later post), but I finally have some time to write again. The topic? Generating serialization classes <em>as part of your build process </em>(Part 1) and <em>in your own way </em>(Part 2).</p>
<p>I might reach only a niche of .NET developers with this post, but it&#8217;s something that niche should be aware of. There is a tool in the .NET framework called <a href="http://msdn.microsoft.com/en-us/library/x6c1kb0s(VS.71).aspx">xsd.exe</a>, 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.</p>
<p>Wouldn&#8217;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.</p>
<p><span id="more-105"></span></p>
<p>We&#8217;ll start from scratch here, so first things first: create a new project. Here I&#8217;ll just create a class library called &quot;DeWinterXsd&quot;. Then add a new XML Schema file to the project. (You can find it under the Data category of items.)</p>
<p style="list-style-type: none"><a href="http://blogs.rev-net.com/ddewinter/wp-content/uploads/2008/07/image.png"><img style="border-top-width: 0px; border-left-width: 0px; border-bottom-width: 0px; border-right-width: 0px" height="486" alt="image" src="http://blogs.rev-net.com/ddewinter/wp-content/uploads/2008/07/image-thumb.png" width="808" border="0" /></a></p>
<p>Replace the contents of the schema file with the following snippet. It&#8217;s a very simple schema, featuring a root element and two child elements with three attributes among them.</p>
<div style="font-size: 8pt; background: white; margin-bottom: 10px; color: black; font-family: courier new">
<p style="margin: 0px"><span style="color: blue">&lt;?</span><span style="color: #a31515">xml</span><span style="color: blue"> </span><span style="color: red">version</span><span style="color: blue">=</span>&quot;<span style="color: blue">1.0</span>&quot;<span style="color: blue"> </span><span style="color: red">encoding</span><span style="color: blue">=</span>&quot;<span style="color: blue">utf-8</span>&quot;<span style="color: blue">?&gt;</span></p>
<p style="margin: 0px"><span style="color: blue">&lt;</span><span style="color: #a31515">xs:schema</span><span style="color: blue"> </span><span style="color: red">id</span><span style="color: blue">=</span>&quot;<span style="color: blue">SampleSchema</span>&quot;</p>
<p style="margin: 0px"><span style="color: blue">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; </span><span style="color: red">targetNamespace</span><span style="color: blue">=</span>&quot;<span style="color: blue">http://schemas.example.com/SampleSchema.xsd</span>&quot;</p>
<p style="margin: 0px"><span style="color: blue">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; </span><span style="color: red">elementFormDefault</span><span style="color: blue">=</span>&quot;<span style="color: blue">qualified</span>&quot;</p>
<p style="margin: 0px"><span style="color: blue">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; </span><span style="color: red">xmlns</span><span style="color: blue">=</span>&quot;<span style="color: blue">http://schemas.example.com/SampleSchema.xsd</span>&quot;</p>
<p style="margin: 0px"><span style="color: blue">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; </span><span style="color: red">xmlns:xs</span><span style="color: blue">=</span>&quot;<span style="color: blue">http://www.w3.org/2001/XMLSchema</span>&quot;<span style="color: blue">&gt;</span></p>
<p style="margin: 0px"><span style="color: blue">&#160; &lt;</span><span style="color: #a31515">xs:element</span><span style="color: blue"> </span><span style="color: red">name</span><span style="color: blue">=</span>&quot;<span style="color: blue">root</span>&quot;<span style="color: blue">&gt;</span></p>
<p style="margin: 0px"><span style="color: blue">&#160;&#160;&#160; &lt;</span><span style="color: #a31515">xs:complexType</span><span style="color: blue">&gt;</span></p>
<p style="margin: 0px"><span style="color: blue">&#160;&#160;&#160;&#160;&#160; &lt;</span><span style="color: #a31515">xs:sequence</span><span style="color: blue">&gt;</span></p>
<p style="margin: 0px"><span style="color: blue">&#160;&#160;&#160;&#160;&#160;&#160;&#160; &lt;</span><span style="color: #a31515">xs:element</span><span style="color: blue"> </span><span style="color: red">name</span><span style="color: blue">=</span>&quot;<span style="color: blue">first</span>&quot;<span style="color: blue">&gt;</span></p>
<p style="margin: 0px"><span style="color: blue">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; &lt;</span><span style="color: #a31515">xs:complexType</span><span style="color: blue">&gt;</span></p>
<p style="margin: 0px"><span style="color: blue">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; &lt;</span><span style="color: #a31515">xs:attribute</span><span style="color: blue"> </span><span style="color: red">name</span><span style="color: blue">=</span>&quot;<span style="color: blue">name</span>&quot;<span style="color: blue"> </span><span style="color: red">type</span><span style="color: blue">=</span>&quot;<span style="color: blue">xs:token</span>&quot;<span style="color: blue"> /&gt;</span></p>
<p style="margin: 0px"><span style="color: blue">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; &lt;</span><span style="color: #a31515">xs:attribute</span><span style="color: blue"> </span><span style="color: red">name</span><span style="color: blue">=</span>&quot;<span style="color: blue">value</span>&quot;<span style="color: blue"> </span><span style="color: red">type</span><span style="color: blue">=</span>&quot;<span style="color: blue">xs:token</span>&quot;<span style="color: blue"> /&gt;</span></p>
<p style="margin: 0px"><span style="color: blue">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; &lt;/</span><span style="color: #a31515">xs:complexType</span><span style="color: blue">&gt;</span></p>
<p style="margin: 0px"><span style="color: blue">&#160;&#160;&#160;&#160;&#160;&#160;&#160; &lt;/</span><span style="color: #a31515">xs:element</span><span style="color: blue">&gt;</span></p>
<p style="margin: 0px"><span style="color: blue">&#160;&#160;&#160;&#160;&#160;&#160;&#160; &lt;</span><span style="color: #a31515">xs:element</span><span style="color: blue"> </span><span style="color: red">name</span><span style="color: blue">=</span>&quot;<span style="color: blue">second</span>&quot;<span style="color: blue">&gt;</span></p>
<p style="margin: 0px"><span style="color: blue">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; &lt;</span><span style="color: #a31515">xs:complexType</span><span style="color: blue">&gt;</span></p>
<p style="margin: 0px"><span style="color: blue">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; &lt;</span><span style="color: #a31515">xs:attribute</span><span style="color: blue"> </span><span style="color: red">name</span><span style="color: blue">=</span>&quot;<span style="color: blue">origin</span>&quot;<span style="color: blue"> </span><span style="color: red">type</span><span style="color: blue">=</span>&quot;<span style="color: blue">xs:token</span>&quot;<span style="color: blue"> /&gt;</span></p>
<p style="margin: 0px"><span style="color: blue">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; &lt;/</span><span style="color: #a31515">xs:complexType</span><span style="color: blue">&gt;</span></p>
<p style="margin: 0px"><span style="color: blue">&#160;&#160;&#160;&#160;&#160;&#160;&#160; &lt;/</span><span style="color: #a31515">xs:element</span><span style="color: blue">&gt;</span></p>
<p style="margin: 0px"><span style="color: blue">&#160;&#160;&#160;&#160;&#160; &lt;/</span><span style="color: #a31515">xs:sequence</span><span style="color: blue">&gt;</span></p>
<p style="margin: 0px"><span style="color: blue">&#160;&#160;&#160; &lt;/</span><span style="color: #a31515">xs:complexType</span><span style="color: blue">&gt;</span></p>
<p style="margin: 0px"><span style="color: blue">&#160; &lt;/</span><span style="color: #a31515">xs:element</span><span style="color: blue">&gt;</span></p>
<p style="margin: 0px"><span style="color: blue">&lt;/</span><span style="color: #a31515">xs:schema</span><span style="color: blue">&gt;</span></p>
</p></div>
<p>Now that you have the schema, add a new class to your project with the same name as your XML schema file. For example, the name of my schema file is &quot;SampleSchema.xsd&quot;, and the name of the class is &quot;SampleSchema.cs&quot;. This should nest the .cs file underneath the schema file, akin to how code-behind files are nested under UI files (<em>e.g.</em> Windows Forms, XAML). So how do we generate serialization classes? Right click on your project file and select &quot;Unload Project&quot;.</p>
<p><a href="http://blogs.rev-net.com/ddewinter/wp-content/uploads/2008/07/image1.png"><img style="border-top-width: 0px; border-left-width: 0px; border-bottom-width: 0px; border-right-width: 0px" height="519" alt="image" src="http://blogs.rev-net.com/ddewinter/wp-content/uploads/2008/07/image-thumb1.png" width="312" border="0" /></a></p>
<p>And then right click on the project again and click &quot;Edit <em>xxx</em>.csproj&quot;.</p>
<p><a href="http://blogs.rev-net.com/ddewinter/wp-content/uploads/2008/07/image2.png"><img style="border-top-width: 0px; border-left-width: 0px; border-bottom-width: 0px; border-right-width: 0px" height="169" alt="image" src="http://blogs.rev-net.com/ddewinter/wp-content/uploads/2008/07/image-thumb2.png" width="281" border="0" /></a></p>
<p>Now you&#8217;ll see the contents of the .csproj file itself. If you&#8217;re not familiar with the MSBuild system, then here&#8217;s the gist of it. Building a project in your solution executes a series of tasks, which are logically grouped into <em>targets</em>. Building will actually run only one target, <em>Compile</em>. However, the Compile target can depend on other targets in order to run correctly, so those targets are run before Compile, and so on. Take a look at your output window sometime while building; it will show you the tasks being executed by each target. For more information, read an MSBuild tutorial, like <a href="http://www.codeplex.com/msbuildshellex/Wiki/View.aspx?title=MSBuild%20Tutorial&amp;referringTitle=Manual">this one</a>.</p>
<p>What we&#8217;ll do now is say that before the compilation target occurs, we want to generate serialization classes using xsd.exe. Scroll to the bottom of the file and you should see this:</p>
<div style="font-size: 8pt; background: white; margin-bottom: 10px; color: black; font-family: courier new">
<p style="margin: 0px"><span style="color: blue">&lt;!&#8211;</span><span style="color: green"> To modify your build process, add your task inside one of the targets below and uncomment it.</span></p>
<p style="margin: 0px"><span style="color: green">Other similar extension points exist, see Microsoft.Common.targets.</span></p>
<p style="margin: 0px"><span style="color: green">&lt;Target Name=&quot;BeforeBuild&quot;&gt;</span></p>
<p style="margin: 0px"><span style="color: green">&lt;/Target&gt;</span></p>
<p style="margin: 0px"><span style="color: green">&lt;Target Name=&quot;AfterBuild&quot;&gt;</span></p>
<p style="margin: 0px"><span style="color: green">&lt;/Target&gt;</span></p>
<p style="margin: 0px"><span style="color: blue">&#8211;&gt;</span></p>
</p></div>
<p>For now, we&#8217;ll uncomment the BeforeBuild target and insert a task to run xsd.exe. But since this is logically better off as its own target (<em>e.g.</em> GenerateSerializationClasses), we&#8217;ll specify that the BeforeBuild target depends on another target of our creation.</p>
<div style="font-size: 8pt; background: white; margin-bottom: 10px; color: black; font-family: courier new">
<p style="margin: 0px"><span style="color: blue">&lt;</span><span style="color: #a31515">Target</span><span style="color: blue"> </span><span style="color: red">Name</span><span style="color: blue">=</span>&quot;<span style="color: blue">GenerateSerializationClasses</span>&quot;<span style="color: blue">&gt;</span></p>
<p style="margin: 0px"><span style="color: blue">&lt;/</span><span style="color: #a31515">Target</span><span style="color: blue">&gt;</span></p>
<p style="margin: 0px"><span style="color: blue">&lt;</span><span style="color: #a31515">Target</span><span style="color: blue"> </span><span style="color: red">Name</span><span style="color: blue">=</span>&quot;<span style="color: blue">BeforeBuild</span>&quot;<span style="color: blue"> </span><span style="color: red">DependsOnTargets</span><span style="color: blue">=</span>&quot;<span style="color: blue">GenerateSerializationClasses</span>&quot;<span style="color: blue">&gt;</span></p>
<p style="margin: 0px"><span style="color: blue">&lt;/</span><span style="color: #a31515">Target</span><span style="color: blue">&gt;</span></p>
</p></div>
<p>I&#8217;ve placed the above lines right above the comments that discuss the BeforeBuild and AfterBuild targets (&quot;To modify your build process, add your task&#8230;&quot;). Now&#8230;to actually do something inside GenerateSerializationClasses requires the use of the Exec task, which as its name implies, will execute a task as if running it from the command line. Here we need to run xsd.exe, so we need to find where this tool is located. To do this easily, run &quot;where xsd.exe&quot; from a Visual Studio Command Prompt. My xsd.exe is in one of the Windows SDK directories, so I&#8217;ll add it to the Exec task like this:</p>
<div style="font-size: 8pt; background: white; margin-bottom: 10px; color: black; font-family: courier new">
<p style="margin: 0px"><span style="color: blue">&lt;</span><span style="color: #a31515">Target</span><span style="color: blue"> </span><span style="color: red">Name</span><span style="color: blue">=</span>&quot;<span style="color: blue">GenerateSerializationClasses</span>&quot;<span style="color: blue">&gt;</span></p>
<p style="margin: 0px"><span style="color: blue">&#160; &lt;</span><span style="color: #a31515">Exec</span><span style="color: blue"> </span><span style="color: red">Command</span><span style="color: blue">=</span>&quot;<span style="color: red">&amp;quot;</span><span style="color: blue">C:\Program Files\Microsoft SDKs\Windows\v6.0\Bin\xsd.exe</span><span style="color: red">&amp;quot;</span><span style="color: blue"> SampleSchema.xsd /classes</span>&quot;<span style="color: blue"> /&gt;</span></p>
<p style="margin: 0px"><span style="color: blue">&lt;/</span><span style="color: #a31515">Target</span><span style="color: blue">&gt;</span></p>
</p></div>
<p>Straightforward, right? The Exec task tells MSBuild to run xsd.exe using the specified command parameters, which will generate serialization classes based off my XSD file (SampleSchema.xsd). If you reload and rebuild your project, then you&#8217;ll see the serialization classes appear in the .cs file you provided. But there&#8217;s one more thing we can do here first! It makes sense that we want to generate classes only when the schema file has actually changed, so we&#8217;ll need a few more attributes to the GenerateSerializationClasses target. The <em>Inputs</em> attribute specifies the inputs to consider for the target, and the <em>Outputs</em> attribute specifies the outputs to consider for the target. MSBuild will use this data to determine whether to run the target at all. Here, our logic is simple: if the schema file has been modified after the last modified time of the class file, then run the target, and that&#8217;s exactly what MSBuild will do. The final XML snippet:</p>
<div style="font-size: 8pt; background: white; margin-bottom: 10px; color: black; font-family: courier new">
<p style="margin: 0px"><span style="color: blue">&lt;</span><span style="color: #a31515">Target</span><span style="color: blue"> </span><span style="color: red">Name</span><span style="color: blue">=</span>&quot;<span style="color: blue">GenerateSerializationClasses</span>&quot;<span style="color: blue"> </span><span style="color: red">Inputs</span><span style="color: blue">=</span>&quot;<span style="color: blue">SampleSchema.xsd</span>&quot;<span style="color: blue"> </span><span style="color: red">Outputs</span><span style="color: blue">=</span>&quot;<span style="color: blue">SampleSchema.cs</span>&quot;<span style="color: blue">&gt;</span></p>
<p style="margin: 0px"><span style="color: blue">&#160; &lt;</span><span style="color: #a31515">Exec<span style="color: #0000ff"> </span></span><span style="color: red">Command</span><span style="color: blue">=</span>&quot;<span style="color: red">&amp;quot;</span><span style="color: blue">C:\Program Files\Microsoft SDKs\Windows\v6.0\Bin\xsd.exe</span><span style="color: red">&amp;quot;</span><span style="color: blue"> SampleSchema.xsd /classes</span>&quot;<span style="color: blue"> /&gt;</span></p>
<p style="margin: 0px"><span style="color: blue">&lt;/</span><span style="color: #a31515">Target</span><span style="color: blue">&gt;</span></p>
<p style="margin: 0px"><span style="color: blue">&lt;</span><span style="color: #a31515">Target</span><span style="color: blue"> </span><span style="color: red">Name</span><span style="color: blue">=</span>&quot;<span style="color: blue">BeforeBuild</span>&quot;<span style="color: blue"> </span><span style="color: red">DependsOnTargets</span><span style="color: blue">=</span>&quot;<span style="color: blue">GenerateSerializationClasses</span>&quot;<span style="color: blue">&gt;</span></p>
<p style="margin: 0px"><span style="color: blue">&lt;/</span><span style="color: #a31515">Target</span><span style="color: blue">&gt;</span></p>
<p style="margin: 0px"><span style="color: blue">&lt;!&#8211;</span><span style="color: green"> To modify your build process, add your task inside one of the targets below and uncomment it. </span></p>
<p style="margin: 0px"><span style="color: green">Other similar extension points exist, see Microsoft.Common.targets.</span></p>
<p style="margin: 0px"><span style="color: green">&lt;Target Name=&quot;BeforeBuild&quot;&gt;</span></p>
<p style="margin: 0px"><span style="color: green">&lt;/Target&gt;</span></p>
<p style="margin: 0px"><span style="color: green">&lt;Target Name=&quot;AfterBuild&quot;&gt;</span></p>
<p style="margin: 0px"><span style="color: green">&lt;/Target&gt;</span></p>
<p style="margin: 0px"><span style="color: blue">&#8211;&gt;</span></p>
</p></div>
<p>Now, if you reload and rebuild your project, you can see the fruits of your labor:</p>
<p><a href="http://blogs.rev-net.com/ddewinter/wp-content/uploads/2008/07/image3.png"><img style="border-top-width: 0px; border-left-width: 0px; border-bottom-width: 0px; border-right-width: 0px" height="544" alt="image" src="http://blogs.rev-net.com/ddewinter/wp-content/uploads/2008/07/image-thumb3.png" width="648" border="0" /></a></p>
<p>We&#8217;ve generated the code, but it&#8217;s not the nicest output. Our classes have camel-cased names to match our element names, and the comments are non-existent for classes and publicly exposed members. Of course, we didn&#8217;t add any comments in our XML schema, but even if we used the xs:documentation element to document our elements and attributes, those comments <em>would not</em> be carried across to the generated code.</p>
<p>Next time, I&#8217;ll show you how to remedy these and other problems by building your own MSBuild task that can generate the same quality of code as xsd.exe but with a few custom enhancements.</p>
]]></content:encoded>
			<wfw:commentRss>http://blogs.rev-net.com/ddewinter/2008/07/08/generate-serialization-classes-as-part-of-your-build-part-1/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>The ExceptionMessageBox</title>
		<link>http://blogs.rev-net.com/ddewinter/2007/12/01/the-exceptionmessagebox/</link>
		<comments>http://blogs.rev-net.com/ddewinter/2007/12/01/the-exceptionmessagebox/#comments</comments>
		<pubDate>Sat, 01 Dec 2007 17:06:20 +0000</pubDate>
		<dc:creator>David DeWinter</dc:creator>
				<category><![CDATA[C#]]></category>

		<guid isPermaLink="false">http://dev.rev-net.com/blog/ddewinter/?p=24</guid>
		<description><![CDATA[Ever seen this in your application?

Yes? Then this article is for you. If not, you might know what this entry&#8217;s going to cover, but perhaps you&#8217;ll learn something new.
In tools I&#8217;ve been building, I&#8217;ve always been dissatisfied with this sort of &#34;error reporting&#34; (outside of logging, of course), but none of us have had the [...]]]></description>
			<content:encoded><![CDATA[<p>Ever seen this in your application?</p>
<p><img alt="TargetInvocationException" src="http://blogs.rev-net.com/ddewinter/wp-content/uploads/2007/12/targetinvocationexception.png" /></p>
<p>Yes? Then this article is for you. If not, you might know what this entry&#8217;s going to cover, but perhaps you&#8217;ll learn something new.</p>
<p>In tools I&#8217;ve been building, I&#8217;ve always been dissatisfied with this sort of &quot;error reporting&quot; (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&#8211;thank goodness we didn&#8217;t! Yesterday I read about the <a href="http://msdn2.microsoft.com/en-us/library/microsoft.sqlserver.messagebox.exceptionmessagebox.aspx">ExceptionMessageBox</a> class, and this is the sort of thing I&#8217;ve been waiting for! (Except it&#8217;s been out for well over a year&#8230;but that&#8217;s another story).</p>
<p>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:</p>
<p><a href="http://blogs.rev-net.com/ddewinter/wp-content/uploads/2007/12/targetinvocationexception-2.png">New and Improved</a></p>
<p>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 &quot;Show Technical Details&quot; icon in the toolbar (the button on the right) you&#8217;ll see a much appreciated stack trace for each of the exceptions in your chain.</p>
<p><a href="http://blogs.rev-net.com/ddewinter/wp-content/uploads/2007/12/targetinvocationexception-details.png">Details</a></p>
<p>All of this is accomplished with two lines of code:</p>
<div style="font-size: 8pt; background: white; margin-bottom: 10px; color: black; font-family: courier new; white-space: normal">
<p style="margin: 0px; text-align: left"><span style="color: gray">///</span><span style="color: green"> </span><span style="color: gray">&lt;summary&gt;</span></p>
<p style="margin: 0px; text-align: left"><span style="color: gray">///</span><span style="color: green"> Handles and logs the specified </span><span style="color: gray">&lt;see cref=&quot;Exception&quot;/&gt;</span><span style="color: green">.</span></p>
<p style="margin: 0px; text-align: left"><span style="color: gray">///</span><span style="color: green"> </span><span style="color: gray">&lt;/summary&gt;</span></p>
<p style="margin: 0px; text-align: left"><span style="color: gray">///</span><span style="color: green"> </span><span style="color: gray">&lt;param name=&quot;exception&quot;&gt;</span><span style="color: green">The </span><span style="color: gray">&lt;see cref=&quot;Exception&quot;/&gt;</span><span style="color: green"> to handle.</span><span style="color: gray">&lt;/param&gt;</span></p>
<p style="margin: 0px; text-align: left"><span style="color: blue">private</span> <span style="color: blue">static</span> <span style="color: blue">void</span> HandleException(<span style="color: #2b91af">Exception</span> exception)</p>
<p style="margin: 0px; text-align: left">{</p>
<p style="margin: 0px; text-align: left">&#160;&#160;&#160; <span style="color: #2b91af">ExceptionMessageBox</span> mbox = <span style="color: blue">new</span> <span style="color: #2b91af">ExceptionMessageBox</span>(exception);</p>
<p style="margin: 0px; text-align: left">&#160;&#160;&#160; mbox.Show(<span style="color: blue">null</span>);</p>
<p style="margin: 0px; text-align: left">}</p>
</p></div>
<p>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 <a href="http://www.microsoft.com/downloads/details.aspx?FamilyID=df0ba5aa-b4bd-4705-aa0a-b477ba72a9cb&amp;DisplayLang=en">this page</a>. (Search for &quot;Exception Message Box.&quot;)</p>
<p>In addition, the ExceptionMessageBox supports a fair number of properties that should be touched on. We&#8217;ll cover the highlights here:</p>
<p><strong>Properties</strong></p>
<ul>
<li>Beep (Boolean) &#8211; Specifies whether the ExceptionMessageBox beeps when it is launched (similar to a normal MessageBox). </li>
<li>Buttons (<a href="http://msdn2.microsoft.com/en-us/library/microsoft.sqlserver.messagebox.exceptionmessageboxbuttons.aspx">ExceptionMessageBoxButtons</a>) &#8211; 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. </li>
<li>Caption (String) &#8211; The caption/title of the ExceptionMessageBox form. </li>
<li>CustomDialogResult (<a href="http://msdn2.microsoft.com/en-us/library/microsoft.sqlserver.messagebox.exceptionmessageboxdialogresult.aspx">ExceptionMessageBoxDialogResult</a>) &#8211; Specifies the button that was clicked when using custom buttons. </li>
<li>CustomSymbol (Bitmap) &#8211; Specifies a custom image to display instead of the normal Asterisk, Error, Warning, Information, etc. </li>
<li>DefaultDialogResult (DialogResult) &#8211; Specifies the result of user action on the dialog when not using custom buttons. </li>
<li>IsCheckBoxChecked (Boolean) &#8211; Specifies whether a check box for &quot;Do not show this dialog again&quot; was checked. </li>
<li>Message (Exception) &#8211; The original exception passed into the ExceptionMessageBox constructor. </li>
<li>MessageLevelDefault (Int32) &#8211; 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. </li>
<li>Options (<a href="http://msdn2.microsoft.com/en-us/library/microsoft.sqlserver.messagebox.exceptionmessageboxoptions.aspx">ExceptionMessageBoxOptions</a>) &#8211; Enables various options like right-to-left reading or right alignment. </li>
<li>ShowCheckBox (Boolean) &#8211; Specifies whether to show the checkbox which enables developers to hook into users&#8217; preferences on whether they want to show the dialog again. </li>
<li>ShowToolBar (Boolean) &#8211; Specifies whether to show the toolbar (which allows copying text from the message and showing technical details). </li>
<li>Symbol (<a href="http://msdn2.microsoft.com/en-us/library/microsoft.sqlserver.messagebox.exceptionmessageboxsymbol.aspx">ExceptionMessageBoxSymbol</a>) &#8211; The symbol to show in the message box, like Asterisk, Error, Warning, and so on. </li>
<li>Text (String) &#8211; If the message box is being used for custom text instead of an exception, then this property will be populated with that text. </li>
<li>UseOwnerFont (String) &#8211; If you want to keep a consistent look across your application, you can tell the ExceptionMessageBox to use its owner window&#8217;s font instead of the default. </li>
</ul>
<p><strong>Methods</strong></p>
<ul>
<li>SetButtonText &#8211; There are a couple of overloads for this method. It&#8217;s used to set the text of one to five buttons on the dialog. This only applies if the Buttons property is ExceptionMessageBoxButtons.Custom. </li>
<li>Show &#8211; 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. </li>
</ul>
<p><strong>Event</strong></p>
<ul>
<li>OnCopyToClipboard -This is a pretty interesting event. It&#8217;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&#8217;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&#8217;s no easy way to change the text on the toolbar button&#8230; </li>
</ul>
<p>So that&#8217;s a brief look at the ExceptionMessageBox. One thing I didn&#8217;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:</p>
<p><a href="http://msdn2.microsoft.com/en-us/library/ms166340.aspx">How To: Program The ExceptionMessageBox</a></p>
<p><a href="http://msdn2.microsoft.com/en-us/library/microsoft.sqlserver.messagebox.exceptionmessagebox.aspx">The ExceptionMessageBox Class</a></p>
<p><a href="http://www.microsoft.com/downloads/details.aspx?FamilyID=df0ba5aa-b4bd-4705-aa0a-b477ba72a9cb&amp;DisplayLang=en">Download Page For ExceptionMessageBox</a> (Search for &quot;Exception Message Box&quot;)</p>
]]></content:encoded>
			<wfw:commentRss>http://blogs.rev-net.com/ddewinter/2007/12/01/the-exceptionmessagebox/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Null Your DataSources!</title>
		<link>http://blogs.rev-net.com/ddewinter/2007/09/23/null-your-datasources/</link>
		<comments>http://blogs.rev-net.com/ddewinter/2007/09/23/null-your-datasources/#comments</comments>
		<pubDate>Mon, 24 Sep 2007 02:54:03 +0000</pubDate>
		<dc:creator>David DeWinter</dc:creator>
				<category><![CDATA[C#]]></category>

		<guid isPermaLink="false">http://dev.rev-net.com/blog/ddewinter/?p=18</guid>
		<description><![CDATA[I&#8217;ve recently been working on an application that mimics a Windows Forms designer&#8211;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 [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ve recently been working on an application that mimics a Windows Forms designer&#8211;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.</p>
<p>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.</p>
<p>That action was most definitely related to the issue, but we still couldn&#8217;t think of why it was trying to serialize the ListBox, especially after the dialog was closed.</p>
<p>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.</p>
<p>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. <img src='http://blogs.rev-net.com/ddewinter/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://blogs.rev-net.com/ddewinter/2007/09/23/null-your-datasources/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>WF Tracing</title>
		<link>http://blogs.rev-net.com/ddewinter/2007/08/09/wf-tracing/</link>
		<comments>http://blogs.rev-net.com/ddewinter/2007/08/09/wf-tracing/#comments</comments>
		<pubDate>Fri, 10 Aug 2007 04:19:10 +0000</pubDate>
		<dc:creator>David DeWinter</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[WF]]></category>

		<guid isPermaLink="false">http://dev.rev-net.com/blog/ddewinter/?p=16</guid>
		<description><![CDATA[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&#8217;ve recently been working with the rules engine and PolicyActivity in WF. I&#8217;ve found that you can log what&#8217;s going on with the rules engine with the following configuration in the configuration file:

&#60;configuration&#62;
    &#60;system.diagnostics&#62;
        &#60;switches&#62;
        [...]]]></description>
			<content:encoded><![CDATA[<p>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.</p>
<p>I&#8217;ve recently been working with the rules engine and PolicyActivity in WF. I&#8217;ve found that you can log what&#8217;s going on with the rules engine with the following configuration in the configuration file:</p>
<p style="background: white none repeat scroll 0% 50%; font-family: Courier New; font-size: 10pt; color: black; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial">
<p style="margin: 0px"><span style="color: blue">&lt;</span><span style="color: #a31515">configuration</span><span style="color: blue">&gt;</span></p>
<p style="margin: 0px"><span style="color: blue">    &lt;</span><span style="color: #a31515">system.diagnostics</span><span style="color: blue">&gt;</span></p>
<p style="margin: 0px"><span style="color: blue">        &lt;</span><span style="color: #a31515">switches</span><span style="color: blue">&gt;</span></p>
<p style="margin: 0px"><span style="color: blue">            &lt;</span><span style="color: #a31515">add</span><span style="color: blue"> </span><span style="color: red">name</span><span style="color: blue">=</span>&#8220;<span style="color: blue">System.Workflow.Activities.Rules</span>&#8220;<span style="color: blue"> </span><span style="color: red">value</span><span style="color: blue">=</span>&#8220;<span style="color: blue">All</span>&#8220;<span style="color: blue">/&gt;</span></p>
<p style="margin: 0px"><span style="color: blue">            &lt;</span><span style="color: #a31515">add</span><span style="color: blue"> </span><span style="color: red">name</span><span style="color: blue">=</span>&#8220;<span style="color: blue">System.Workflow.LogToFile</span>&#8220;<span style="color: blue"> </span><span style="color: red">value</span><span style="color: blue">=</span>&#8220;<span style="color: blue">1</span>&#8220;<span style="color: blue">/&gt;</span></p>
<p style="margin: 0px"><span style="color: blue">        &lt;/</span><span style="color: #a31515">switches</span><span style="color: blue">&gt;</span></p>
<p style="margin: 0px"><span style="color: blue">    &lt;/</span><span style="color: #a31515">system.diagnostics</span><span style="color: blue">&gt;</span></p>
<p style="margin: 0px"><span style="color: blue">&lt;/</span><span style="color: #a31515">configuration</span><span style="color: blue">&gt;</span></p>
<p>However, it&#8217;s also possible to trace using any trace listeners registered with the Trace.Listeners collection using the following:</p>
<p style="background: white none repeat scroll 0% 50%; font-family: Courier New; font-size: 10pt; color: black; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial">
<p style="margin: 0px"><span style="color: blue">&lt;</span><span style="color: #a31515">configuration</span><span style="color: blue">&gt;</span></p>
<p style="margin: 0px"><span style="color: blue">    &lt;</span><span style="color: #a31515">system.diagnostics</span><span style="color: blue">&gt;</span></p>
<p style="margin: 0px"><span style="color: blue">        &lt;</span><span style="color: #a31515">switches</span><span style="color: blue">&gt;</span></p>
<p style="margin: 0px"><span style="color: blue">            &lt;</span><span style="color: #a31515">add</span><span style="color: blue"> </span><span style="color: red">name</span><span style="color: blue">=</span>&#8220;<span style="color: blue">System.Workflow.Activities.Rules</span>&#8220;<span style="color: blue"> </span><span style="color: red">value</span><span style="color: blue">=</span>&#8220;<span style="color: blue">All</span>&#8220;<span style="color: blue">/&gt;</span></p>
<p style="margin: 0px"><span style="color: blue">            &lt;</span><span style="color: #a31515">add</span><span style="color: blue"> </span><span style="color: red">name</span><span style="color: blue">=</span>&#8220;<span style="color: blue">System.Workflow.LogToTraceListeners</span>&#8220;<span style="color: blue"> </span><span style="color: red">value</span><span style="color: blue">=</span>&#8220;<span style="color: blue">1</span>&#8220;<span style="color: blue">/&gt;</span></p>
<p style="margin: 0px"><span style="color: blue">        &lt;/</span><span style="color: #a31515">switches</span><span style="color: blue">&gt;</span></p>
<p style="margin: 0px"><span style="color: blue">    &lt;/</span><span style="color: #a31515">system.diagnostics</span><span style="color: blue">&gt;</span></p>
<p style="margin: 0px"><span style="color: blue">&lt;/</span><span style="color: #a31515">configuration</span><span style="color: blue">&gt;</span></p>
<p>I mention this because in the context that I found it, I found almost no documentation on this. It&#8217;s probably more easily accessible than I think, but it&#8217;s here just in case. =)</p>
]]></content:encoded>
			<wfw:commentRss>http://blogs.rev-net.com/ddewinter/2007/08/09/wf-tracing/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Implicit Vs. Explicit Interface Method Implementation</title>
		<link>http://blogs.rev-net.com/ddewinter/2007/01/05/%c2%bb-implicit-vs-explicit-interface-method-implementation/</link>
		<comments>http://blogs.rev-net.com/ddewinter/2007/01/05/%c2%bb-implicit-vs-explicit-interface-method-implementation/#comments</comments>
		<pubDate>Sat, 06 Jan 2007 00:01:16 +0000</pubDate>
		<dc:creator>David DeWinter</dc:creator>
				<category><![CDATA[C#]]></category>

		<guid isPermaLink="false">http://dev.rev-net.com/blog/ddewinter/?p=9</guid>
		<description><![CDATA[In the NORMA project we were encouraged to use Explicit Interface Method Implementation (EIMI). However, after reading a bit of Jeffrey Richter&#8217;s CLR via C#, I&#8217;ve decided to change the way I implement interfaces.
This entry is also a response to Ben&#8217;s blog entry, located here, which you should read first because it explains the difference [...]]]></description>
			<content:encoded><![CDATA[<p>In the NORMA project we were encouraged to use Explicit Interface Method Implementation (EIMI). However, after reading a bit of Jeffrey Richter&#8217;s <em>CLR via C#</em>, I&#8217;ve decided to change the way I implement interfaces.</p>
<p>This entry is also a response to Ben&#8217;s blog entry, located <a href="http://dev.rev-net.com/blog/bmeyers/wp-trackback.php?p=3" title="Implicit Versus Explicit Interface Implementation - bmeyers">here</a>, which you should read first because it explains the difference between the two approaches.</p>
<p>Now&#8230;a little about why I disagree that EIMI should be used as often as possible.</p>
<ol>
<li>Having to cast an object to the interface just to call the interface method can get a little annoying in code. When you&#8217;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&#8217;s a little awkward. However, this may be a superficial reason to some, so let&#8217;s continue&#8230;</li>
<li>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.</li>
<li>Furthermore, with EIMI, if you derive from a class that implements an interface in this manner, you can&#8217;t call your base class&#8217;s implementation of that interface.</li>
</ol>
<p>Now, I&#8217;m not saying that EIMI is useless. There are some specific cases when it is necessary. Take for instance the following example:</p>
<p>[code lang="csharp"] public interface IWindow<br />
{<br />
object GetMenu();<br />
}<br />
public interface IRestaurant<br />
{<br />
object GetMenu();<br />
}<br />
public class Pizzeria : IWindow, IRestaurant<br />
{<br />
object IWindow.GetMenu() { ... }</p>
<p>object IRestaurant.GetMenu() { ... }<br />
}<br />
[/code]</p>
<p>Here you have to use EIMI because you have two interfaces with the same method names. It doesn&#8217;t make sense to call GetMenu() and expect the CLR to infer which interface you&#8217;re binding to.</p>
<p>Another case where EIMI can come in handy is to improve compile-time safety. Let&#8217;s say you have a struct that implements a non-generic interface, like IComparable:</p>
<p>[code lang="csharp"] public interface IComparable<br />
{<br />
Int32 CompareTo(Object other);<br />
}</p>
<p>public struct SomeValueType : IComparable<br />
{<br />
private int x;</p>
<p>public SomeValueType(Int32 x) { this.x = x; }</p>
<p>public Int32 CompareTo(Object other)<br />
{<br />
return x - ((SomeValueType)other).x;<br />
}<br />
}</p>
<p>// Now in some other method I can call CompareTo like this<br />
public static void Main()<br />
{<br />
SomeValueType v = new SomeValueType(0);<br />
Object o = new Object();<br />
Int32 n = v.CompareTo(v); // Undesired Boxing<br />
n = v.CompareTo(o); // InvalidCastException<br />
}[/code]</p>
<p>So now instead of what&#8217;s listed above, you want to enforce some semblance of compile-time safety with your interface method. Here&#8217;s something you can do with EIMI:<br />
[code lang="csharp"] public struct SomeValueType : IComparable<br />
{<br />
private int x;</p>
<p>public SomeValueType(Int32 x) { this.x = x; }</p>
<p>Int32 IComparable.CompareTo(Object other)<br />
{<br />
return CompareTo((SomeValueType)other);<br />
}<br />
public Int32 CompareTo(SomeValueType other)<br />
{<br />
return x - other.x;<br />
}<br />
}</p>
<p>// Now in some other method I can call CompareTo like this<br />
public static void Main()<br />
{<br />
SomeValueType v = new SomeValueType(0);<br />
Object o = new Object();<br />
Int32 n = v.CompareTo(v); // No Boxing<br />
n = v.CompareTo(o); // Compile-time Error<br />
}[/code]</p>
<p>Of course, if we box SomeValueType into an IComparable instance then it would throw as above, so this s&#8221;olution&#8221; 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.</p>
<p>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.</p>
]]></content:encoded>
			<wfw:commentRss>http://blogs.rev-net.com/ddewinter/2007/01/05/%c2%bb-implicit-vs-explicit-interface-method-implementation/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>As, Is, and the Art of Reflection</title>
		<link>http://blogs.rev-net.com/ddewinter/2006/05/28/%c2%bb-as-is-and-the-art-of-reflection/</link>
		<comments>http://blogs.rev-net.com/ddewinter/2006/05/28/%c2%bb-as-is-and-the-art-of-reflection/#comments</comments>
		<pubDate>Sun, 28 May 2006 23:48:31 +0000</pubDate>
		<dc:creator>David DeWinter</dc:creator>
				<category><![CDATA[C#]]></category>

		<guid isPermaLink="false">http://dev.rev-net.com/blog/ddewinter/?p=4</guid>
		<description><![CDATA[I&#8217;m sure that for all of us there have been times when we want to get the type of an object that we&#8217;re using, especially when dealing with abstract classes, interfaces, and inheritance. For this, there&#8217;s a right way and a wrong way to do things.
The first way to determine the type of an object [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;m sure that for all of us there have been times when we want to get the type of an object that we&#8217;re using, especially when dealing with abstract classes, interfaces, and inheritance. For this, there&#8217;s a right way and a wrong way to do things.</p>
<p>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&#8217;s an example.</p>
<blockquote>
<pre>public void Display(IList displayer)
{
if (displayer.GetType() == Type.GetType("System.Collections.ArrayList"))
{
return;
}
// Other processing...
}</pre>
</blockquote>
<p>It&#8217;s bad enough that we&#8217;re using reflection for this information (via the <em>GetType()</em> method of <em>displayer</em>), but also that we&#8217;re hardcoding the type of the class we&#8217;re interested in with &#8220;System.Collections.ArrayList.&#8221; This can be cleaned up to the following:</p>
<blockquote>
<pre>public void Display(IList displayer)
{
if (displayer.GetType() == typeof(System.Collections.ArrayList))
{
return;
}
// Other processing...
}</pre>
</blockquote>
<p>However, it&#8217;s still reflection. Instead of using this, consider using the <em>is</em> keyword, which in fact does not use reflection at all but a special MSIL statement which is pretty quick, as far as what I&#8217;ve heard.</p>
<blockquote>
<pre>public void Display(IList displayer)
{
if (displayer is System.Collections.ArrayList)
{
return;
}
// Other processing...
}</pre>
</blockquote>
<p>Another keyword that is often overlooked is the <em>as</em> keyword. This handles casting on reference types. Although I hope you haven&#8217;t, maybe you&#8217;ve seen something like this before:</p>
<blockquote>
<pre>DataSet ds;
try
{
ds = (DataSet)Request.Cache["ds"];
}
catch { }</pre>
</blockquote>
<p>You don&#8217;t even need a try/catch statement here; just use the <em>as</em> 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 <em>is</em>, so it&#8217;s pretty efficient. You can&#8217;t use these two keywords with value types because value types and reference types are handled differently in memory.</p>
<p>Here&#8217;s one last example:</p>
<blockquote>
<pre>public void Display(IList«IDisposable» list)
{
int count = list.Count;
for (int i = 0; i &lt; count; ++i)
{
IDisposable item = list[i];
if (item is SqlConnection)
{
(item as SqlConnection).Open();
}
// Other processing...
}
}</pre>
</blockquote>
<p>Say you wanted to check if a particular item is a SqlConnection object, and if it is, open it. Remember how <em>is</em> and <em>as</em> 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:</p>
<blockquote>
<pre>public void Display(IList«IDisposable» list)
{
int count = list.Count;
for (int i = 0; i &lt; count; ++i)
{
IDisposable item = list[i];
SqlConnection cnn = item as SqlConnection;
if (cnn != null)
{
cnn.Open();
}
// Other processing...
}
}</pre>
</blockquote>
]]></content:encoded>
			<wfw:commentRss>http://blogs.rev-net.com/ddewinter/2006/05/28/%c2%bb-as-is-and-the-art-of-reflection/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Matt&#8217;s First Rule of Performance</title>
		<link>http://blogs.rev-net.com/ddewinter/2006/05/20/%c2%bb-matts-first-rule-of-performance/</link>
		<comments>http://blogs.rev-net.com/ddewinter/2006/05/20/%c2%bb-matts-first-rule-of-performance/#comments</comments>
		<pubDate>Sat, 20 May 2006 19:28:41 +0000</pubDate>
		<dc:creator>David DeWinter</dc:creator>
				<category><![CDATA[C#]]></category>

		<guid isPermaLink="false">http://dev.rev-net.com/blog/ddewinter/?p=3</guid>
		<description><![CDATA[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 &#8220;right.&#8221; I [...]]]></description>
			<content:encoded><![CDATA[<p>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 &#8220;right.&#8221; I came across a concept from NU&#8217;s own Matt Curland the other day that looked something like this:</p>
<p>// Matt&#8217;s first rule of performance:<br />
// 0 &gt; 1 &gt; 2</p>
<p>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, <em>it&#8217;s better to call it once than call it twice.</em> But even so, it&#8217;s better not to call anything at all if you can help it.</p>
<p>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&#8217;s opposite role on a binary fact type <em>i.e.</em> if I had the fact type &#8220;Person(ID) has PersonName()&#8221; with a uniqueness and mandatory role constraint on the side of the Person object, calling the Multiplicity property of the PersonName&#8217;s role would give me RoleMultiplicity.ExactlyOne (opposite role&#8217;s constraints signify this).</p>
<p>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&#8217;s &#8220;Store&#8221; (as its name implies, stores everything that would be on the diagram, and we have know idea how that&#8217;s done; could be something of O(n<sup>2</sup>) complexity; see how Algorithms comes into play?!), and then <em>create a new </em>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:</p>
<p><a href="http://members.lycos.co.uk/suffusion/firstrule_before.png" title="Before the first rule">Before the Rule</a> &#8211; Notice the properties referenced multiple times.</p>
<p><a href="http://members.lycos.co.uk/suffusion/firstrule_after.png" title="After the first rule">After the Rule</a> &#8211; Notice how things are pulled out.</p>
<p>So remember:<br />
<em>When in doubt, pull it out.</em></p>
]]></content:encoded>
			<wfw:commentRss>http://blogs.rev-net.com/ddewinter/2006/05/20/%c2%bb-matts-first-rule-of-performance/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>
