<?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>Mindscape Blog &#187; Visual Studio</title>
	<atom:link href="http://www.mindscapehq.com/blog/index.php/category/visual-studio/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.mindscapehq.com/blog</link>
	<description>The official blog of Mindscape</description>
	<lastBuildDate>Fri, 14 Jun 2013 05:34:30 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.5</generator>
		<item>
		<title>Runtime code generation for types</title>
		<link>http://www.mindscapehq.com/blog/index.php/2011/12/06/runtime-code-generation-for-types/</link>
		<comments>http://www.mindscapehq.com/blog/index.php/2011/12/06/runtime-code-generation-for-types/#comments</comments>
		<pubDate>Wed, 07 Dec 2011 01:50:52 +0000</pubDate>
		<dc:creator>Ivan Towlson</dc:creator>
				<category><![CDATA[Visual Studio]]></category>

		<guid isPermaLink="false">http://www.mindscapehq.com/blog/?p=3970</guid>
		<description><![CDATA[Last week I discussed how you could use runtime code generation to create fast methods to replace slow reflection code, even when you didn&#8217;t have the target types to compile against. But runtime code generation allows you to go further than isolated methods: you can actually create whole new types at runtime. Why might you [...]]]></description>
				<content:encoded><![CDATA[<p>Last week I discussed <a href="http://www.mindscapehq.com/blog/index.php/2011/11/27/reflection-performance-and-runtime-code-generation/">how you could use runtime code generation to create fast methods to replace slow reflection code</a>, even when you didn&#8217;t have the target types to compile against.  But runtime code generation allows you to go further than isolated methods: you can actually create whole new types at runtime.</p>
<p>Why might you want to do that?  The classic example is to subclass a user-defined class so as to intercept certain calls that you are interested in.  Some object-relational mappers do this, for example, so that users can write entity properties using automatic property syntax and yet the object-relational mapper can still intercept the getters and setters to perform, for example, lazy loading.  Another example could be to create objects that are implemented according to a regular pattern but whose properties are determined from a schema that is only available at runtime (say, from a configuration file or a database&#8217;s catalogue); such objects might not be terribly useful for programming with, unless there were design-time interfaces through which you could address them, but could be handy for using with ASP.NET Dynamic Data or a data grid control.</p>
<p>Of the methods I talked about in my previous post, expression trees can&#8217;t be used to implement whole types.  They&#8217;re restricted to, well, expressions.  CodeDom can be used, in the same way and with the same considerations as before, so I&#8217;m not going to repeat that discussion.  Dynamic methods can&#8217;t be used, because like expression trees they represent methods rather than types &#8212; but there is a closely related technique which can.</p>
<p><strong>Enter the Reflection.Emit namespace</strong></p>
<p>As well as the DynamicMethod class, the Reflection.Emit namespace includes builder classes for all the elements that make up a .NET assembly: modules, types, fields, properties, methods and so on.  In many cases, the builder class is actually just like the familiar Reflection equivalent &#8212; for example, PropertyBuilder is a derived class of PropertyInfo &#8212; but writeable instead of read-only.  For generating code, the MethodBuilder class exposes an ILGenerator which is the same as that exposed by DynamicMethod.  So creating a type with these builder classes is a bit like combining what you already know about read-only Reflection with what you already know about dynamic method code generation.  Easy, right?</p>
<p>Well, there are a few small hoops that you need to jump through.  But once you&#8217;ve got your head around them&#8230; yes, it&#8217;s not too difficult.  Let&#8217;s try it!</p>
<p><strong>Preliminaries</strong></p>
<p>The first thing we need to do is get some preliminaries out of the way.  A type has to live inside an assembly.  But it&#8217;s not quite that simple.  Back in the day, some bright spark at Microsoft decided it would be a good idea to distinguish between <em>modules</em> (roughly, physical files that contain stuff) and <em>assemblies</em> (roughly, units of deployment and versioning).  The idea was that your assembly, instead of being a huge monolithic DLL or EXE, could be split up so that large resources could be&#8230; actually, I don&#8217;t know why I&#8217;m explaining this, as only seven people even remember that the whole &#8216;multi-module assembly&#8217; concept ever existed, and they are one by one being erased from history by a mysterious and terrifying force with a dodgy Austrian accent.  All you need to know is that your &#8216;assembly&#8217; is actually a wrapper around a thing called a &#8216;module,&#8217; and it is within this mysterious &#8216;module&#8217; that all the excitement happens.</p>
<p>So without further ado, let&#8217;s create a dynamic assembly-module-thingy to hold our runtime generated types.</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;">AssemblyName name <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> AssemblyName<span style="color: #008000;">&#40;</span><span style="color: #666666;">&quot;MyRuntimeTypes&quot;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
AssemblyBuilder assembly <span style="color: #008000;">=</span> AppDomain<span style="color: #008000;">.</span><span style="color: #0000FF;">CurrentDomain</span><span style="color: #008000;">.</span><span style="color: #0000FF;">DefineDynamicAssembly</span><span style="color: #008000;">&#40;</span>name, AssemblyBuilderAccess<span style="color: #008000;">.</span><span style="color: #0000FF;">Run</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
ModuleBuilder module <span style="color: #008000;">=</span> assembly<span style="color: #008000;">.</span><span style="color: #0000FF;">DefineDynamicModule</span><span style="color: #008000;">&#40;</span><span style="color: #666666;">&quot;MyRuntimeTypes&quot;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span></pre></div></div>

<p>Not much to see here, except for the AssemblyBuilderAccess option.  For most dynamic assemblies, you&#8217;ll set this to Run.  However, if you want to be able to persist the emitted assembly, you can specify RunAndSave instead.  (In this case, you&#8217;ll need to call the DefineDynamicModule overload which also takes a file name.)  You might do this to cache the dynamic assembly to save rebuilding it on every run, or for diagnostic purposes so you can open it in Reflector or ILDASM and see where it all went so horribly wrong.</p>
<p>Great, so now we have a big empty module.  Time to get down to business.</p>
<p><strong>Defining a dynamic type</strong></p>
<p>To define a dynamic type in a module, you call the DefineType method.  (Gasps of amazement.)  This gives you a TypeBuilder object, which you can then party on.  Once you&#8217;ve got the type the way you want it, you call CreateType and this gives you a Type object representing the compiled type &#8212; you can now create instances of this using Activator.CreateInstance or the faster techniques I discussed in the previous post.</p>
<p>For my example, I&#8217;m going to imagine that my system includes a user profile object whose properties are defined in a configuration file or something, and I have to implement an object with these properties so it can be displayed in a dynamic form builder or a data grid or something like that.  (It&#8217;s not a stupendously realistic example but I want to keep it reasonably simple so as not to get bogged down in extraneous detail.)  So here&#8217;s how I define and build that type:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;">TypeBuilder type <span style="color: #008000;">=</span> module<span style="color: #008000;">.</span><span style="color: #0000FF;">DefineType</span><span style="color: #008000;">&#40;</span><span style="color: #666666;">&quot;Mindscape.RuntimeTypes.Profile&quot;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
<span style="color: #008080; font-style: italic;">// magic goes here</span>
Type compiledType <span style="color: #008000;">=</span> type<span style="color: #008000;">.</span><span style="color: #0000FF;">CreateType</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span></pre></div></div>

<p>What about inheritance?  You can pass a parent type to DefineType:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;">TypeBuilder type <span style="color: #008000;">=</span> module<span style="color: #008000;">.</span><span style="color: #0000FF;">DefineType</span><span style="color: #008000;">&#40;</span><span style="color: #666666;">&quot;Mindscape.RuntimeTypes.Profile&quot;</span>, TypeAttributes<span style="color: #008000;">.</span><span style="color: #0600FF; font-weight: bold;">Public</span>, <span style="color: #008000;">typeof</span><span style="color: #008000;">&#40;</span>ProfileBase<span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span></pre></div></div>

<p>If you want your dynamic type to implement an interface, you can specify it using AddInterfaceImplementation:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;">type<span style="color: #008000;">.</span><span style="color: #0000FF;">AddInterfaceImplementation</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">typeof</span><span style="color: #008000;">&#40;</span>IProfile<span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span></pre></div></div>

<p>Of course this doesn&#8217;t create the actual properties or methods to implement the interface &#8212; it just marks the type as implementing the interface.  You&#8217;ll still need to supply the interface members, or you&#8217;ll get an error when you create the type.</p>
<p><strong>Implementing the type&#8217;s members: fields</strong></p>
<p>Implementing a member field is dead easy: call the DefineField method:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;">FieldBuilder myField <span style="color: #008000;">=</span> type<span style="color: #008000;">.</span><span style="color: #0000FF;">DefineField</span><span style="color: #008000;">&#40;</span><span style="color: #666666;">&quot;_myField&quot;</span>, <span style="color: #008000;">typeof</span><span style="color: #008000;">&#40;</span><span style="color: #6666cc; font-weight: bold;">int</span><span style="color: #008000;">&#41;</span>, FieldAttributes<span style="color: #008000;">.</span><span style="color: #0600FF; font-weight: bold;">Private</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span></pre></div></div>

<p>You&#8217;re probably going to want to refer to your fields when you come to build your methods and properties (otherwise, there&#8217;s not much point having the fields, right?), so you&#8217;ll usually want to keep references to them.</p>
<p><strong>Implementing the type&#8217;s members: methods</strong></p>
<p>Defining a method is dead easy too: call the (you guessed it) DefineMethod method.</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;">MethodBuilder myMethod <span style="color: #008000;">=</span> type<span style="color: #008000;">.</span><span style="color: #0000FF;">DefineMethod</span><span style="color: #008000;">&#40;</span><span style="color: #666666;">&quot;GetLength&quot;</span>, MethodAttributes<span style="color: #008000;">.</span><span style="color: #0600FF; font-weight: bold;">Public</span>, <span style="color: #008000;">typeof</span><span style="color: #008000;">&#40;</span><span style="color: #6666cc; font-weight: bold;">int</span><span style="color: #008000;">&#41;</span>, <span style="color: #008000;">new</span> Type<span style="color: #008000;">&#91;</span><span style="color: #008000;">&#93;</span> <span style="color: #008000;">&#123;</span> <span style="color: #008000;">typeof</span><span style="color: #008000;">&#40;</span><span style="color: #6666cc; font-weight: bold;">string</span><span style="color: #008000;">&#41;</span> <span style="color: #008000;">&#125;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span></pre></div></div>

<p>Here the third argument is the return type of the method, and the fourth the parameter types: so the above is equivalent to the signature <em>public int GetLength(string)</em>.</p>
<p>Of course if you try to create the type in this state you will get an error because you haven&#8217;t provided a method body for GetLength.  Fortunately, you can do this in exactly the same way as you did for &#8216;floating&#8217; dynamic methods, as discussed in my earlier post.</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;">ILGenerator ilgen <span style="color: #008000;">=</span> myMethod<span style="color: #008000;">.</span><span style="color: #0000FF;">GetILGenerator</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
ilgen<span style="color: #008000;">.</span><span style="color: #0000FF;">Emit</span><span style="color: #008000;">&#40;</span>OpCodes<span style="color: #008000;">.</span><span style="color: #0000FF;">Ldarg_1</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
ilgen<span style="color: #008000;">.</span><span style="color: #0000FF;">Emit</span><span style="color: #008000;">&#40;</span>OpCodes<span style="color: #008000;">.</span><span style="color: #0000FF;">Callvirt</span>, <span style="color: #008000;">typeof</span><span style="color: #008000;">&#40;</span><span style="color: #6666cc; font-weight: bold;">string</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">.</span><span style="color: #0000FF;">GetProperty</span><span style="color: #008000;">&#40;</span><span style="color: #666666;">&quot;Length&quot;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">.</span><span style="color: #0000FF;">GetGetMethod</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
ilgen<span style="color: #008000;">.</span><span style="color: #0000FF;">Emit</span><span style="color: #008000;">&#40;</span>OpCodes<span style="color: #008000;">.</span><span style="color: #0000FF;">Ret</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span></pre></div></div>

<p>As always with IL generation the tricky bit is knowing what IL to write and as always the answer is to cheat.  Write an example of the type and its methods in C#, compile it (in Release mode), open the compiled assembly in ILDASM and copy the IL opcodes from there (<em>mutatis mutandis</em> of course).  It&#8217;s not as hard as it looks!  However, there are some special things to be aware of when your method needs to refer to other members of the type you&#8217;re building.  We&#8217;ll talk about those in a moment.</p>
<p><strong>Implementing the type&#8217;s properties</strong></p>
<p>After all that alarming IL, properties are nice and easy.  The only thing to watch out for is that you need to implement the get and set code (if you have any of course) as methods, conventionally called get_Xxx and set_Xxx (where Xxx is your property name).  The signatures of the getter and setter must be consistent with the property type.  With this done, you just associate those methods with the property using SetGetMethod and/or SetSetMethod.  Unlike the C# syntactic sugar, you don&#8217;t write any code in the property itself.</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;">PropertyBuilder myProperty <span style="color: #008000;">=</span> type<span style="color: #008000;">.</span><span style="color: #0000FF;">DefineProperty</span><span style="color: #008000;">&#40;</span><span style="color: #666666;">&quot;MyProperty&quot;</span>, PropertyAttributes<span style="color: #008000;">.</span><span style="color: #0000FF;">None</span>, <span style="color: #008000;">typeof</span><span style="color: #008000;">&#40;</span><span style="color: #6666cc; font-weight: bold;">int</span><span style="color: #008000;">&#41;</span>, Type<span style="color: #008000;">.</span><span style="color: #0000FF;">EmptyTypes</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
MethodBuilder myPropertyGetter <span style="color: #008000;">=</span> type<span style="color: #008000;">.</span><span style="color: #0000FF;">DefineMethod</span><span style="color: #008000;">&#40;</span><span style="color: #666666;">&quot;get_MyProperty&quot;</span>, MethodAttributes<span style="color: #008000;">.</span><span style="color: #0600FF; font-weight: bold;">Public</span>, <span style="color: #008000;">typeof</span><span style="color: #008000;">&#40;</span><span style="color: #6666cc; font-weight: bold;">int</span><span style="color: #008000;">&#41;</span>, Type<span style="color: #008000;">.</span><span style="color: #0000FF;">EmptyTypes</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>  <span style="color: #008080; font-style: italic;">// getter takes no args and returns the property type</span>
<span style="color: #008080; font-style: italic;">// implement myPropertyGetter using ILGenerator in the usual way</span>
&nbsp;
myProperty<span style="color: #008000;">.</span><span style="color: #0000FF;">SetGetMethod</span><span style="color: #008000;">&#40;</span>myPropertyGetter<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span></pre></div></div>

<p>Notice that the property itself doesn&#8217;t even have an access modifier like public or protected &#8212; the access modifiers are on the getter and setter, again slightly different from the way C# lays it out.</p>
<p><strong>And there&#8217;s more</strong></p>
<p>TypeBuilder also provides methods for defining events, constructors, generic type parameters etc., setting attributes on members, creating nested types and all the other spiffy things you can do to make your CLR types a joy to behold.  I&#8217;m not going to plough through them all &#8212; you can figure them out if you need them.</p>
<p><strong>Putting it all together</strong></p>
<p>We&#8217;ve seen how to define members in isolation.  Now let&#8217;s put it together and see how to build an entire type.</p>
<p>For our example, I just want to create a set of read-write properties according to some input spec (maybe read in from a config file), but I want the class to raise property changed notifications so it can be used in WPF or Silverlight.</p>
<p>This leaves me with a design decision: should I implement INotifyPropertyChanged in the runtime generated code, or should I create a base class which implements INotifyPropertyChanged and have my runtime generated class take advantage of that?  From the point of view of a consumer of the runtime generated class, there&#8217;s not much difference between these two options, but from the point of view of implementation, the second is a lot easier, both to understand and to maintain, because I can write the INotifyPropertyChanged implementation, which is unchanging, in C# which everybody understands, and use IL only for the dynamic bits.</p>
<p>So enter a base class:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #6666cc; font-weight: bold;">class</span> ViewModelBase <span style="color: #008000;">:</span> INotifyPropertyChanged
<span style="color: #008000;">&#123;</span>
  <span style="color: #0600FF; font-weight: bold;">protected</span> <span style="color: #6666cc; font-weight: bold;">void</span> Set<span style="color: #008000;">&lt;</span>T<span style="color: #008000;">&gt;</span><span style="color: #008000;">&#40;</span><span style="color: #0600FF; font-weight: bold;">ref</span> T field, T value, <span style="color: #6666cc; font-weight: bold;">string</span> propertyName<span style="color: #008000;">&#41;</span>
  <span style="color: #008000;">&#123;</span>
    <span style="color: #0600FF; font-weight: bold;">if</span> <span style="color: #008000;">&#40;</span><span style="color: #008000;">!</span><span style="color: #6666cc; font-weight: bold;">Object</span><span style="color: #008000;">.</span><span style="color: #0000FF;">Equals</span><span style="color: #008000;">&#40;</span>field, value<span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span>
    <span style="color: #008000;">&#123;</span>
      field <span style="color: #008000;">=</span> value<span style="color: #008000;">;</span>
      OnPropertyChanged<span style="color: #008000;">&#40;</span>propertyName<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
    <span style="color: #008000;">&#125;</span>
  <span style="color: #008000;">&#125;</span>
&nbsp;
  <span style="color: #0600FF; font-weight: bold;">protected</span> <span style="color: #0600FF; font-weight: bold;">virtual</span> <span style="color: #6666cc; font-weight: bold;">void</span> OnPropertyChanged<span style="color: #008000;">&#40;</span><span style="color: #6666cc; font-weight: bold;">string</span> propertyName<span style="color: #008000;">&#41;</span>
  <span style="color: #008000;">&#123;</span>
    var handler <span style="color: #008000;">=</span> PropertyChanged<span style="color: #008000;">;</span>
    <span style="color: #0600FF; font-weight: bold;">if</span> <span style="color: #008000;">&#40;</span>handler <span style="color: #008000;">!=</span> <span style="color: #0600FF; font-weight: bold;">null</span><span style="color: #008000;">&#41;</span>
    <span style="color: #008000;">&#123;</span>
      PropertyChanged<span style="color: #008000;">&#40;</span><span style="color: #0600FF; font-weight: bold;">this</span>, <span style="color: #008000;">new</span> PropertyChangedEventArgs<span style="color: #008000;">&#40;</span>propertyName<span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
    <span style="color: #008000;">&#125;</span>
  <span style="color: #008000;">&#125;</span>
&nbsp;
  <span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #0600FF; font-weight: bold;">event</span> PropertyChangedEventHandler PropertyChanged<span style="color: #008000;">;</span>
<span style="color: #008000;">&#125;</span></pre></div></div>

<p>You&#8217;re cordially invited to ILDASM the ViewModelBase class and imagine the joy of generating the equivalent code dynamically into the Profile class.</p>
<p>With that helper sorted, we can set to implementing the Profile class itself:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF; font-weight: bold;">private</span> <span style="color: #0600FF; font-weight: bold;">static</span> Type CreateProfileType<span style="color: #008000;">&#40;</span>Dictionary<span style="color: #008000;">&lt;</span><span style="color: #6666cc; font-weight: bold;">string</span>, Type<span style="color: #008000;">&gt;</span> properties<span style="color: #008000;">&#41;</span>
<span style="color: #008000;">&#123;</span>
  AssemblyName name <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> AssemblyName<span style="color: #008000;">&#40;</span><span style="color: #666666;">&quot;MyRuntimeTypes&quot;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
  AssemblyBuilder assembly <span style="color: #008000;">=</span> AppDomain<span style="color: #008000;">.</span><span style="color: #0000FF;">CurrentDomain</span><span style="color: #008000;">.</span><span style="color: #0000FF;">DefineDynamicAssembly</span><span style="color: #008000;">&#40;</span>name, AssemblyBuilderAccess<span style="color: #008000;">.</span><span style="color: #0000FF;">Run</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
  ModuleBuilder module <span style="color: #008000;">=</span> assembly<span style="color: #008000;">.</span><span style="color: #0000FF;">DefineDynamicModule</span><span style="color: #008000;">&#40;</span><span style="color: #666666;">&quot;MyRuntimeTypes&quot;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
  <span style="color: #008080; font-style: italic;">// Our runtime-generated type inherits from ViewModelBase</span>
  TypeBuilder type <span style="color: #008000;">=</span> module<span style="color: #008000;">.</span><span style="color: #0000FF;">DefineType</span><span style="color: #008000;">&#40;</span><span style="color: #666666;">&quot;Mindscape.RuntimeTypes.Profile&quot;</span>, TypeAttributes<span style="color: #008000;">.</span><span style="color: #0600FF; font-weight: bold;">Public</span>, <span style="color: #008000;">typeof</span><span style="color: #008000;">&#40;</span>ViewModelBase<span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
  <span style="color: #0600FF; font-weight: bold;">foreach</span> <span style="color: #008000;">&#40;</span>var property <span style="color: #0600FF; font-weight: bold;">in</span> properties<span style="color: #008000;">&#41;</span>
  <span style="color: #008000;">&#123;</span>
    ImplementProperty<span style="color: #008000;">&#40;</span>type, property<span style="color: #008000;">.</span><span style="color: #0000FF;">Key</span>, property<span style="color: #008000;">.</span><span style="color: #0000FF;">Value</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
  <span style="color: #008000;">&#125;</span>
&nbsp;
  <span style="color: #0600FF; font-weight: bold;">return</span> type<span style="color: #008000;">.</span><span style="color: #0000FF;">CreateType</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
<span style="color: #008000;">&#125;</span></pre></div></div>

<p>This is all familiar framework, but this time, we&#8217;re implementing a property for every entry in the dictionary, instead of just some hardwired name.  The real work happens in the ImplementProperty method:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF; font-weight: bold;">private</span> <span style="color: #0600FF; font-weight: bold;">static</span> <span style="color: #6666cc; font-weight: bold;">void</span> ImplementProperty<span style="color: #008000;">&#40;</span>TypeBuilder type, <span style="color: #6666cc; font-weight: bold;">string</span> propertyName, Type propertyType<span style="color: #008000;">&#41;</span>
<span style="color: #008000;">&#123;</span>
  FieldBuilder field <span style="color: #008000;">=</span> type<span style="color: #008000;">.</span><span style="color: #0000FF;">DefineField</span><span style="color: #008000;">&#40;</span><span style="color: #666666;">&quot;_&quot;</span> <span style="color: #008000;">+</span> propertyName, propertyType, FieldAttributes<span style="color: #008000;">.</span><span style="color: #0600FF; font-weight: bold;">Private</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
  PropertyBuilder property <span style="color: #008000;">=</span> type<span style="color: #008000;">.</span><span style="color: #0000FF;">DefineProperty</span><span style="color: #008000;">&#40;</span>propertyName, PropertyAttributes<span style="color: #008000;">.</span><span style="color: #0000FF;">None</span>, propertyType, Type<span style="color: #008000;">.</span><span style="color: #0000FF;">EmptyTypes</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
  MethodBuilder getter <span style="color: #008000;">=</span> type<span style="color: #008000;">.</span><span style="color: #0000FF;">DefineMethod</span><span style="color: #008000;">&#40;</span><span style="color: #666666;">&quot;get_&quot;</span> <span style="color: #008000;">+</span> propertyName, MethodAttributes<span style="color: #008000;">.</span><span style="color: #0600FF; font-weight: bold;">Public</span>, propertyType, Type<span style="color: #008000;">.</span><span style="color: #0000FF;">EmptyTypes</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
  ILGenerator getterIL <span style="color: #008000;">=</span> getter<span style="color: #008000;">.</span><span style="color: #0000FF;">GetILGenerator</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
  getterIL<span style="color: #008000;">.</span><span style="color: #0000FF;">Emit</span><span style="color: #008000;">&#40;</span>OpCodes<span style="color: #008000;">.</span><span style="color: #0000FF;">Ldarg_0</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
  getterIL<span style="color: #008000;">.</span><span style="color: #0000FF;">Emit</span><span style="color: #008000;">&#40;</span>OpCodes<span style="color: #008000;">.</span><span style="color: #0000FF;">Ldfld</span>, field<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
  getterIL<span style="color: #008000;">.</span><span style="color: #0000FF;">Emit</span><span style="color: #008000;">&#40;</span>OpCodes<span style="color: #008000;">.</span><span style="color: #0000FF;">Ret</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
  MethodBuilder setter <span style="color: #008000;">=</span> type<span style="color: #008000;">.</span><span style="color: #0000FF;">DefineMethod</span><span style="color: #008000;">&#40;</span><span style="color: #666666;">&quot;set_&quot;</span> <span style="color: #008000;">+</span> propertyName, MethodAttributes<span style="color: #008000;">.</span><span style="color: #0600FF; font-weight: bold;">Public</span>, <span style="color: #008000;">typeof</span><span style="color: #008000;">&#40;</span><span style="color: #6666cc; font-weight: bold;">void</span><span style="color: #008000;">&#41;</span>, <span style="color: #008000;">new</span> Type<span style="color: #008000;">&#91;</span><span style="color: #008000;">&#93;</span> <span style="color: #008000;">&#123;</span> propertyType <span style="color: #008000;">&#125;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
  ILGenerator setterIL <span style="color: #008000;">=</span> setter<span style="color: #008000;">.</span><span style="color: #0000FF;">GetILGenerator</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
  setterIL<span style="color: #008000;">.</span><span style="color: #0000FF;">Emit</span><span style="color: #008000;">&#40;</span>OpCodes<span style="color: #008000;">.</span><span style="color: #0000FF;">Ldarg_0</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
  setterIL<span style="color: #008000;">.</span><span style="color: #0000FF;">Emit</span><span style="color: #008000;">&#40;</span>OpCodes<span style="color: #008000;">.</span><span style="color: #0000FF;">Ldarg_0</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
  setterIL<span style="color: #008000;">.</span><span style="color: #0000FF;">Emit</span><span style="color: #008000;">&#40;</span>OpCodes<span style="color: #008000;">.</span><span style="color: #0000FF;">Ldflda</span>, field<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
  setterIL<span style="color: #008000;">.</span><span style="color: #0000FF;">Emit</span><span style="color: #008000;">&#40;</span>OpCodes<span style="color: #008000;">.</span><span style="color: #0000FF;">Ldarg_1</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
  setterIL<span style="color: #008000;">.</span><span style="color: #0000FF;">Emit</span><span style="color: #008000;">&#40;</span>OpCodes<span style="color: #008000;">.</span><span style="color: #0000FF;">Ldstr</span>, propertyName<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
  setterIL<span style="color: #008000;">.</span><span style="color: #0000FF;">Emit</span><span style="color: #008000;">&#40;</span>OpCodes<span style="color: #008000;">.</span><span style="color: #0000FF;">Call</span>, <span style="color: #008000;">typeof</span><span style="color: #008000;">&#40;</span>ViewModelBase<span style="color: #008000;">&#41;</span><span style="color: #008000;">.</span><span style="color: #0000FF;">GetMethod</span><span style="color: #008000;">&#40;</span><span style="color: #666666;">&quot;Set&quot;</span>, BindingFlags<span style="color: #008000;">.</span><span style="color: #0000FF;">NonPublic</span> <span style="color: #008000;">|</span> BindingFlags<span style="color: #008000;">.</span><span style="color: #0000FF;">Instance</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">.</span><span style="color: #0000FF;">MakeGenericMethod</span><span style="color: #008000;">&#40;</span>propertyType<span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
  setterIL<span style="color: #008000;">.</span><span style="color: #0000FF;">Emit</span><span style="color: #008000;">&#40;</span>OpCodes<span style="color: #008000;">.</span><span style="color: #0000FF;">Ret</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
  property<span style="color: #008000;">.</span><span style="color: #0000FF;">SetGetMethod</span><span style="color: #008000;">&#40;</span>getter<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
  property<span style="color: #008000;">.</span><span style="color: #0000FF;">SetSetMethod</span><span style="color: #008000;">&#40;</span>setter<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
<span style="color: #008000;">&#125;</span></pre></div></div>

<p>Whew!  Although all that IL looks a bit scary, we can pick this apart bit by bit to see how each property gets implemented.  First we need a backing field, so we call DefineField.  We&#8217;re going to need to refer to this field later, when we implement the property getter and setter, so we keep hold of the returned FieldBuilder.  Next we define the property itself, which is as exciting as a not very exciting thing.  Then comes the good bit: defining the property getter and setter.  Notice the &#8220;get_&#8221;/&#8221;set_&#8221; prefix convention and the getter and setter signatures.</p>
<p>The setter has a couple of interesting features.  The first is that when we call the base class Set method in the setter, we can pass a MethodInfo obtained in the usual way, via good old-fashioned Reflection.  The second is that when we want to refer to the backing field &#8212; to get its value in the getter, and to pass a reference to it in the setter &#8212; we can do so using the FieldBuilder we got back from DefineField.  This might seem inconsistent &#8212; how come we use an old-school Reflection MethodInfo for the method but a dynamic FieldBuilder for the field?  Well, all the &#8216;builder&#8217; classes are also &#8216;info&#8217; classes: for example, a FieldBuilder is a FieldInfo.  The Emit method accepts the &#8216;info&#8217; classes, so that we can pass members that aren&#8217;t part of the dynamic assembly (like the ViewModelBase.Set method), and thanks to inheritance this also allows the Emit method to accept the &#8216;builder&#8217; classes, which we need so we can pass members which *are* part of the dynamic assembly (like the field).</p>
<p>Finally, how did I know what IL to write in the getter and setter?  You should know this by now: I cheated.  I wrote an example Profile class in C#, compiled that, opened it in ILDASM and just adapted the method bodies to the property name and type variables.</p>
<p><strong>It works!</strong></p>
<p>And that&#8217;s it.  We now have a working type &#8212; we can instantiate it from a list of properties, set those dynamically created properties, see the change notifications and retrieve their values.</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;">var t <span style="color: #008000;">=</span> CreateProfileType<span style="color: #008000;">&#40;</span><span style="color: #008000;">new</span> Dictionary<span style="color: #008000;">&lt;</span><span style="color: #6666cc; font-weight: bold;">string</span>, Type<span style="color: #008000;">&gt;</span> <span style="color: #008000;">&#123;</span> <span style="color: #008000;">&#123;</span> <span style="color: #666666;">&quot;SomeInt&quot;</span>, <span style="color: #008000;">typeof</span><span style="color: #008000;">&#40;</span><span style="color: #6666cc; font-weight: bold;">int</span><span style="color: #008000;">&#41;</span> <span style="color: #008000;">&#125;</span>, <span style="color: #008000;">&#123;</span> <span style="color: #666666;">&quot;SomeStr&quot;</span>, <span style="color: #008000;">typeof</span><span style="color: #008000;">&#40;</span><span style="color: #6666cc; font-weight: bold;">string</span><span style="color: #008000;">&#41;</span> <span style="color: #008000;">&#125;</span> <span style="color: #008000;">&#125;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
dynamic o <span style="color: #008000;">=</span> Activator<span style="color: #008000;">.</span><span style="color: #0000FF;">CreateInstance</span><span style="color: #008000;">&#40;</span>t<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#40;</span>INotifyPropertyChanged<span style="color: #008000;">&#41;</span>o<span style="color: #008000;">&#41;</span><span style="color: #008000;">.</span><span style="color: #0000FF;">PropertyChanged</span> <span style="color: #008000;">+=</span> <span style="color: #008000;">&#40;</span>s, e<span style="color: #008000;">&#41;</span> <span style="color: #008000;">=&gt;</span> <span style="color: #008000;">&#123;</span> Console<span style="color: #008000;">.</span><span style="color: #0000FF;">WriteLine</span><span style="color: #008000;">&#40;</span><span style="color: #666666;">&quot;changed &quot;</span> <span style="color: #008000;">+</span> e<span style="color: #008000;">.</span><span style="color: #0000FF;">PropertyName</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span> <span style="color: #008000;">&#125;</span><span style="color: #008000;">;</span>
o<span style="color: #008000;">.</span><span style="color: #0000FF;">SomeInt</span> <span style="color: #008000;">=</span> <span style="color: #FF0000;">123</span><span style="color: #008000;">;</span>
o<span style="color: #008000;">.</span><span style="color: #0000FF;">SomeStr</span> <span style="color: #008000;">=</span> <span style="color: #666666;">&quot;hello&quot;</span><span style="color: #008000;">;</span>
Console<span style="color: #008000;">.</span><span style="color: #0000FF;">WriteLine</span><span style="color: #008000;">&#40;</span>o<span style="color: #008000;">.</span><span style="color: #0000FF;">SomeInt</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
Console<span style="color: #008000;">.</span><span style="color: #0000FF;">WriteLine</span><span style="color: #008000;">&#40;</span>o<span style="color: #008000;">.</span><span style="color: #0000FF;">SomeStr</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span></pre></div></div>

<p>As I said, it&#8217;s not a very realistic example, but I hope it&#8217;s simple enough to be easy to follow, and that this has given you enough of a leg up to create your own more sophisticated runtime generated types when the occasion demands!  Have fun!</p>
<p>P.S. <a href="http://fromthedevtrenches.blogspot.com/">Carel Lotz</a> was kind enough to draw our attention to a library named RunSharp which provides a rather friendlier wrapper over some of the IL nastiness.  He&#8217;s got a tutorial on it at <a href="http://fromthedevtrenches.blogspot.com/2010/08/runsharp-il-generation-for-dummies.html">http://fromthedevtrenches.blogspot.com/2010/08/runsharp-il-generation-for-dummies.html</a> &#8212; check it out!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.mindscapehq.com/blog/index.php/2011/12/06/runtime-code-generation-for-types/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Reflection, performance and runtime code generation</title>
		<link>http://www.mindscapehq.com/blog/index.php/2011/11/27/reflection-performance-and-runtime-code-generation/</link>
		<comments>http://www.mindscapehq.com/blog/index.php/2011/11/27/reflection-performance-and-runtime-code-generation/#comments</comments>
		<pubDate>Sun, 27 Nov 2011 22:56:53 +0000</pubDate>
		<dc:creator>Ivan Towlson</dc:creator>
				<category><![CDATA[Visual Studio]]></category>

		<guid isPermaLink="false">http://www.mindscapehq.com/blog/?p=3948</guid>
		<description><![CDATA[If you&#8217;re developing a library or a utility module, you&#8217;ll often you need to make it work with different types &#8212; including types that you don&#8217;t know about at build time. In many cases, you can handle this with .NET generics, but sometimes you need to work with the specific features of types, without knowing [...]]]></description>
				<content:encoded><![CDATA[<p>If you&#8217;re developing a library or a utility module, you&#8217;ll often you need to make it work with different types &#8212; including types that you don&#8217;t know about at build time.  In many cases, you can handle this with .NET generics, but sometimes you need to work with the specific features of types, without knowing what those types are.  For example, in LightSpeed, we need to be able to set the fields of an entity from a database, without knowing what those entity fields are.  Or if you&#8217;re writing a generic Clone method, you need to be able to copy fields from one object to another.  You can&#8217;t do this with generics because you need to access the specific fields, whereas generics only allow you to access stuff in interfaces or other constraints declared at design time.</p>
<p>The traditional solution to this is to use Reflection.  Reflection gives you a way to enumerate and invoke methods, properties, constructors and fields.  It&#8217;s pretty easy to write the &#8216;set all fields&#8217; or &#8216;copy all fields&#8217; code this way.  However, the big problem is that it&#8217;s slow.  Horribly, horribly slow.</p>
<p>If your code runs only occasionally, this may not be a big deal, but if you&#8217;re working with a lot of objects, Reflection code quickly becomes a bottleneck.  At this point, it&#8217;s worth looking at an alternative: runtime code generation.</p>
<p>The idea of runtime code generation goes something like this.</p>
<ul>
<li>If we could write code that was specific to each type we had to handle, then that would run really fast.</li>
<li>But we can&#8217;t do that, because we don&#8217;t have access to the types that the user of our library is going to come up with.</li>
<li>But if we did have access to those types, the code we&#8217;d write for each type would follow a predictable pattern (maybe simple, maybe complicated &#8212; but there must *be* a pattern or we couldn&#8217;t be writing a generic library in the first place!).</li>
<li>Now if the type-specific code follows a predictable pattern, we can write a program where we give it a type, and it generates and compiles the type-specific code.</li>
<li>And in that case, we can run that program at run-time, and it will create fast, type-specific methods for each of our user&#8217;s types!</li>
</ul>
<p>At first this may sound crazy.  Running a code generator and compiler sounds like it will be even slower than using Reflection.  And won&#8217;t the code generator have to use Reflection to get the details of the user type anyway?  Yes and yes.  But the code generator and compiler have to run only once per type.  They produce a compiled method, and we can call that method again and again, without needing to regenerate or recompile it.</p>
<p>Okay, so maybe it&#8217;s not crazy, but isn&#8217;t it fearfully difficult?  Well, it can be, but it certainly doesn&#8217;t have to be.  We&#8217;ll look at three ways, starting out at the highest level and gradually dropping down to the lowest.</p>
<p><strong>Generating code using a high-level language</strong></p>
<p>The easiest way to generate code is as C# or Visual Basic!  For example, you could build up C# code as a string, either by concatenating strings or by hosting a templating engine such as T4.  You can then compile the generated code using CodeDom.</p>
<p>This is pretty easy, though it requires careful attention to detail.  However, CodeDom is quite heavyweight and slow, and you have to basically compile an entire assembly, which means you incur even more overhead creating classes and locating your generated method in the assembly.  Since we&#8217;re doing this for performance reasons, this often makes CodeDom a somewhat unattractive choice, but for some scenarios it can be excellent.</p>
<p><strong>Generating code with expression trees</strong></p>
<p>Expression trees were introduced as part of LINQ in .NET 3.5.  An expression tree is like an abstract representation of a piece of code, not bound to any particular language.  Usually the compiler creates expression trees for you as part of a LINQ expression, but you can also create them yourself using the expressions API, and (tada!) you can compile them to delegates.</p>
<p>The trick to runtime code generation using expression trees is to figure out what your desired code would look like as a lambda.  For example, suppose you want to generate a method to instantiate objects of an unknown type &#8212; basically the same as Activator.CreateInstance, but fast.  (I&#8217;m going to ignore the possibility of using generics and the new() constraint, which would solve this problem in many, but not all, cases, because I want to show you expression trees, and this is a nice simple example.)  Here&#8217;s a lambda that would do that:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;">Func<span style="color: #008000;">&lt;</span>T<span style="color: #008000;">&gt;</span> creator <span style="color: #008000;">=</span> <span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span> <span style="color: #008000;">=&gt;</span> <span style="color: #008000;">new</span> T<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
<span style="color: #008080; font-style: italic;">// usage: T instance = creator();</span></pre></div></div>

<p>How can we create a corresponding expression tree for a type?  Fortunately, the expressions API corresponds pretty closely to the constructs we used in our lambda:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;">var lambdaBody <span style="color: #008000;">=</span> Expression<span style="color: #008000;">.</span><span style="color: #008000;">New</span><span style="color: #008000;">&#40;</span>type<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>  <span style="color: #008080; font-style: italic;">// this corresponds to &quot;new T()&quot;</span>
var lambdaExpr <span style="color: #008000;">=</span> Expression<span style="color: #008000;">.</span><span style="color: #0000FF;">Lambda</span><span style="color: #008000;">&lt;</span>Func<span style="color: #008000;">&lt;</span><span style="color: #6666cc; font-weight: bold;">object</span><span style="color: #008000;">&gt;&gt;</span><span style="color: #008000;">&#40;</span>lambdaBody<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>  <span style="color: #008080; font-style: italic;">// this corresponds to &quot;() =&gt; ...&quot;</span>
Func<span style="color: #008000;">&lt;</span><span style="color: #6666cc; font-weight: bold;">object</span><span style="color: #008000;">&gt;</span> creator <span style="color: #008000;">=</span> lambdaExpr<span style="color: #008000;">.</span><span style="color: #0000FF;">Compile</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span></pre></div></div>

<p>The flow here is a bit tricky to read because it&#8217;s inside-out rather than left-to-right.  We first create an expression representing the body of the lambda: &#8220;new T()&#8221;.  Our body is so simple we can do this using a single Expression.New call.  Then we wrap it in an Expression.Lambda, which roughly corresponds to sticking the &#8220;() =>&#8221; on the front.  .NET requires the Expression.Lambda instead of allowing us to compile the body directly because in the more general case the lambda might have parameters.</p>
<p>If you&#8217;re wondering whether this is worthwhile, calling the &#8220;creator&#8221; delegate is now about five times faster than calling Activator.CreateInstance (at least on my machine).  If the delegate were replacing more Reflection calls &#8212; as in the object cloning example &#8212; then the savings would probably be even greater.</p>
<p>Expression trees are reasonably easy to write, reasonably safe, and quite efficient.  For many runtime code generation applications, these could well be the sweet spot.</p>
<p><strong>Generating code using dynamic methods</strong></p>
<p>Expression trees are spiffy, but have some limitations.  One of these is that in .NET 3.5 you are limited to simple expressions.  (This limitation is greatly relaxed in .NET 4, which provides new expression types to represent things like loops, if statements and goto.  Yes, all this whizzy modern technology, and it still has goto.)  Another is that you can&#8217;t use an expression tree to generate a member method, which is important if your generated code needs access to private members of the user type, as in the cloning example which needs access to private fields.  For that, you need to drop down to the lowest level: generating IL directly using dynamic methods.</p>
<p>(By the way, dynamic methods aren&#8217;t the only place you can use the direct IL generation technique.  If you need to generate an entire class or assembly, then you can&#8217;t use expression trees for that, so you have to either move up to CodeDom, or down AssemblyBuilder, TypeBuilder and related Reflection.Emit classes, in which case you&#8217;ll be generating IL into the method bodies.  I&#8217;m not going to cover that here; maybe some other time.)</p>
<p>Setting up a dynamic method is pretty easy.  Here&#8217;s one for the &#8216;instantiate a new object&#8217; example we had for expression trees:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #008080; font-style: italic;">// using System.Reflection.Emit;</span>
&nbsp;
var dynamicMethod <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> DynamicMethod<span style="color: #008000;">&#40;</span>
  <span style="color: #666666;">&quot;create_&quot;</span> <span style="color: #008000;">+</span> type<span style="color: #008000;">.</span><span style="color: #0000FF;">GetName</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span>,     <span style="color: #008080; font-style: italic;">// name of the dynamic method</span>
  <span style="color: #008000;">typeof</span><span style="color: #008000;">&#40;</span><span style="color: #6666cc; font-weight: bold;">object</span><span style="color: #008000;">&#41;</span>,                 <span style="color: #008080; font-style: italic;">// the return type</span>
  <span style="color: #008000;">new</span> Type<span style="color: #008000;">&#91;</span><span style="color: #FF0000;">0</span><span style="color: #008000;">&#93;</span>,                    <span style="color: #008080; font-style: italic;">// the dynamic method has no parameters</span>
  type<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>                          <span style="color: #008080; font-style: italic;">// which type it's a member of</span>
<span style="color: #008080; font-style: italic;">// TODO: create method body</span>
Func<span style="color: #008000;">&lt;</span><span style="color: #6666cc; font-weight: bold;">object</span><span style="color: #008000;">&gt;</span> creator <span style="color: #008000;">=</span> dynamicMethod<span style="color: #008000;">.</span><span style="color: #0000FF;">CreateDelegate</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">typeof</span><span style="color: #008000;">&#40;</span>Func<span style="color: #008000;">&lt;</span><span style="color: #6666cc; font-weight: bold;">object</span><span style="color: #008000;">&gt;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span></pre></div></div>

<p>You just need to provide a name for the method, specify the signature (parameter and return types), and say which type the method is a member of, though this is usually only an issue if the method needs to access private members such as fields.</p>
<p>The tricky bit is generating the IL for the dynamic method.  No friendly expression trees or C# compiler to help you here: just man versus IL opcode, two enter, only one leaves.  This means you have two alternatives: (1) learn IL or (2) cheat.</p>
<p>I&#8217;m not going to talk about option 1.</p>
<p>To cheat, you write an example instance of your dynamic method in a high level language such as C#, baking in an example &#8216;user type&#8217; you have created for the purpose.  You then compile this in the usual way to produce an EXE or DLL.  (Make sure you compile in Release mode &#8212; if you&#8217;re in Debug mode then the compiler will emit all sorts of extra nonsense which is no use to you.)</p>
<p>Now open your compiled EXE or DLL in ILDASM.  Yes, that&#8217;s right, ILDASM, the application you last looked at in 2002 and which you thought had been completely superseded by Reflector.  ILDASM will show you the IL op codes that your example method compiled to, and all you need to do is copy those op codes into your DynamicMethod, replacing specific references to fields, types, etc. of your example type with dynamically-generated references to the fields, types, etc. of the type for which you are creating the DynamicMethod.</p>
<p>For example, here&#8217;s what ILDASM shows for new-ing up an object:</p>
<p><a href="http://www.mindscapehq.com/blog/wp-content/uploads/2011/11/ildasm-create-method.png"><img src="http://www.mindscapehq.com/blog/wp-content/uploads/2011/11/ildasm-create-method.png" alt="" title="IL for method which just does &quot;return new Dromedary()&quot;" width="659" height="211" class="alignleft size-full wp-image-3952" /></a></p>
<p>We can map this across pretty mechanically to IL op code objects in the System.Reflection.Emit.OpCodes class, and thereby generate the equivalent IL into our dynamic method.</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;">var constructor <span style="color: #008000;">=</span> type<span style="color: #008000;">.</span><span style="color: #0000FF;">GetConstructor</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">new</span> Type<span style="color: #008000;">&#91;</span><span style="color: #008000;">&#93;</span> <span style="color: #008000;">&#123;</span> <span style="color: #008000;">&#125;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>  <span style="color: #008080; font-style: italic;">// we want to call the default constructor</span>
&nbsp;
var ilGenerator <span style="color: #008000;">=</span> dynamicMethod<span style="color: #008000;">.</span><span style="color: #0000FF;">GetILGenerator</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
ilGenerator<span style="color: #008000;">.</span><span style="color: #0000FF;">Emit</span><span style="color: #008000;">&#40;</span>OpCodes<span style="color: #008000;">.</span><span style="color: #0000FF;">Newobj</span>, constructor<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
ilGenerator<span style="color: #008000;">.</span><span style="color: #0000FF;">Emit</span><span style="color: #008000;">&#40;</span>OpCodes<span style="color: #008000;">.</span><span style="color: #0000FF;">Ret</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span></pre></div></div>

<p>Obviously, in most cases, the code generation would be more complex: for example, in the object cloning scenario, you&#8217;d loop over the fields you wanted to copy, emitting a Ldfld (load field) and Stfld (store to field) op code for each one until you&#8217;d built up the entire dynamic method.</p>
<p>IL generation is low-level, but that makes it very efficient.  There&#8217;s no extra compilation step as there was with expression trees.  If you have to generate a lot of dynamic methods, then IL and DynamicMethod could be the way to go.</p>
<p><strong>Conclusion</strong></p>
<p>Most applications don&#8217;t need runtime code generation &#8212; either they know everything they need to know at compile time, or the performance considerations are such that Reflection is good enough.  However, if you&#8217;re running a lot of Reflection code, then replacing it with type-specific code generated at runtime can give you a big performance boost.  You&#8217;ll need to figure out how to trade off difficulty (and hence maintainability) against performance, but I hope this article gives you some idea of what the options are and what tradeoffs you&#8217;re making with each one.  Have fun!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.mindscapehq.com/blog/index.php/2011/11/27/reflection-performance-and-runtime-code-generation/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>In bed with Roslyn</title>
		<link>http://www.mindscapehq.com/blog/index.php/2011/10/20/in-bed-with-roslyn/</link>
		<comments>http://www.mindscapehq.com/blog/index.php/2011/10/20/in-bed-with-roslyn/#comments</comments>
		<pubDate>Fri, 21 Oct 2011 00:39:39 +0000</pubDate>
		<dc:creator>Ivan Towlson</dc:creator>
				<category><![CDATA[Visual Studio]]></category>

		<guid isPermaLink="false">http://www.mindscapehq.com/blog/?p=3883</guid>
		<description><![CDATA[Microsoft have been talking about their &#8220;C# compiler as a service&#8221; project, aka Roslyn, for a couple of years now, and yesterday the C# team finally released a preview version. Being a bit of a language geek, I was interested to see if I could use Roslyn not only to perform analysis and refactorings but [...]]]></description>
				<content:encoded><![CDATA[<p>Microsoft have been talking about their &#8220;C# compiler as a service&#8221; project, aka Roslyn, for a couple of years now, and yesterday the C# team finally released a preview version.  Being a bit of a language geek, I was interested to see if I could use Roslyn not only to perform analysis and refactorings but to extend the C# language itself.  The reason for wanting to do this is to replace repetitive and error-prone boilerplate code with terser, more expressive code &#8212; quicker to write, easier to read and no chance for human error to muck it up.</p>
<p><strong>The motivating example</strong></p>
<p>If you&#8217;ve written much WPF or Silverlight code, you&#8217;ve undoubtedly written a bunch of dependency properties.  Because C# has no built-in support for DPs, this means you have to write a bunch of code spread across several members, something like this:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #0600FF; font-weight: bold;">static</span> <span style="color: #0600FF; font-weight: bold;">readonly</span> DependencyProperty WidgetudeProperty <span style="color: #008000;">=</span>
  DependencyProperty<span style="color: #008000;">.</span><span style="color: #0000FF;">Register</span><span style="color: #008000;">&#40;</span><span style="color: #666666;">&quot;Widgetude&quot;</span>, <span style="color: #008000;">typeof</span><span style="color: #008000;">&#40;</span><span style="color: #6666cc; font-weight: bold;">int</span><span style="color: #008000;">&#41;</span>, <span style="color: #008000;">typeof</span><span style="color: #008000;">&#40;</span>Widget<span style="color: #008000;">&#41;</span>,
    <span style="color: #008000;">new</span> FrameworkPropertyMetadata<span style="color: #008000;">&#40;</span>OnWidgetudeChanged<span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
<span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #6666cc; font-weight: bold;">int</span> Widgetude
<span style="color: #008000;">&#123;</span>
  get <span style="color: #008000;">&#123;</span> <span style="color: #0600FF; font-weight: bold;">return</span> <span style="color: #008000;">&#40;</span><span style="color: #6666cc; font-weight: bold;">int</span><span style="color: #008000;">&#41;</span>GetValue<span style="color: #008000;">&#40;</span>WidgetudeProperty<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span> <span style="color: #008000;">&#125;</span>
  set <span style="color: #008000;">&#123;</span> SetValue<span style="color: #008000;">&#40;</span>WidgetudeProperty, value<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span> <span style="color: #008000;">&#125;</span>
<span style="color: #008000;">&#125;</span>
&nbsp;
<span style="color: #0600FF; font-weight: bold;">private</span> <span style="color: #0600FF; font-weight: bold;">static</span> <span style="color: #6666cc; font-weight: bold;">void</span> OnWidgetudeChanged<span style="color: #008000;">&#40;</span>DependencyObject d, DependencyPropertyChangedEventArgs e<span style="color: #008000;">&#41;</span>
<span style="color: #008000;">&#123;</span>
  <span style="color: #008080; font-style: italic;">// on-change logic here</span>
<span style="color: #008000;">&#125;</span></pre></div></div>

<p>This is not only boring to write, it is hard to read because the code is cluttered with boilerplate, and it is prone to error.  If I had a dollar for everybody who put business logic in the CLR property setter and then wondered why it wasn&#8217;t being run when a binding updated&#8230; well, I&#8217;d have $3.00.  And it&#8217;s awful to maintain.  For example, if I change the property to a double, I have to update the type in three places.  If I change the property name, I have to update it in seven!</p>
<p>Wouldn&#8217;t it be sweet if C# had language support for DPs, so you could write:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #008000;">&#91;</span>dependency<span style="color: #008000;">&#93;</span> <span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #6666cc; font-weight: bold;">int</span> Widgetude
<span style="color: #008000;">&#123;</span>
  change <span style="color: #008000;">&#123;</span> <span style="color: #008080; font-style: italic;">/* on-change logic here */</span> <span style="color: #008000;">&#125;</span>
<span style="color: #008000;">&#125;</span></pre></div></div>

<p>and the C# compiler would treat it as though you&#8217;d written all the boilerplate?  Of course, that&#8217;s impossible because even if you used something like PostSharp to do a rewriting at the IL level, there&#8217;s no way to represent a &#8220;property change&#8221; element in IL &#8212; it&#8217;s simply not legal C#.</p>
<p>Enter Roslyn.</p>
<p><strong>Roslyn is forgiving</strong></p>
<p>Roslyn is about building tooling for source code, and one of the nasty facts about source code is that it is in an invalid state more often than not.  For example, you may be halfway through writing an &#8216;if&#8217; statement and haven&#8217;t done the closing brace yet.  Or you&#8217;ve written a call to a method but you haven&#8217;t written that method yet.  Or you&#8217;ve misspelt &#8216;get&#8217; as &#8216;grt&#8217; in a property accessor.</p>
<p>A compiler won&#8217;t stand for this nonsense.  Roslyn, at least at the parsing stage, is much more forgiving.  You can write any old gibberish and Roslyn will do its best to organise it into a nice syntax tree, even if that syntax tree is uncompilable.</p>
<p>This forgiving nature means we can sneak our own illegal constructs into Roslyn, and use the Roslyn APIs to transform them into legal constructs.  It&#8217;s a risky business, because Roslyn will try to interpret whatever we write as valid C#, so we probably shouldn&#8217;t be relying on any particular interpretation of invalid C#, but what the heck.  If you&#8217;re going to have a sweet, forgiving nature, you must expect people to take advantage of it.</p>
<p><strong>Reading code in with Roslyn</strong></p>
<p>Reading code in with Roslyn is a snap &#8212; just call SyntaxTree.ParseCompilationUnit.</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;">SyntaxTree tree <span style="color: #008000;">=</span> SyntaxTree<span style="color: #008000;">.</span><span style="color: #0000FF;">ParseCompilationUnit</span><span style="color: #008000;">&#40;</span>sourceCode<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
var root <span style="color: #008000;">=</span> <span style="color: #008000;">&#40;</span>CompilationUnitSyntax<span style="color: #008000;">&#41;</span><span style="color: #008000;">&#40;</span>tree<span style="color: #008000;">.</span><span style="color: #0000FF;">Root</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span></pre></div></div>

<p>A SyntaxTree is an abstract representation of the source code &#8212; warts and all.  It includes everything: good code, bad code, whitespace, rude comments about the client, rude comments about the client&#8217;s mother, the lot.  This is all represented as a tree &#8212; at the top is a root node containing usings, members, trivia (e.g. whitespace and comments), etc., then each member (e.g. a namespace) contains sub-members (e.g. the classes in that namespace), and so on down to individual statements and expressions.</p>
<p>If we give Roslyn our made-up dependency property syntax (suitably enclosed in a class of course), it cheerfully parses it as a property (represented as a PropertyDeclarationSyntax object).  And the change { } fragment looks enough like a get or set accessor that the Roslyn parser actually accepts it as an accessor, noting only with clinical disinterest that it wasn&#8217;t recognised as the get or set accessor.</p>
<p>Of course, the compiler stage of Roslyn would pitch a fit if it saw an unrecognised accessor.  But we&#8217;re not going to ask the compiler stage its opinion.  We&#8217;re going to take what the parser produces, and turn it into something of our own.</p>
<p><strong>Rewriting code with Roslyn</strong></p>
<p>Roslyn syntax trees are immutable.  This is computer science jargon for &#8220;good,&#8221; but it does mean we can&#8217;t just party on the SyntaxTree object.  Instead we have to transform it to produce a new SyntaxTree object.  Roslyn provides a bunch of helper methods for updating, extending and pruning syntax trees, but for our purposes we&#8217;re going to use a gadget called SyntaxRewriter.  SyntaxRewriter lets you traverse an entire syntax tree making whatever changes you want (though again, remember that &#8216;making changes&#8217; doesn&#8217;t actually modify an existing object, it produces a new one).</p>
<p>Our syntax rewriter is going to rewrite our property to be a CLR dependency property wrapper, and it&#8217;s also going to inject a DependencyProperty field and an optional change callback into the enclosing class.  That means we&#8217;re interested in two kinds of syntax tree node.  First, we&#8217;re interested in property declarations, because (a) we need to rewrite them and (b) we need to generate fields and callback methods from them.  Second, we&#8217;re interested in class declarations, because we need to poke those fields and callback methods into the containing class.</p>
<p>This observation makes it easy to stub out our rewriter.</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #6666cc; font-weight: bold;">class</span> DPRewriter <span style="color: #008000;">:</span> SyntaxRewriter
<span style="color: #008000;">&#123;</span>
  <span style="color: #0600FF; font-weight: bold;">private</span> <span style="color: #0600FF; font-weight: bold;">readonly</span> List<span style="color: #008000;">&lt;</span>FieldDeclarationSyntax<span style="color: #008000;">&gt;</span> _fields <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> List<span style="color: #008000;">&lt;</span>FieldDeclarationSyntax<span style="color: #008000;">&gt;</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
  <span style="color: #0600FF; font-weight: bold;">private</span> <span style="color: #0600FF; font-weight: bold;">readonly</span> List<span style="color: #008000;">&lt;</span>MethodDeclarationSyntax<span style="color: #008000;">&gt;</span> _methods <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> List<span style="color: #008000;">&lt;</span>MethodDeclarationSyntax<span style="color: #008000;">&gt;</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
  <span style="color: #0600FF; font-weight: bold;">protected</span> <span style="color: #0600FF; font-weight: bold;">override</span> SyntaxNode VisitPropertyDeclaration<span style="color: #008000;">&#40;</span>PropertyDeclarationSyntax node<span style="color: #008000;">&#41;</span>
  <span style="color: #008000;">&#123;</span>
    <span style="color: #008080; font-style: italic;">// TBA</span>
  <span style="color: #008000;">&#125;</span>
&nbsp;
  <span style="color: #0600FF; font-weight: bold;">protected</span> <span style="color: #0600FF; font-weight: bold;">override</span> SyntaxNode VisitClassDeclaration<span style="color: #008000;">&#40;</span>ClassDeclarationSyntax node<span style="color: #008000;">&#41;</span>
  <span style="color: #008000;">&#123;</span>
    <span style="color: #008080; font-style: italic;">// TBA</span>
  <span style="color: #008000;">&#125;</span>
<span style="color: #008000;">&#125;</span></pre></div></div>

<p>The fields and methods collections are going to hold the dependency property fields and the change callback methods that we generate during property visits, so that we can later inject them into the class.</p>
<p>I&#8217;ve also been lazy and chosen an attribute-like syntax for marking a property as a dependency property.  This makes the first stage of our property handler pretty easy too:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF; font-weight: bold;">protected</span> <span style="color: #0600FF; font-weight: bold;">override</span> SyntaxNode VisitPropertyDeclaration<span style="color: #008000;">&#40;</span>PropertyDeclarationSyntax node<span style="color: #008000;">&#41;</span>
<span style="color: #008000;">&#123;</span>
  <span style="color: #6666cc; font-weight: bold;">bool</span> isDP <span style="color: #008000;">=</span> node<span style="color: #008000;">.</span><span style="color: #0000FF;">Attributes</span>
                  <span style="color: #008000;">.</span><span style="color: #0000FF;">SelectMany</span><span style="color: #008000;">&#40;</span>a <span style="color: #008000;">=&gt;</span> a<span style="color: #008000;">.</span><span style="color: #0000FF;">ChildNodes</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">.</span><span style="color: #0000FF;">OfType</span><span style="color: #008000;">&lt;</span>AttributeSyntax<span style="color: #008000;">&gt;</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span>
                  <span style="color: #008000;">.</span><span style="color: #0000FF;">Any</span><span style="color: #008000;">&#40;</span>a <span style="color: #008000;">=&gt;</span> a<span style="color: #008000;">.</span><span style="color: #0000FF;">Name</span><span style="color: #008000;">.</span><span style="color: #0000FF;">PlainName</span> <span style="color: #008000;">==</span> <span style="color: #666666;">&quot;dependency&quot;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
  <span style="color: #0600FF; font-weight: bold;">if</span> <span style="color: #008000;">&#40;</span><span style="color: #008000;">!</span>isDP<span style="color: #008000;">&#41;</span>
  <span style="color: #008000;">&#123;</span>
    <span style="color: #0600FF; font-weight: bold;">return</span> <span style="color: #0600FF; font-weight: bold;">base</span><span style="color: #008000;">.</span><span style="color: #0000FF;">VisitPropertyDeclaration</span><span style="color: #008000;">&#40;</span>node<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
  <span style="color: #008000;">&#125;</span>
&nbsp;
  <span style="color: #008080; font-style: italic;">// real work TBA</span>
<span style="color: #008000;">&#125;</span></pre></div></div>

<p>Unfortunately, this is pretty much the end of the easy bit.  Now we need to dive in and actually do our rewriting.</p>
<p><strong>Rewriting the dependency property syntax</strong></p>
<p>You probably want to see some code here, but you see, the other thing about Roslyn is, Roslyn is <em>verbose</em>.  Really, really, verbose.  I mean, it makes CodeDom look terse.  It&#8217;s not really Roslyn&#8217;s fault &#8212; you&#8217;re manipulating syntax trees which are trying to provide full flexibility and fidelity to source code, so there&#8217;s bound to be a lot of detail and depth &#8212; but it does make it a pain in the backside to post any useful chunk of Roslyn code.</p>
<p>Consider yourself warned.</p>
<p>Our rewrite code needs to do three things:</p>
<ul>
<li>Add a field of type DependencyProperty to the fields list</li>
<li>Replace the property with the DP implementation</li>
<li>If the property had a change &#8216;accessor,&#8217; wrap the body of that accessor up in a method and add that to the methods list</li>
</ul>
<p>To build new Roslyn objects, we use the Syntax.* factory methods.  Each of these takes 84 parameters, most of which are optional, so if you don&#8217;t like C# named arguments, look away now.  Here, for example, is how to build the field.  (<strong>BIG CAVEAT:</strong> I&#8217;ve only been playing with Roslyn for a few hours.  I&#8217;m pretty sure I&#8217;m using the wrong idioms for some things, and that there are easier ways to do others.  Don&#8217;t take this as a best practice guide.)</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #008080; font-style: italic;">// Desired output:</span>
<span style="color: #008080; font-style: italic;">// DependencyProperty XxxProperty = DependencyProperty.Register(&quot;Xxx&quot;,</span>
<span style="color: #008080; font-style: italic;">//   typeof(PropType), typeof(OwnerType),</span>
<span style="color: #008080; font-style: italic;">//   new FrameworkPropertyMetadata(OnXxxChanged);</span>
&nbsp;
<span style="color: #008080; font-style: italic;">// Set up some useful elements</span>
var changeCallback <span style="color: #008000;">=</span> node<span style="color: #008000;">.</span><span style="color: #0000FF;">AccessorList</span><span style="color: #008000;">.</span><span style="color: #0000FF;">Accessors</span><span style="color: #008000;">.</span><span style="color: #0000FF;">FirstOrDefault</span><span style="color: #008000;">&#40;</span>a <span style="color: #008000;">=&gt;</span> a<span style="color: #008000;">.</span><span style="color: #0000FF;">Kind</span> <span style="color: #008000;">==</span> SyntaxKind<span style="color: #008000;">.</span><span style="color: #0000FF;">UnknownAccessorDeclaration</span> <span style="color: #008000;">&amp;&amp;</span> a<span style="color: #008000;">.</span><span style="color: #0000FF;">Keyword</span><span style="color: #008000;">.</span><span style="color: #0000FF;">ValueText</span> <span style="color: #008000;">==</span> <span style="color: #666666;">&quot;change&quot;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
<span style="color: #6666cc; font-weight: bold;">bool</span> hasChangeCallback <span style="color: #008000;">=</span> changeCallback <span style="color: #008000;">!=</span> <span style="color: #0600FF; font-weight: bold;">null</span><span style="color: #008000;">;</span>
&nbsp;
var dpType <span style="color: #008000;">=</span> Syntax<span style="color: #008000;">.</span><span style="color: #0000FF;">ParseTypeName</span><span style="color: #008000;">&#40;</span><span style="color: #666666;">&quot;System.Windows.DependencyProperty&quot;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
var ownerType <span style="color: #008000;">=</span> Syntax<span style="color: #008000;">.</span><span style="color: #0000FF;">ParseTypeName</span><span style="color: #008000;">&#40;</span>node<span style="color: #008000;">.</span><span style="color: #0000FF;">FirstAncestorOrSelf</span><span style="color: #008000;">&lt;</span>ClassDeclarationSyntax<span style="color: #008000;">&gt;</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">.</span><span style="color: #0000FF;">Identifier</span><span style="color: #008000;">.</span><span style="color: #0000FF;">ValueText</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
<span style="color: #6666cc; font-weight: bold;">string</span> propName <span style="color: #008000;">=</span> node<span style="color: #008000;">.</span><span style="color: #0000FF;">Identifier</span><span style="color: #008000;">.</span><span style="color: #0000FF;">ValueText</span><span style="color: #008000;">;</span>
ExpressionSyntax propNameExpr <span style="color: #008000;">=</span> Syntax<span style="color: #008000;">.</span><span style="color: #0000FF;">LiteralExpression</span><span style="color: #008000;">&#40;</span>SyntaxKind<span style="color: #008000;">.</span><span style="color: #0000FF;">StringLiteralExpression</span>, Syntax<span style="color: #008000;">.</span><span style="color: #0000FF;">Literal</span><span style="color: #008000;">&#40;</span>text<span style="color: #008000;">:</span> <span style="color: #666666;">'&quot;'</span> <span style="color: #008000;">+</span> propName <span style="color: #008000;">+</span> <span style="color: #666666;">'&quot;'</span>, value<span style="color: #008000;">:</span> propName<span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
ExpressionSyntax typeofPropType <span style="color: #008000;">=</span> Syntax<span style="color: #008000;">.</span><span style="color: #0000FF;">TypeOfExpression</span><span style="color: #008000;">&#40;</span>argumentList<span style="color: #008000;">:</span> Syntax<span style="color: #008000;">.</span><span style="color: #0000FF;">ArgumentList</span><span style="color: #008000;">&#40;</span>arguments<span style="color: #008000;">:</span> Syntax<span style="color: #008000;">.</span><span style="color: #0000FF;">SeparatedList</span><span style="color: #008000;">&#40;</span>Syntax<span style="color: #008000;">.</span><span style="color: #0000FF;">Argument</span><span style="color: #008000;">&#40;</span>expression<span style="color: #008000;">:</span> node<span style="color: #008000;">.</span><span style="color: #0000FF;">Type</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
ExpressionSyntax typeofOwnerType <span style="color: #008000;">=</span> Syntax<span style="color: #008000;">.</span><span style="color: #0000FF;">TypeOfExpression</span><span style="color: #008000;">&#40;</span>argumentList<span style="color: #008000;">:</span> Syntax<span style="color: #008000;">.</span><span style="color: #0000FF;">ArgumentList</span><span style="color: #008000;">&#40;</span>arguments<span style="color: #008000;">:</span> Syntax<span style="color: #008000;">.</span><span style="color: #0000FF;">SeparatedList</span><span style="color: #008000;">&#40;</span>Syntax<span style="color: #008000;">.</span><span style="color: #0000FF;">Argument</span><span style="color: #008000;">&#40;</span>expression<span style="color: #008000;">:</span> ownerType<span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
<span style="color: #008080; font-style: italic;">// Build the arguments to the Register call</span>
var registerArgs <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> List<span style="color: #008000;">&lt;</span>ArgumentSyntax<span style="color: #008000;">&gt;</span> <span style="color: #008000;">&#123;</span>
  Syntax<span style="color: #008000;">.</span><span style="color: #0000FF;">Argument</span><span style="color: #008000;">&#40;</span>expression<span style="color: #008000;">:</span> propNameExpr<span style="color: #008000;">&#41;</span>,
  Syntax<span style="color: #008000;">.</span><span style="color: #0000FF;">Argument</span><span style="color: #008000;">&#40;</span>expression<span style="color: #008000;">:</span> typeofPropType<span style="color: #008000;">&#41;</span>,
  Syntax<span style="color: #008000;">.</span><span style="color: #0000FF;">Argument</span><span style="color: #008000;">&#40;</span>expression<span style="color: #008000;">:</span> typeofOwnerType<span style="color: #008000;">&#41;</span>
<span style="color: #008000;">&#125;</span><span style="color: #008000;">;</span>
&nbsp;
<span style="color: #0600FF; font-weight: bold;">if</span> <span style="color: #008000;">&#40;</span>hasChangeCallback<span style="color: #008000;">&#41;</span>
<span style="color: #008000;">&#123;</span>
  ExpressionSyntax changeMethod <span style="color: #008000;">=</span> Syntax<span style="color: #008000;">.</span><span style="color: #0000FF;">ParseName</span><span style="color: #008000;">&#40;</span><span style="color: #666666;">&quot;On&quot;</span> <span style="color: #008000;">+</span> propName <span style="color: #008000;">+</span> <span style="color: #666666;">&quot;Changed&quot;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
  ExpressionSyntax fpm <span style="color: #008000;">=</span> Syntax<span style="color: #008000;">.</span><span style="color: #0000FF;">ObjectCreationExpression</span><span style="color: #008000;">&#40;</span>
    type<span style="color: #008000;">:</span> Syntax<span style="color: #008000;">.</span><span style="color: #0000FF;">ParseTypeName</span><span style="color: #008000;">&#40;</span><span style="color: #666666;">&quot;System.Windows.FrameworkPropertyMetadata&quot;</span><span style="color: #008000;">&#41;</span>,
    argumentListOpt<span style="color: #008000;">:</span> Syntax<span style="color: #008000;">.</span><span style="color: #0000FF;">ArgumentList</span><span style="color: #008000;">&#40;</span>
      arguments<span style="color: #008000;">:</span> Syntax<span style="color: #008000;">.</span><span style="color: #0000FF;">SeparatedList</span><span style="color: #008000;">&#40;</span>Syntax<span style="color: #008000;">.</span><span style="color: #0000FF;">Argument</span><span style="color: #008000;">&#40;</span>expression<span style="color: #008000;">:</span> changeMethod<span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span>
    <span style="color: #008000;">&#41;</span>
  <span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
  registerArgs<span style="color: #008000;">.</span><span style="color: #0000FF;">Add</span><span style="color: #008000;">&#40;</span>Syntax<span style="color: #008000;">.</span><span style="color: #0000FF;">Argument</span><span style="color: #008000;">&#40;</span>expression<span style="color: #008000;">:</span> fpm<span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
<span style="color: #008000;">&#125;</span>
&nbsp;
var argSeparators <span style="color: #008000;">=</span> Enumerable<span style="color: #008000;">.</span><span style="color: #0000FF;">Repeat</span><span style="color: #008000;">&#40;</span>Syntax<span style="color: #008000;">.</span><span style="color: #0000FF;">Token</span><span style="color: #008000;">&#40;</span>SyntaxKind<span style="color: #008000;">.</span><span style="color: #0000FF;">CommaToken</span><span style="color: #008000;">&#41;</span>, registerArgs<span style="color: #008000;">.</span><span style="color: #0000FF;">Count</span> <span style="color: #008000;">-</span> <span style="color: #FF0000;">1</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">.</span><span style="color: #0000FF;">ToList</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
<span style="color: #008080; font-style: italic;">// Build the call to the Register method</span>
ExpressionSyntax dpexpr <span style="color: #008000;">=</span> Syntax<span style="color: #008000;">.</span><span style="color: #0000FF;">InvocationExpression</span><span style="color: #008000;">&#40;</span>
  expression<span style="color: #008000;">:</span> Syntax<span style="color: #008000;">.</span><span style="color: #0000FF;">ParseName</span><span style="color: #008000;">&#40;</span><span style="color: #666666;">&quot;System.Windows.DependencyProperty.Register&quot;</span><span style="color: #008000;">&#41;</span>,
  argumentList<span style="color: #008000;">:</span> Syntax<span style="color: #008000;">.</span><span style="color: #0000FF;">ArgumentList</span><span style="color: #008000;">&#40;</span>
    arguments<span style="color: #008000;">:</span> Syntax<span style="color: #008000;">.</span><span style="color: #0000FF;">SeparatedList</span><span style="color: #008000;">&#40;</span>registerArgs, argSeparators<span style="color: #008000;">&#41;</span>
  <span style="color: #008000;">&#41;</span>
<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
<span style="color: #008080; font-style: italic;">// Build the field variable</span>
<span style="color: #6666cc; font-weight: bold;">string</span> fieldName <span style="color: #008000;">=</span> propName <span style="color: #008000;">+</span> <span style="color: #666666;">&quot;Property&quot;</span><span style="color: #008000;">;</span>
VariableDeclaratorSyntax declarator <span style="color: #008000;">=</span> Syntax<span style="color: #008000;">.</span><span style="color: #0000FF;">VariableDeclarator</span><span style="color: #008000;">&#40;</span>
  identifier<span style="color: #008000;">:</span> Syntax<span style="color: #008000;">.</span><span style="color: #0000FF;">Identifier</span><span style="color: #008000;">&#40;</span>fieldName<span style="color: #008000;">&#41;</span>,
  initializerOpt<span style="color: #008000;">:</span> Syntax<span style="color: #008000;">.</span><span style="color: #0000FF;">EqualsValueClause</span><span style="color: #008000;">&#40;</span>
    value<span style="color: #008000;">:</span> dpexpr
  <span style="color: #008000;">&#41;</span>
<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
<span style="color: #008080; font-style: italic;">// Build the field declaration</span>
FieldDeclarationSyntax newField <span style="color: #008000;">=</span> Syntax<span style="color: #008000;">.</span><span style="color: #0000FF;">FieldDeclaration</span><span style="color: #008000;">&#40;</span>
  modifiers<span style="color: #008000;">:</span> Syntax<span style="color: #008000;">.</span><span style="color: #0000FF;">TokenList</span><span style="color: #008000;">&#40;</span>Syntax<span style="color: #008000;">.</span><span style="color: #0000FF;">Token</span><span style="color: #008000;">&#40;</span>SyntaxKind<span style="color: #008000;">.</span><span style="color: #0000FF;">PublicKeyword</span><span style="color: #008000;">&#41;</span>, Syntax<span style="color: #008000;">.</span><span style="color: #0000FF;">Token</span><span style="color: #008000;">&#40;</span>SyntaxKind<span style="color: #008000;">.</span><span style="color: #0000FF;">StaticKeyword</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span>,
  declaration<span style="color: #008000;">:</span> Syntax<span style="color: #008000;">.</span><span style="color: #0000FF;">VariableDeclaration</span><span style="color: #008000;">&#40;</span>
    type<span style="color: #008000;">:</span> dpType,
    variables<span style="color: #008000;">:</span> Syntax<span style="color: #008000;">.</span><span style="color: #0000FF;">SeparatedList</span><span style="color: #008000;">&#40;</span>declarator<span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
<span style="color: #008080; font-style: italic;">// Store it to add to the class later</span>
_fields<span style="color: #008000;">.</span><span style="color: #0000FF;">Add</span><span style="color: #008000;">&#40;</span>newField<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span></pre></div></div>

<p>Don&#8217;t panic at this.  I know it&#8217;s long by bloggy standards (about 50 lines), and that it appears very dense.  But a lot of the density is down to the named arguments and the deep nesting of Roslyn trees, so if you walk through it methodically, it&#8217;s not that difficult, just lengthy.  Here&#8217;s what happens:</p>
<ul>
<li>We build up ExpressionSyntax objects representing the arguments to the DependencyProperty.Register call: the property name literal string, the typeof() expressions for the property type and the owner type, and optionally a &#8220;new FrameworkPropertyMetadata&#8221; (ObjectCreationExpression) with a reference to the callback method name</li>
<li>We build a call to the DependencyProperty.Register method, passing the arguments we built in the last step.  Roslyn asks us to wrap the arguments in an ArgumentList, which incurs some tedious messing around with separators.  Roslyn may be forgiving on the read side, but it&#8217;s pedantic as all hell on the write side!</li>
<li>We build the field declaration itself.  This comes in two bits.  First we create a VariableDeclaratorSyntax representing the field variable and the initialiser for that variable.  The initialiser is just the DependencyProperty.Register call we built in the previous step.  Then we wrap this up with a &#8220;public&#8221; visibility modifier and a data type into a FieldDeclarationSyntax.</li>
<li>Job done &#8212; stick the FieldDeclarationSyntax in the collection for later processing.</li>
</ul>
<p>After this epic, the other two bits are relatively concise.  Here&#8217;s the code that generates the CLR wrapper property:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #008080; font-style: italic;">// Desired output:</span>
<span style="color: #008080; font-style: italic;">// public PropType Xxx</span>
<span style="color: #008080; font-style: italic;">// {</span>
<span style="color: #008080; font-style: italic;">//   get { return (PropType)GetValue(XxxProperty); }</span>
<span style="color: #008080; font-style: italic;">//   set { SetValue(XxxPropety, value); }</span>
<span style="color: #008080; font-style: italic;">// }</span>
ExpressionSyntax getval <span style="color: #008000;">=</span> Syntax<span style="color: #008000;">.</span><span style="color: #0000FF;">ParseExpression</span><span style="color: #008000;">&#40;</span><span style="color: #666666;">&quot;GetValue(&quot;</span> <span style="color: #008000;">+</span> fieldName <span style="color: #008000;">+</span> <span style="color: #666666;">&quot;)&quot;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
ExpressionSyntax casty <span style="color: #008000;">=</span> Syntax<span style="color: #008000;">.</span><span style="color: #0000FF;">CastExpression</span><span style="color: #008000;">&#40;</span>type<span style="color: #008000;">:</span> node<span style="color: #008000;">.</span><span style="color: #0000FF;">Type</span>, expression<span style="color: #008000;">:</span> getval<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
StatementSyntax getter <span style="color: #008000;">=</span> Syntax<span style="color: #008000;">.</span><span style="color: #0000FF;">ReturnStatement</span><span style="color: #008000;">&#40;</span>expressionOpt<span style="color: #008000;">:</span> casty<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
StatementSyntax setter <span style="color: #008000;">=</span> Syntax<span style="color: #008000;">.</span><span style="color: #0000FF;">ParseStatement</span><span style="color: #008000;">&#40;</span><span style="color: #666666;">&quot;SetValue(&quot;</span> <span style="color: #008000;">+</span> fieldName <span style="color: #008000;">+</span> <span style="color: #666666;">&quot;);&quot;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
PropertyDeclarationSyntax newProperty <span style="color: #008000;">=</span> Syntax<span style="color: #008000;">.</span><span style="color: #0000FF;">PropertyDeclaration</span><span style="color: #008000;">&#40;</span>
  modifiers<span style="color: #008000;">:</span> Syntax<span style="color: #008000;">.</span><span style="color: #0000FF;">TokenList</span><span style="color: #008000;">&#40;</span>Syntax<span style="color: #008000;">.</span><span style="color: #0000FF;">Token</span><span style="color: #008000;">&#40;</span>SyntaxKind<span style="color: #008000;">.</span><span style="color: #0000FF;">PublicKeyword</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span>,
  type<span style="color: #008000;">:</span> node<span style="color: #008000;">.</span><span style="color: #0000FF;">Type</span>,
  identifier<span style="color: #008000;">:</span> node<span style="color: #008000;">.</span><span style="color: #0000FF;">Identifier</span>,
  accessorList<span style="color: #008000;">:</span> Syntax<span style="color: #008000;">.</span><span style="color: #0000FF;">AccessorList</span><span style="color: #008000;">&#40;</span>
    accessors<span style="color: #008000;">:</span> Syntax<span style="color: #008000;">.</span><span style="color: #0000FF;">List</span><span style="color: #008000;">&#40;</span>
      Syntax<span style="color: #008000;">.</span><span style="color: #0000FF;">AccessorDeclaration</span><span style="color: #008000;">&#40;</span>
        kind<span style="color: #008000;">:</span> SyntaxKind<span style="color: #008000;">.</span><span style="color: #0000FF;">GetAccessorDeclaration</span>,
        bodyOpt<span style="color: #008000;">:</span> Syntax<span style="color: #008000;">.</span><span style="color: #0000FF;">Block</span><span style="color: #008000;">&#40;</span>
          statements<span style="color: #008000;">:</span> Syntax<span style="color: #008000;">.</span><span style="color: #0000FF;">List</span><span style="color: #008000;">&#40;</span>
            getter
          <span style="color: #008000;">&#41;</span>
        <span style="color: #008000;">&#41;</span>
      <span style="color: #008000;">&#41;</span>,
      Syntax<span style="color: #008000;">.</span><span style="color: #0000FF;">AccessorDeclaration</span><span style="color: #008000;">&#40;</span>
        kind<span style="color: #008000;">:</span> SyntaxKind<span style="color: #008000;">.</span><span style="color: #0000FF;">SetAccessorDeclaration</span>,
        bodyOpt<span style="color: #008000;">:</span> Syntax<span style="color: #008000;">.</span><span style="color: #0000FF;">Block</span><span style="color: #008000;">&#40;</span>
          statements<span style="color: #008000;">:</span> Syntax<span style="color: #008000;">.</span><span style="color: #0000FF;">List</span><span style="color: #008000;">&#40;</span>
            setter
          <span style="color: #008000;">&#41;</span>
        <span style="color: #008000;">&#41;</span>
      <span style="color: #008000;">&#41;</span>
    <span style="color: #008000;">&#41;</span>
  <span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span></pre></div></div>

<p>Again, there&#8217;s lots of fiddly wrapper classes and lots of nesting, but the core concepts aren&#8217;t too hard.  We build a GetValue call, apply a cast to it, and stick a return statement on it, and that&#8217;s our getter body.  For our setter body, we build a SetValue call.  Notice that Roslyn lets us build our code as C# source using string operations via the Parse methods, so we don&#8217;t have to do everything with trees.  Then we bundle the getter and setter bodies up into accessors and stuff them into a property declaration.</p>
<p>Finally comes the on-changed callback.  This is relatively easy because all we need to do is create a method, and transplant whatever the user wrote inside the change { } pseudo-accessor into that method.</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #008080; font-style: italic;">// Desired output:</span>
<span style="color: #008080; font-style: italic;">// private static void OnXxxChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)</span>
<span style="color: #008080; font-style: italic;">// {</span>
<span style="color: #008080; font-style: italic;">//   /* body */</span>
<span style="color: #008080; font-style: italic;">// }</span>
&nbsp;
<span style="color: #008080; font-style: italic;">// Reminder</span>
var changeCallback <span style="color: #008000;">=</span> node<span style="color: #008000;">.</span><span style="color: #0000FF;">AccessorList</span><span style="color: #008000;">.</span><span style="color: #0000FF;">Accessors</span><span style="color: #008000;">.</span><span style="color: #0000FF;">FirstOrDefault</span><span style="color: #008000;">&#40;</span>a <span style="color: #008000;">=&gt;</span> a<span style="color: #008000;">.</span><span style="color: #0000FF;">Kind</span> <span style="color: #008000;">==</span> SyntaxKind<span style="color: #008000;">.</span><span style="color: #0000FF;">UnknownAccessorDeclaration</span> <span style="color: #008000;">&amp;&amp;</span> a<span style="color: #008000;">.</span><span style="color: #0000FF;">Keyword</span><span style="color: #008000;">.</span><span style="color: #0000FF;">ValueText</span> <span style="color: #008000;">==</span> <span style="color: #666666;">&quot;change&quot;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
<span style="color: #6666cc; font-weight: bold;">bool</span> hasChangeCallback <span style="color: #008000;">=</span> changeCallback <span style="color: #008000;">!=</span> <span style="color: #0600FF; font-weight: bold;">null</span><span style="color: #008000;">;</span>
&nbsp;
<span style="color: #0600FF; font-weight: bold;">if</span> <span style="color: #008000;">&#40;</span>hasChangeCallback<span style="color: #008000;">&#41;</span>
<span style="color: #008000;">&#123;</span>
  <span style="color: #008080; font-style: italic;">// Specify the method parameters (always d and e)</span>
  List<span style="color: #008000;">&lt;</span>ParameterSyntax<span style="color: #008000;">&gt;</span> parameterList <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> List<span style="color: #008000;">&lt;</span>ParameterSyntax<span style="color: #008000;">&gt;</span>
  <span style="color: #008000;">&#123;</span>
    Syntax<span style="color: #008000;">.</span><span style="color: #0000FF;">Parameter</span><span style="color: #008000;">&#40;</span>identifier<span style="color: #008000;">:</span> Syntax<span style="color: #008000;">.</span><span style="color: #0000FF;">Identifier</span><span style="color: #008000;">&#40;</span><span style="color: #666666;">&quot;d&quot;</span><span style="color: #008000;">&#41;</span>, typeOpt<span style="color: #008000;">:</span> Syntax<span style="color: #008000;">.</span><span style="color: #0000FF;">ParseTypeName</span><span style="color: #008000;">&#40;</span><span style="color: #666666;">&quot;System.Windows.DependencyObject&quot;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span>,
    Syntax<span style="color: #008000;">.</span><span style="color: #0000FF;">Parameter</span><span style="color: #008000;">&#40;</span>identifier<span style="color: #008000;">:</span> Syntax<span style="color: #008000;">.</span><span style="color: #0000FF;">Identifier</span><span style="color: #008000;">&#40;</span><span style="color: #666666;">&quot;e&quot;</span><span style="color: #008000;">&#41;</span>, typeOpt<span style="color: #008000;">:</span> Syntax<span style="color: #008000;">.</span><span style="color: #0000FF;">ParseTypeName</span><span style="color: #008000;">&#40;</span><span style="color: #666666;">&quot;System.Windows.DependencyPropertyChangedEventArgs&quot;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span>,
  <span style="color: #008000;">&#125;</span><span style="color: #008000;">;</span>
  var paramSeparators <span style="color: #008000;">=</span> Enumerable<span style="color: #008000;">.</span><span style="color: #0000FF;">Repeat</span><span style="color: #008000;">&#40;</span>Syntax<span style="color: #008000;">.</span><span style="color: #0000FF;">Token</span><span style="color: #008000;">&#40;</span>SyntaxKind<span style="color: #008000;">.</span><span style="color: #0000FF;">CommaToken</span><span style="color: #008000;">&#41;</span>, parameterList<span style="color: #008000;">.</span><span style="color: #0000FF;">Count</span> <span style="color: #008000;">-</span> <span style="color: #FF0000;">1</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">.</span><span style="color: #0000FF;">ToList</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>  <span style="color: #008080; font-style: italic;">// must be an easier way</span>
  ParameterListSyntax parameters <span style="color: #008000;">=</span> Syntax<span style="color: #008000;">.</span><span style="color: #0000FF;">ParameterList</span><span style="color: #008000;">&#40;</span>
    parameters<span style="color: #008000;">:</span> Syntax<span style="color: #008000;">.</span><span style="color: #0000FF;">SeparatedList</span><span style="color: #008000;">&#40;</span>parameterList, paramSeparators<span style="color: #008000;">&#41;</span>
  <span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
  <span style="color: #008080; font-style: italic;">// Build the method</span>
  MethodDeclarationSyntax changeMethod <span style="color: #008000;">=</span> Syntax<span style="color: #008000;">.</span><span style="color: #0000FF;">MethodDeclaration</span><span style="color: #008000;">&#40;</span>
    modifiers<span style="color: #008000;">:</span> Syntax<span style="color: #008000;">.</span><span style="color: #0000FF;">TokenList</span><span style="color: #008000;">&#40;</span>Syntax<span style="color: #008000;">.</span><span style="color: #0000FF;">Token</span><span style="color: #008000;">&#40;</span>SyntaxKind<span style="color: #008000;">.</span><span style="color: #0000FF;">PrivateKeyword</span><span style="color: #008000;">&#41;</span>, Syntax<span style="color: #008000;">.</span><span style="color: #0000FF;">Token</span><span style="color: #008000;">&#40;</span>SyntaxKind<span style="color: #008000;">.</span><span style="color: #0000FF;">StaticKeyword</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span>,
    identifier<span style="color: #008000;">:</span> Syntax<span style="color: #008000;">.</span><span style="color: #0000FF;">Identifier</span><span style="color: #008000;">&#40;</span><span style="color: #666666;">&quot;On&quot;</span> <span style="color: #008000;">+</span> propName <span style="color: #008000;">+</span> <span style="color: #666666;">&quot;Changed&quot;</span><span style="color: #008000;">&#41;</span>,
    returnType<span style="color: #008000;">:</span> Syntax<span style="color: #008000;">.</span><span style="color: #0000FF;">PredefinedType</span><span style="color: #008000;">&#40;</span>Syntax<span style="color: #008000;">.</span><span style="color: #0000FF;">Token</span><span style="color: #008000;">&#40;</span>SyntaxKind<span style="color: #008000;">.</span><span style="color: #0000FF;">VoidKeyword</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span>,
    parameterList<span style="color: #008000;">:</span> parameters,
    bodyOpt<span style="color: #008000;">:</span> changeCallback<span style="color: #008000;">.</span><span style="color: #0000FF;">BodyOpt</span>
  <span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
  _methods<span style="color: #008000;">.</span><span style="color: #0000FF;">Add</span><span style="color: #008000;">&#40;</span>changeMethod<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
<span style="color: #008000;">&#125;</span></pre></div></div>

<p>A lot of the noise here comes from building up the parameter list; once we get into building the method, you can almost read off what you need to do from the desired output syntax.  public static, those are the modifiers; OnXxxChanged, that&#8217;s the identifier; void, that&#8217;s the return type; and the method body, well hey, Roslyn has already parsed that into body of the change pseudo-accessor, so we just pass a reference to that!</p>
<p>Taken together, this probably looks intimidating.  Brave heart!  It&#8217;s not difficult, just long and fiddly.  Everything we&#8217;re doing here maps very exactly to the C# syntax in the &#8220;desired output&#8221; sections.  If you feel yourself getting lost, map it back to those.</p>
<p>One final thing: our property rewriter needs to return the rewritten property.</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF; font-weight: bold;">return</span> newProperty<span style="color: #008000;">;</span></pre></div></div>

<p>Back on familiar ground at last!</p>
<p><strong>Rewriting the class</strong></p>
<p>Okay, so we rewrote the property by returning it from VisitPropertyDeclaration, but how are we going to get those fields and methods we&#8217;ve been collecting emitted into the generated code?  Well, fields and methods live at class level, so for this we need to rewrite the class.  Fortunately, we only need to do a very simple rewrite, just jamming in a few extra members.  Here&#8217;s the code:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF; font-weight: bold;">protected</span> <span style="color: #0600FF; font-weight: bold;">override</span> SyntaxNode VisitClassDeclaration<span style="color: #008000;">&#40;</span>ClassDeclarationSyntax node<span style="color: #008000;">&#41;</span>
<span style="color: #008000;">&#123;</span>
  var newTypeDeclaration <span style="color: #008000;">=</span> <span style="color: #008000;">&#40;</span>TypeDeclarationSyntax<span style="color: #008000;">&#41;</span><span style="color: #0600FF; font-weight: bold;">base</span><span style="color: #008000;">.</span><span style="color: #0000FF;">VisitClassDeclaration</span><span style="color: #008000;">&#40;</span>node<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
  <span style="color: #0600FF; font-weight: bold;">if</span> <span style="color: #008000;">&#40;</span>_fields<span style="color: #008000;">.</span><span style="color: #0000FF;">Count</span> <span style="color: #008000;">&gt;</span> <span style="color: #FF0000;">0</span> <span style="color: #008000;">||</span> _methods<span style="color: #008000;">.</span><span style="color: #0000FF;">Count</span> <span style="color: #008000;">&gt;</span> <span style="color: #FF0000;">0</span><span style="color: #008000;">&#41;</span>
  <span style="color: #008000;">&#123;</span>
    var members <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> List<span style="color: #008000;">&lt;</span>MemberDeclarationSyntax<span style="color: #008000;">&gt;</span><span style="color: #008000;">&#40;</span>newTypeDeclaration<span style="color: #008000;">.</span><span style="color: #0000FF;">Members</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
    members<span style="color: #008000;">.</span><span style="color: #0000FF;">InsertRange</span><span style="color: #008000;">&#40;</span><span style="color: #FF0000;">0</span>, _methods<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
    members<span style="color: #008000;">.</span><span style="color: #0000FF;">InsertRange</span><span style="color: #008000;">&#40;</span><span style="color: #FF0000;">0</span>, _fields<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
    <span style="color: #0600FF; font-weight: bold;">return</span> <span style="color: #008000;">&#40;</span><span style="color: #008000;">&#40;</span>ClassDeclarationSyntax<span style="color: #008000;">&#41;</span>newTypeDeclaration<span style="color: #008000;">&#41;</span><span style="color: #008000;">.</span><span style="color: #0000FF;">Update</span><span style="color: #008000;">&#40;</span>
        newTypeDeclaration<span style="color: #008000;">.</span><span style="color: #0000FF;">Attributes</span>,
        newTypeDeclaration<span style="color: #008000;">.</span><span style="color: #0000FF;">Modifiers</span>,
        newTypeDeclaration<span style="color: #008000;">.</span><span style="color: #0000FF;">Keyword</span>,
        newTypeDeclaration<span style="color: #008000;">.</span><span style="color: #0000FF;">Identifier</span>,
        newTypeDeclaration<span style="color: #008000;">.</span><span style="color: #0000FF;">TypeParameterListOpt</span>,
        newTypeDeclaration<span style="color: #008000;">.</span><span style="color: #0000FF;">BaseListOpt</span>,
        newTypeDeclaration<span style="color: #008000;">.</span><span style="color: #0000FF;">ConstraintClauses</span>,
        newTypeDeclaration<span style="color: #008000;">.</span><span style="color: #0000FF;">OpenBraceToken</span>,
        Syntax<span style="color: #008000;">.</span><span style="color: #0000FF;">List</span><span style="color: #008000;">&#40;</span>members<span style="color: #008000;">.</span><span style="color: #0000FF;">AsEnumerable</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span>,
        newTypeDeclaration<span style="color: #008000;">.</span><span style="color: #0000FF;">CloseBraceToken</span>,
        newTypeDeclaration<span style="color: #008000;">.</span><span style="color: #0000FF;">SemicolonTokenOpt</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
  <span style="color: #008000;">&#125;</span>
&nbsp;
  <span style="color: #0600FF; font-weight: bold;">return</span> newTypeDeclaration<span style="color: #008000;">;</span>
<span style="color: #008000;">&#125;</span></pre></div></div>

<p>What&#8217;s the deal?  The first thing we have to do is call the base class implementation, which goes off to all the elements within the class and gives them the chance to rewrite themselves.  This is essential, because otherwise our property rewriter would never get called.  And it&#8217;s also essential to do it first, so that the fields and methods that are by-products of the property rewriting are ready when we need them.</p>
<p>Then we take a copy of the existing members of the class, add in the fields and methods that came out of the property rewriting process, and use the Update helper method to create a copy of the class with the extended member collection.  As before, it looks scarier than it is &#8212; most of the Update call is boilerplate copying, there&#8217;s just quite a bit of it!</p>
<p><strong>Let&#8217;s rewrite</strong></p>
<p>Finally, we need to call the rewriter to transform our illegal pseudo-C# into legal C#.</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;">SyntaxTree tree <span style="color: #008000;">=</span> SyntaxTree<span style="color: #008000;">.</span><span style="color: #0000FF;">ParseCompilationUnit</span><span style="color: #008000;">&#40;</span>sourceCode<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
var root <span style="color: #008000;">=</span> <span style="color: #008000;">&#40;</span>CompilationUnitSyntax<span style="color: #008000;">&#41;</span><span style="color: #008000;">&#40;</span>tree<span style="color: #008000;">.</span><span style="color: #0000FF;">Root</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
var rewriter <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> DPRewriter<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
var newRoot <span style="color: #008000;">=</span> <span style="color: #008000;">&#40;</span>CompilationUnitSyntax<span style="color: #008000;">&#41;</span><span style="color: #008000;">&#40;</span>rewriter<span style="color: #008000;">.</span><span style="color: #0000FF;">Visit</span><span style="color: #008000;">&#40;</span>root<span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
newRoot <span style="color: #008000;">=</span> newRoot<span style="color: #008000;">.</span><span style="color: #0000FF;">Format</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
Console<span style="color: #008000;">.</span><span style="color: #0000FF;">WriteLine</span><span style="color: #008000;">&#40;</span>newRoot<span style="color: #008000;">.</span><span style="color: #0000FF;">ToString</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span></pre></div></div>

<p>Just new up a rewriter, pass it the node you want to rewrite &#8212; in our case we&#8217;ll rewrite the whole source by passing the root &#8212; and call ToString() on the result to get the transformed code.  Easy!</p>
<p>Here&#8217;s the results (slightly reformatted for readability):</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #008080; font-style: italic;">// Input:</span>
<span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #6666cc; font-weight: bold;">class</span> Widget <span style="color: #008000;">:</span> DependencyObject
<span style="color: #008000;">&#123;</span>
  <span style="color: #008000;">&#91;</span>dependency<span style="color: #008000;">&#93;</span> <span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #6666cc; font-weight: bold;">int</span> Widgetude
  <span style="color: #008000;">&#123;</span>
    change <span style="color: #008000;">&#123;</span> Console<span style="color: #008000;">.</span><span style="color: #0000FF;">WriteLine</span><span style="color: #008000;">&#40;</span><span style="color: #666666;">&quot;DP change: &quot;</span> <span style="color: #008000;">+</span> e <span style="color: #008000;">+</span> <span style="color: #666666;">&quot; on &quot;</span> <span style="color: #008000;">+</span> d<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span> <span style="color: #008000;">&#125;</span>
  <span style="color: #008000;">&#125;</span>
<span style="color: #008000;">&#125;</span>
&nbsp;
<span style="color: #008080; font-style: italic;">// Output:</span>
<span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #6666cc; font-weight: bold;">class</span> Widget <span style="color: #008000;">:</span> DependencyObject
<span style="color: #008000;">&#123;</span>
  <span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #0600FF; font-weight: bold;">static</span> <span style="color: #000000;">System</span><span style="color: #008000;">.</span><span style="color: #0000FF;">Windows</span><span style="color: #008000;">.</span><span style="color: #0000FF;">DependencyProperty</span> WidgetudeProperty <span style="color: #008000;">=</span>
    <span style="color: #000000;">System</span><span style="color: #008000;">.</span><span style="color: #0000FF;">Windows</span><span style="color: #008000;">.</span><span style="color: #0000FF;">DependencyProperty</span><span style="color: #008000;">.</span><span style="color: #0000FF;">Register</span><span style="color: #008000;">&#40;</span><span style="color: #666666;">&quot;Widgetude&quot;</span>,
      <span style="color: #008000;">typeof</span> <span style="color: #008000;">&#40;</span><span style="color: #6666cc; font-weight: bold;">int</span><span style="color: #008000;">&#41;</span>, <span style="color: #008000;">typeof</span> <span style="color: #008000;">&#40;</span>Widget<span style="color: #008000;">&#41;</span>,
        <span style="color: #008000;">new</span> <span style="color: #000000;">System</span><span style="color: #008000;">.</span><span style="color: #0000FF;">Windows</span><span style="color: #008000;">.</span><span style="color: #0000FF;">FrameworkPropertyMetadata</span><span style="color: #008000;">&#40;</span>OnWidgetudeChanged<span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
  <span style="color: #0600FF; font-weight: bold;">private</span> <span style="color: #0600FF; font-weight: bold;">static</span> <span style="color: #6666cc; font-weight: bold;">void</span> OnWidgetudeChanged<span style="color: #008000;">&#40;</span><span style="color: #000000;">System</span><span style="color: #008000;">.</span><span style="color: #0000FF;">Windows</span><span style="color: #008000;">.</span><span style="color: #0000FF;">DependencyObject</span> d, <span style="color: #000000;">System</span><span style="color: #008000;">.</span><span style="color: #0000FF;">Windows</span><span style="color: #008000;">.</span><span style="color: #0000FF;">DependencyPropertyChangedEventArgs</span> e<span style="color: #008000;">&#41;</span>
  <span style="color: #008000;">&#123;</span>
    Console<span style="color: #008000;">.</span><span style="color: #0000FF;">WriteLine</span><span style="color: #008000;">&#40;</span><span style="color: #666666;">&quot;DP change: &quot;</span> <span style="color: #008000;">+</span> e <span style="color: #008000;">+</span> <span style="color: #666666;">&quot; on &quot;</span> <span style="color: #008000;">+</span> d<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
  <span style="color: #008000;">&#125;</span>
&nbsp;
  <span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #6666cc; font-weight: bold;">int</span> Widgetude
  <span style="color: #008000;">&#123;</span>
    get <span style="color: #008000;">&#123;</span> <span style="color: #0600FF; font-weight: bold;">return</span> <span style="color: #008000;">&#40;</span><span style="color: #6666cc; font-weight: bold;">int</span><span style="color: #008000;">&#41;</span>GetValue<span style="color: #008000;">&#40;</span>WidgetudeProperty<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span> <span style="color: #008000;">&#125;</span>
    set <span style="color: #008000;">&#123;</span> SetValue<span style="color: #008000;">&#40;</span>WidgetudeProperty<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span> <span style="color: #008000;">&#125;</span>
  <span style="color: #008000;">&#125;</span>
<span style="color: #008000;">&#125;</span></pre></div></div>

<p>Sweet!</p>
<p><strong>Take it for a spin</strong></p>
<p>The possibilities for Roslyn make my head spin.  It&#8217;s going to lower the barrier to entry for building code analysis and refactoring tools, which I reckon is going to lead to a huge flowering of new and cool products in this sector.  But it also opens up some exciting new possibilities for code generation &#8212; from the legitimate, like aspect weaving on source code, to the slightly naughty, like syntax extensions.</p>
<p>You can <a href="http://www.microsoft.com/download/en/details.aspx?id=27746">get the Roslyn preview for VS2010 SP1 here</a>.  It has a bunch of great samples and walkthroughs which are well worth checking out.  My code is about a million times uglier, and is I&#8217;m sure riddled with unnecessary kludges and workarounds, but if you want to have a play with it, <a href='http://www.mindscapehq.com/blog/wp-content/uploads/2011/10/RoslynTest.zip'>here it is</a>.</p>
<p>Enjoy, and go crazy!</p>
<p>Enjoyed this post? Please upvote on <a href="http://news.ycombinator.com/item?id=3137916">Hacker News</a> or <a href="http://www.reddit.com/r/programming/comments/ljenx/in_bed_with_roslyn_extending_c_syntax/">Reddit</a> &#8212; thanks!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.mindscapehq.com/blog/index.php/2011/10/20/in-bed-with-roslyn/feed/</wfw:commentRss>
		<slash:comments>18</slash:comments>
		</item>
		<item>
		<title>NHibernate Designer 2 is here!</title>
		<link>http://www.mindscapehq.com/blog/index.php/2011/10/19/nhibernate-designer-2-is-here/</link>
		<comments>http://www.mindscapehq.com/blog/index.php/2011/10/19/nhibernate-designer-2-is-here/#comments</comments>
		<pubDate>Thu, 20 Oct 2011 04:20:49 +0000</pubDate>
		<dc:creator>John-Daniel Trask</dc:creator>
				<category><![CDATA[NHibernate Designer]]></category>
		<category><![CDATA[Visual Studio]]></category>
		<category><![CDATA[Designer]]></category>
		<category><![CDATA[NHibernate]]></category>
		<category><![CDATA[Visual]]></category>

		<guid isPermaLink="false">http://www.mindscapehq.com/blog/?p=3859</guid>
		<description><![CDATA[I&#8217;m very pleased to announce the immediate availability of the NHibernate Designer 2.0! This release represents a big set of improvements for existing users and a great experience for new users. Key new features: File per class generation option added Setup wizard for creating a new model Generate mappings with either inline XML or Fluent [...]]]></description>
				<content:encoded><![CDATA[<p><img src="http://www.mindscapehq.com/blog/wp-content/uploads/2011/01/NHibernateDesignerBlog.jpg" alt="NHibernate Visual Designer for Visual Studio" title="NHibernate Visual Designer for Visual Studio" width="718" height="180" class="alignnone size-full wp-image-2632"></p>
<p>I&#8217;m very pleased to announce the immediate availability of the <a href="http://www.mindscapehq.com/products/nhdesigner">NHibernate Designer</a> 2.0! This release represents a big set of improvements for existing users and a great experience for new users.</p>
<p><strong>Key new features:</strong></p>
<ul>
<li>File per class generation option added</li>
<li>Setup wizard for creating a new model</li>
<li>Generate mappings with either inline XML or Fluent NHibernate</li>
<li>Configuration guidance wizard to integrate quicker with your project</li>
<li>Automatically add references to required NHibernate assemblies</li>
<li>Fully integrated schema migrations framework</li>
<li>View entity database tables directly within Visual Studio</li>
<li>Set up validation in the designer for NHibernate.Validator</li>
<li>Per project code generation templates</li>
</ul>
<p>Along with all these great additions we&#8217;ve added a lot of polish to really boost the easy of use &#8212; we think you&#8217;ll be very pleased with the results. <a href="http://www.mindscapehq.com/products/nhdesigner/features">Read more about the NHibernate Designer 2 features here</a>.</p>
<p><strong>How to get it today</strong></p>
<p>If you already have the NHibernate Designer installed in Visual Studio 2010, simply open the Extension Manager (Tools -> Extension Manager) and check for updates. The latest build will be there, install it and you&#8217;re away.</p>
<p>If you have not yet tried the NHibernate Designer then <a href="/products/nhdesigner/download">click here to install the latest version</a>.</p>
<p><strong>One more thing&#8230;</strong></p>
<p>We&#8217;ve dropped the price for the launch of version 2.0. Down to a tight $99 USD per developer! Given the hours of time you&#8217;ll save it&#8217;s the perfect time to invest in your toolset! </p>
<p><a href="/products/nhdesigner/download" class="imgbutton green"><img src="/Content/images/chrome/spacer.gif" alt="Free Download" class="bigdown"> Download the free edition</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.mindscapehq.com/blog/index.php/2011/10/19/nhibernate-designer-2-is-here/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Web Workbench 2.0 &#8211; Faster, Minification and Pro</title>
		<link>http://www.mindscapehq.com/blog/index.php/2011/10/10/web-workbench-2-0-faster-minification-and-pro/</link>
		<comments>http://www.mindscapehq.com/blog/index.php/2011/10/10/web-workbench-2-0-faster-minification-and-pro/#comments</comments>
		<pubDate>Tue, 11 Oct 2011 02:12:21 +0000</pubDate>
		<dc:creator>John-Daniel Trask</dc:creator>
				<category><![CDATA[MegaPack]]></category>
		<category><![CDATA[News]]></category>
		<category><![CDATA[Visual Studio]]></category>
		<category><![CDATA[Web Workbench]]></category>
		<category><![CDATA[Less]]></category>
		<category><![CDATA[Pro]]></category>
		<category><![CDATA[Sass]]></category>

		<guid isPermaLink="false">http://www.mindscapehq.com/blog/?p=3830</guid>
		<description><![CDATA[We&#8217;ve been blown away by the interest in the Mindscape Web Workbench. It seems .NET web developers were hungry for Sass, Less and CoffeeScript inside Visual Studio as we&#8217;ve now passed 14,000 installs! We&#8217;ve had a boat load of feedback and we&#8217;ve been incorporating the smaller bug fixes into our nightly builds while in the [...]]]></description>
				<content:encoded><![CDATA[<p><img src="http://www.mindscapehq.com/blog/wp-content/uploads/2011/07/Workbench_blog_718x200.jpg" alt="" title="Mindscape Web Workbench: Sass, Less and CoffeeScript for Visual Studio" width="718" height="200" class="alignleft size-full wp-image-3524"></p>
<p>We&#8217;ve been blown away by the interest in the <a href="http://www.mindscapehq.com/products/web-workbench">Mindscape Web Workbench</a>. It seems .NET web developers were hungry for Sass, Less and CoffeeScript inside Visual Studio as we&#8217;ve now passed 14,000 installs! We&#8217;ve had a boat load of feedback and we&#8217;ve been incorporating the smaller bug fixes into our nightly builds while in the background working on a grunty new version for you all!</p>
<p><strong>Going Pro</strong></p>
<p>We originally released this tool to scratch an itch. We wanted to play with some of the cool new tech that was being used in the open source camps and so the idea of the Web Workbench was born. With the massive uptake in interest of the product though we&#8217;re thinking it would be fantastic to spend even more time investing in making it the best Visual Studio Extension possible. To be able to achieve that we need to fund the development while still keeping this as inexpensive as possible and also keeping what is currently there free.</p>
<p>Here&#8217;s what we have done:</p>
<ul>
<li>There will always be a free version and everything in version 1 continues to be free.</li>
<li>None of the existing features will require you to have a Pro version and in fact they will just continue to run better than v1!</li>
<li>Some new features will be for Pro users only by way of thanks for supporting the new developments.</li>
<li>The price of the Pro edition should be low enough that it&#8217;s a no brainer to support future development.</li>
</ul>
<p>That last point is the key one I want to make. We&#8217;ve been swamped with great ideas, feature requests and things we could improve. By purchasing a Pro license you&#8217;re helping support the future development of the tool and as a sign of appreciation we want those that help to get some nice extra bits and pieces.</p>
<p>So what is new in Version 2?</p>
<p><strong>V8 Engine Enabled &#8211; Free Feature</strong><img src="http://www.mindscapehq.com/blog/wp-content/uploads/2011/10/V8_JavaScript_engine_logo.png" alt="Google V8 JavaScript Engine Logo" title="Google V8 JavaScript Engine Logo" width="68" height="55" class="alignnone size-full wp-image-3840" style="float:right; margin-left:10px; margin-bottom:10px;" /><br />
Feedback on the initial version was great&#8230; until folks had BIG files. Like 1000+ line CoffeeScript files. Unfortunately the JavaScript engine we used, while very cool, wasn&#8217;t quite fast enough to keep up with such large files. We have spent the last few weeks baking in Google&#8217;s V8 JavaScript engine that ships with Google Chrome to super charge the speed when working with larger files. Early feedback on a test release was very promising:</p>
<p><em>&#8220;I am using win7 x64 &#8211; I just applied the update and I am seeing a great improvement! Woohoo!&#8221; &#8211; Dan</em></p>
<p><em>&#8220;10 words: &#8220;Awesome job&#8221;!&#8221;  &#8211; Bagosm (aka Binary Man)</em></p>
<p>This improvement is included for everyone, including the free users.</p>
<p><strong>LESS compilation &#8211; Pro Feature</strong><br />
Initially we did not compile LESS files into .css files as we assumed folks used the JavaScript parser. Feedback was that it would be really cool if the Web Workbench would just create the CSS files on save in the same way that we do with Sass. So this is now included.</p>
<p><strong>CSS &#038; JavaScript Minification &#8211; Pro Feature</strong><br />
Editing the files is great, but having another step to do minification was proving to be a hassle to users. In the pro edition we now include the option to minify both the CSS output and the JavaScript output, saving you even more time!</p>
<p>Thanks again for all your feedback to date and we hope this release makes the Web Workbench even more compelling for you. Thanks to everyone who helps support the ongoing development effort by upgrading to the Pro edition &#8212; we have some really great ideas for the future and you&#8217;re helping it become a reality.</p>
<p>You can obtain version 2.0 by doing an update from the Extension Manager in VS 2010, or by <a href="http://visualstudiogallery.msdn.microsoft.com/2b96d16a-c986-4501-8f97-8008f9db141a">clicking here to download it free</a>. If you wish to support further development the purchase options are available within the Web Workbench itself.  And if you don&#8217;t, well, all the features you love are still there and we hope you enjoy the free V2 enhancements as well!</p>
<div class="boximage leftfloated" style="margin-left:100px;">
<div class="boximageTop">
<span>&nbsp;</span></div>
<div class="boximageContent"><a href="http://www.mindscapehq.com/blog/wp-content/uploads/2011/10/NinjaCoder.jpg"><img src="http://www.mindscapehq.com/blog/wp-content/uploads/2011/10/NinjaCoder.jpg" alt="Used Mindscape Web Workbench... Now the most ninja coder in the company" title="Used Mindscape Web Workbench... Now the most ninja coder in the company" width="398" height="399" /></a></div>
<div class="boximageBottom"><span>&nbsp;</span></div>
</p>
</div>
<div class="clear"></div>
]]></content:encoded>
			<wfw:commentRss>http://www.mindscapehq.com/blog/index.php/2011/10/10/web-workbench-2-0-faster-minification-and-pro/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Buy Visual Studio and MSDN online in New Zealand</title>
		<link>http://www.mindscapehq.com/blog/index.php/2009/08/23/buy-visual-studio-msdn-online/</link>
		<comments>http://www.mindscapehq.com/blog/index.php/2009/08/23/buy-visual-studio-msdn-online/#comments</comments>
		<pubDate>Mon, 24 Aug 2009 00:00:24 +0000</pubDate>
		<dc:creator>John-Daniel Trask</dc:creator>
				<category><![CDATA[News]]></category>
		<category><![CDATA[Visual Studio]]></category>
		<category><![CDATA[Visual Studio Store]]></category>

		<guid isPermaLink="false">http://www.mindscape.co.nz/blog/?p=887</guid>
		<description><![CDATA[Great news for folks living in New Zealand &#8211; today we launched the New Zealand Visual Studio Store at www.getvs.net.nz. Now New Zealand developers and companies can purchase Visual Studio licenses and MSDN subscriptions completely online and in New Zealand dollars. This is a big step forward over the existing approach to purchasing Microsoft software [...]]]></description>
				<content:encoded><![CDATA[<p>Great news for folks living in New Zealand &#8211; today we launched the New Zealand Visual Studio Store at <a href="http://www.getvs.net.nz">www.getvs.net.nz</a>.</p>
<p>Now New Zealand developers and companies can purchase Visual Studio licenses and MSDN subscriptions completely online and in New Zealand dollars. This is a big step forward over the existing approach to purchasing Microsoft software for developers in New Zealand. You can also buy Mindscape products there in NZ dollars and we plan to offer further Microsoft and third-party products over time.</p>
<p><a href="http://www.getvs.net.nz/default.aspx"><img src="http://www.mindscape.co.nz/blog/wp-content/uploads/2009/08/store2.jpg" alt="Get Visual Studio and MSDN online in New Zealand" title="Get Visual Studio and MSDN online in New Zealand" width="610" height="274" class="alignnone size-full wp-image-892" /></a></p>
<p><strong>What&#8217;s available in the store?</strong></p>
<p>We&#8217;ve started the store with VS 2008 / MSDN options (1 year, 3 year subscriptions) and the entire Mindscape catalogue.  We&#8217;ll be growing the lineup over time so if there is a product you&#8217;d like to get your hands on that is not listed then <a href="http://www.getvs.net.nz/contact">please let us know</a> &#8211; we&#8217;ll help make it happen.</p>
<p>One thing we&#8217;ve tried to do is to make it easy for you to identify the editions of products that make the most sense to you &#8211; no more needing tensor calculus to work out what licenses you need!  We&#8217;ve also tried to make pricing a little simpler by pricing everything in New Zealand dollars.</p>
<p>However, if you know you need a licensing option that&#8217;s not listed, or you&#8217;re not sure what products you need, just <a href="http://www.getvs.net.nz/contact">get in touch</a>, we&#8217;re happy to help.</p>
<p><strong>I&#8217;m not a New Zealander!</strong></p>
<p>Just ignore this post!  Our main outlet for Mindscape products continues to be our own <a href="http://www.mindscape.co.nz/store/">online store</a>: there&#8217;s no change there!</p>
<p>For Visual Studio and MSDN licences, you&#8217;ll need to contact a local retailer just as you do at the moment.  Due to how Microsoft licensing is divided up amongst countries and regions, we&#8217;re not able to sell Microsoft products to customers outside New Zealand.</p>
<p><strong>Additional services</strong></p>
<p>Through the Visual Studio Store we are also providing service options to help development teams in New Zealand. The initial offerings include helping larger organisations ascertain what their licensing requirements are as well as more technical workshops on getting the most from your software infrastructure. As with everything, we&#8217;re open to feedback on any support and service options you would like to see.</p>
<p><a href="http://www.getvs.net.nz/default.aspx">Go and check it out and let us know what you think!</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.mindscapehq.com/blog/index.php/2009/08/23/buy-visual-studio-msdn-online/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>SimpleDB Managment Tools screencast</title>
		<link>http://www.mindscapehq.com/blog/index.php/2009/01/08/simpledb-managment-tools-screencast/</link>
		<comments>http://www.mindscapehq.com/blog/index.php/2009/01/08/simpledb-managment-tools-screencast/#comments</comments>
		<pubDate>Thu, 08 Jan 2009 20:53:07 +0000</pubDate>
		<dc:creator>John-Daniel Trask</dc:creator>
				<category><![CDATA[Screencast]]></category>
		<category><![CDATA[SimpleDB Management Tools]]></category>
		<category><![CDATA[Visual Studio]]></category>
		<category><![CDATA[SimpleDB]]></category>

		<guid isPermaLink="false">http://www.mindscape.co.nz/blog/?p=364</guid>
		<description><![CDATA[With SimpleDB Management Tools newly released we decided it would be helpful to those who are interested in it to see it in action. I have created a short 3 minute screencast providing an overview of common functions: Connecting to a new SimpleDB instance inside Visual Studio 2008 Managing domains Querying data both with Amazon [...]]]></description>
				<content:encoded><![CDATA[<p>With <a href="https://www.mindscape.co.nz/products/simpledbtools/default.aspx">SimpleDB Management Tools newly released</a> we decided it would be helpful to those who are interested in it to see it in action. I have created a short 3 minute screencast providing an overview of common functions:</p>
<ul>
<li>Connecting to a new SimpleDB instance inside Visual Studio 2008</li>
<li>Managing domains</li>
<li>Querying data both with Amazon query syntax and SQL-like SELECT syntax</li>
<li>Editing and deleting data</li>
<li>Working with attributes</li>
</ul>
<p><a href="https://www.mindscape.co.nz/products/simpledbtools/screencasts/gettingstarted.aspx">View the screencast of getting started with SimpleDB Management Tools.</a></p>
<p>As always, we appreciate feedback on this &#8211; is there anything else you would like to see? something missing? Let us know in the comments :-)</p>
]]></content:encoded>
			<wfw:commentRss>http://www.mindscapehq.com/blog/index.php/2009/01/08/simpledb-managment-tools-screencast/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>What&#8217;s coming in 2009 from Mindscape?</title>
		<link>http://www.mindscapehq.com/blog/index.php/2009/01/04/whats-coming-in-2009-from-mindscape/</link>
		<comments>http://www.mindscapehq.com/blog/index.php/2009/01/04/whats-coming-in-2009-from-mindscape/#comments</comments>
		<pubDate>Mon, 05 Jan 2009 04:45:16 +0000</pubDate>
		<dc:creator>John-Daniel Trask</dc:creator>
				<category><![CDATA[LightSpeed]]></category>
		<category><![CDATA[News]]></category>
		<category><![CDATA[Products]]></category>
		<category><![CDATA[Visual Studio]]></category>
		<category><![CDATA[WPF Elements]]></category>
		<category><![CDATA[WPF Property Grid]]></category>
		<category><![CDATA[2009]]></category>
		<category><![CDATA[SimpleDB]]></category>
		<category><![CDATA[WPF]]></category>

		<guid isPermaLink="false">http://www.mindscape.co.nz/blog/?p=341</guid>
		<description><![CDATA[Happy new year everybody, I hope you&#8217;ve all had a fantastic break and recharge over the last couple of weeks. We have returned energized and ready to bring a slew of new products and enhancements to our line up. Amazon SimpleDB Love SimpleDB went into public beta late last year and people have been playing [...]]]></description>
				<content:encoded><![CDATA[<p>Happy new year everybody, I hope you&#8217;ve all had a fantastic break and recharge over the last couple of weeks. We have returned energized and ready to bring a slew of new products and enhancements to our line up.</p>
<p><strong>Amazon SimpleDB Love</strong></p>
<p><a href="http://aws.amazon.com/simpledb/">SimpleDB</a> went into public beta late last year and people have been playing with it to work out what cool things they can do with it. Of course we thought that with the rising interest in &#8220;the cloud&#8221; that adding support for SimpleDB to LightSpeed would be a nice first step. If you&#8217;re interested in using the only .NET O/R Mapper that supports SimpleDB then you can get the latest nightly which already supports SimpleDB! Grab the latest nightly from <a href="http://www.mindscape.co.nz/products/lightspeed/nightlybuilds.aspx">the nightly build page</a>.</p>
<p><strong>But wait, there&#8217;s more!</strong></p>
<p>As part of Ivan exploring SimpleDB we rapidly found that we needed to build some things to make it easier for us to work with SimpleDB. Not out the door yet but coming very soon, we will ship a SimpleDB add-in for Visual Studio which will enable you to manage your SimpleDB domains and data in a fashion similar to SQL Management Studio, and of course to create LightSpeed models from your SimpleDB domains.</p>
<p><a href="http://www.mindscape.co.nz/blog/wp-content/uploads/2009/01/editing-simpledb-data.png"><img src="http://www.mindscape.co.nz/blog/wp-content/uploads/2009/01/editing-simpledb-data-600x201.png" alt="Editing data and managing SimpleDB domains inside Visual Studio" title="Editing data and managing SimpleDB domains inside Visual Studio" width="600" height="201" class="size-medium wp-image-348" /></a></p>
<p><strong>WPF goodies</strong></p>
<p>Adding to our existing line up of the <a href="http://www.wpfpropertygrid.com">WPF Property Grid</a> and <a href="http://www.mindscape.co.nz/products/wpfelements/">WPF Elements</a> we will be significantly enhancing our WPF product line up in in the first half of 2009.</p>
<p><strong>LightSpeed 2.2</strong></p>
<p><a href="http://www.mindscape.co.nz/products/lightspeed/">LightSpeed</a> is continuing to evolve and it will be an exciting year for what we have planned for LightSpeed. LightSpeed 2.2 will be shipping shortly and includes several major features:</p>
<ul>
<li>Stored procedure support</li>
<li><a href="http://www.asp.net/dynamicdata/">Dynamic data</a> support</li>
<li>SimpleDB database support</li>
<li>Many more smaller enhancements</li>
</ul>
<p>Of course all of these will be available in the <a href="http://www.mindscape.co.nz/products/lightspeed/nightlybuilds.aspx">nightly builds</a> if you want to get your hands on them early &#8211; many already are!</p>
<p><strong>Anything else?</strong></p>
<p>We have other plans for later in the year however our best source of inspiration around new products and enhancements is you &#8211; our excellent geek audience. What would you love to see delivered in 2009?</p>
<p>Here&#8217;s to making 2009 a huge year!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.mindscapehq.com/blog/index.php/2009/01/04/whats-coming-in-2009-from-mindscape/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Extending Visual Studio properties</title>
		<link>http://www.mindscapehq.com/blog/index.php/2008/09/09/extending-visual-studio-properties/</link>
		<comments>http://www.mindscapehq.com/blog/index.php/2008/09/09/extending-visual-studio-properties/#comments</comments>
		<pubDate>Wed, 10 Sep 2008 02:57:24 +0000</pubDate>
		<dc:creator>Ivan Towlson</dc:creator>
				<category><![CDATA[Visual Studio]]></category>
		<category><![CDATA[VSX]]></category>

		<guid isPermaLink="false">http://www.mindscape.co.nz/blog/?p=257</guid>
		<description><![CDATA[We&#8217;ve been doing a bit of work with Visual Studio Extensibility recently through the LightSpeed designer and the VS File Explorer add-in, so I thought I&#8217;d start jotting down some of the stuff we&#8217;ve come across. We&#8217;ll start with a nice obscure one&#8230; One of the features we&#8217;ve always had in mind for the LightSpeed [...]]]></description>
				<content:encoded><![CDATA[<p>We&#8217;ve been doing a bit of work with <a href="http://msdn.microsoft.com/en-us/vsx/default.aspx">Visual Studio Extensibility</a> recently through the <a href="http://www.mindscape.co.nz/products/LightSpeed/">LightSpeed</a> designer and the <a href="http://www.mindscape.co.nz/products/vsfileexplorer/">VS File Explorer</a> add-in, so I thought I&#8217;d start jotting down some of the stuff we&#8217;ve come across.  We&#8217;ll start with a nice obscure one&#8230;</p>
<p>One of the features we&#8217;ve always had in mind for the LightSpeed designer is the ability to use your own custom templates.  An example of why you might want to do this is if you want to have the property setters always call logging code.  But how would you tell LightSpeed which custom template to use?  Well, of course, it could be a model-level thing, but then if you&#8217;ve got multiple models in a project, you have to specify it on each one individually.  More likely, you&#8217;ll want to choose the custom template at project or solution level because the reasons for needing custom code are likely to be at the project or solution level, e.g. design policy or coding standards.  To support this, we would need to add a property to the Visual Studio project object, to be displayed in the Properties window when the user selected the project.  But that object is defined by Visual Studio, not by us!</p>
<p>If you&#8217;re familiar with Windows Forms, you probably know that some controls (such as ToolTip and HelpProvider) have exactly the same problem &#8212; they want to add a pseudo-property to other controls on the form.  Windows Forms solves this using an interface called IExtenderProvider.  Visual Studio provides an analogous interface, also called IExtenderProvider though with slightly different methods.</p>
<p>So to add properties to a Visual Studio object, you implement IExtenderProvider and register your implementation using DTE.ObjectExtenders.RegisterExtenderProvider.  For add-ins, do this in your connection method.  For DSL Tools packages, you can do it in your package&#8217;s Initialize override.  As part of registration, you have to say what kind of object you&#8217;re interested in extending (expressed as a CATID string for your old-skool COM nostalgia-inducing pleasure), so you may need to register multiple times (for example to extend both C# and Visual Basic projects).  You may need to do a bit of poking around to find out what CATID to register with for any given selection, though the EnvDTE.Constants class and the VSLangProj namespace are good places to start.</p>
<p>When the user makes a selection, Visual Studio asks all suitably registered extender providers whether they are interested in this selection by calling IExtenderProvider.CanExtend.  At this point you have access to the extendee object so you can make a more specific decision if required.  For example we&#8217;d only want to display our custom property against projects that contain LightSpeed models.</p>
<p>If you return true from CanExtend, Visual Studio calls your GetExtender implementation.  All you need to do from here is return an object with the properties you want added to the property grid.  (Well, you need to do some bookkeeping as well, but this is described in the VS SDK documentation.)  One thing we found is that the returned object needs to be COM-visible; otherwise, it&#8217;s just a plain old CLR object.  Your returned object can use WinForms design-time attributes like CategoryAttribute, DisplayNameAttribute, DescriptionAttribute and EditorAttribute to customise the display.</p>
<p>Be aware that all this does is display the extension properties in the Properties window.  Sometimes this is all you need: for example, the <a href="http://ankhsvn.open.collab.net/">AnkhSVN</a> add-in for Subversion displays read-only source control information using this technique.  But in our case we would also need to save whatever the user enters into the &#8220;template file&#8221; extension property.  How you do this depends on what you&#8217;re extending, but if you&#8217;re extending a project or solution, one simple solution is to have Visual Studio save the values as part of the project or solution file by using the Globals property of the Project or Solution interface, and setting VariablePersists to true.</p>
<p>As so often with Visual Studio, much of the battle is knowing what to do.  You can see from the above that there&#8217;s not a lot of code to write to extend a Visual Studio object, but the documentation is ropey and the samples are often out of date.  Hopefully this will provide a few pointers for the two other people on the planet who need to extend the VS properties window&#8230;</p>
]]></content:encoded>
			<wfw:commentRss>http://www.mindscapehq.com/blog/index.php/2008/09/09/extending-visual-studio-properties/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
	</channel>
</rss>

<!-- Performance optimized by W3 Total Cache. Learn more: http://www.w3-edge.com/wordpress-plugins/

Page Caching using disk: basic (Requested URI is rejected)
Database Caching 5/22 queries in 0.018 seconds using disk: basic

 Served from: www.mindscapehq.com @ 2013-06-19 11:39:48 by W3 Total Cache -->