DTE and T4 - Better Together

A couple of folks out there have put together some really neat T4 templates that use the host-specific flag and then access Visual Studio's DTE object model to read state from other code in the project and use that as metadata for code generation.

Daniel Vaughan started out with a  nice post on using DTE to explore the source constructs within your project using the CodeModel and thence using that data to  introduce compile time strong-typing to WPF binding expressions.

To borrow Daniel's example, to switch from this weakly typed case

<StackPanel DataContext="{Binding Source={StaticResource Person}}">
    <TextBlock >Name:</TextBlock>
    <TextBox Text="{Binding Name}" />
</StackPanel>

to this strongly typed one which gives compile-time errors if you get the name wrong

<StackPanel DataContext="{Binding Source={StaticResource Person}}">
	<TextBlock >Name:</TextBlock>
	<TextBox Text="{Binding Path={x:Static Metadata:PersonMetadata.NamePath}}"/>
</StackPanel>

He then also talks about using the same technique to generate implementations of INotifyPropertyChange that are robust to refactoring without the problems of embedded strings or the performance hit of reflection.  Code generation and declarative programming are often criticized for not having good support for refactoring, so it's nice to see a use case that actually helps support refactoring.

Daniel has now expanded this into a full article on The Code Project.

 

Last time, I talked about Colin Eberhardt's article for generating Dependency Properties from an xml file.  Daniel's approach inspired Colin to go back and rework his example to use DTE replacing his external XML file with custom attributes on classes to simply add dependency properties like so:

[DependencyPropertyDecl("Maximum", typeof(double), 0.0)]
[DependencyPropertyDecl("Minimum", typeof(double), 0.0)]
public partial class RangeControl : UserControl
{
    ...
}

Very cool stuff.

Published 25 September 09 07:27 by GarethJ

Comments

# Anoop said on October 7, 2009 2:58 PM:

Gareth, in vs2010 beta, I found that using dynamic types from T4 is causing a runtime binding exception. Any pointers? I've detailed the problem here

http://stackoverflow.com/questions/1531165/how-can-i-specify-t4-text-templates-to-use-c-4-0-in-vs2010

New Comments to this post are disabled

Search

This Blog

Disclaimer
The information in this weblog is provided "AS IS" with no warranties, and confers no rights. This weblog does not represent the thoughts, intentions, plans or strategies of my employer. It is solely my opinion. Inappropriate comments will be deleted at the authors discretion.
All code samples are provided "AS IS" without warranty of any kind, either express or implied, including but not limited to the implied warranties of merchantability and/or fitness for a particular purpose.

Tags

Archives

Architects who Model

DSL Tools Team

Links

Syndication

Page view tracker