Wiki
Clone wikiBoilen / Home
Description
The Boilerplate Generator, or "boilen", is a simple T4 Template file for generating boilerplate property, interface, and constructor code. Supports WPF/Silverlight dependency properties, as well as mutable/immutable/constant .NET properties, INotifyPropertyChanged, etc.
Releases
See release notes for details.
- 23 April 2017 - Boilen v3.5
Use
Caveat: Boilen was created to support a specific project and will not necessarily fit your needs. It has not been designed for extensibility and is tailored to the features we needed. That said, the generated code is still general purpose (we are talking about properties after all), and you're welcome to use it.
Requirements
- Project must output a
.dll
library. - Project must target .NET or WPF (not Silverlight).
- The generator uses WPF features as input to generate both WPF and Silverlight code.
- (helpful) Familiarity with the T4 framework.
First-time Setup
- (optional) Add the
BoilenTemplate.zip
item template to your Visual Studio user directory (Visual Studio 2008\Templates\ItemTemplates\Visual C#\General
under the Documents directory). - Add the
Boilen.tt
file to your project.- For example, create a
Templates
directory and copyBoilen.tt
to it.
- For example, create a
- Add a new
Includes.tt
file to your project.- This file should contain T4 directives to include your library and any common constants referenced by your templates (see example below).
- (optional) Setup your project to automatically register your assembly in the GAC, or update your Reference Paths to include the output folder.
- The Boilen Editor can be used to edit and transform files without having to register assemblies in the GAC.
Includes.tt
#!c# <#@ assembly name="Dependencies.For.Your.Project" #> <#@ assembly name="Your.Project" #> <#@ import namespace="Your.Project.Namespaces" #> <# //GlobalSettings.ExternalDocumentationPrefix = "Documentation/"; #> <#+ private const string CommonConstants = "x"; [TemplateType] public struct CommonReferenceTypes { } #>
Boilen Editor
The Boilen Editor is a stand-alone application that allows you to open, edit, and transform .b.tt
template files. Any assembly references from local projects will be automatically copied when performing a transform operation, so the assemblies do not need to be registered in the GAC.
Open Boilen Template File
Search For Boilen Template File in Selected Project
Edit and Transform Files in the Boilen Editor
Configure and Insert Member Snippets
Using Boilen
- Add a new partial type to your project (i.e.
Example.cs
; see example code below). - Build the project, in order to get the new type into the output library.
- Add a new T4 template file (i.e.
Examples.properties.tt
; see example code below).- With
BoilenTemplate.zip
Item Template:- Right-click in the Solution Explorer tool window and select Add Item....
- Go to the General section and select Boilen Template from the My Templates category at the bottom.
- Manual:
- Add T4 directives to include
Boilen.tt
andIncludes.tt
. - Add a T4 directive to include the namespace of the targeted type, or add the directive to the global
Includes.tt
file, or use the full type name. - Add a new T4 statement block, with a first line of
Partial.Type<YourType>( )
orPartial.Type( typeof(YourType) )
. - Add a last line of
.Run( this.Write );
- Add T4 directives to include
- (optional) If creating a template for a class derived from a type with a non-default constructor, use the base type for
YourType
and add a"DerivedType"
argument to thePartial.Type
method. - Add any
.Add_
and.Implement_
calls to add members to the generated type.- (tip) You can use the snippet window in the Boilen Editor to configure and insert
.Add_
and.Implement_
calls.
- (tip) You can use the snippet window in the Boilen Editor to configure and insert
- With
- Save the template to generate the
Examples.properties.cs
file.
.Add_
and .Implement_
Members
All of the .Add_
methods follow the same pattern, illustrated below. The .Implement_
methods follow a simpler pattern, as the name and documentation are determined by the interface being implemented.
#!c# .Add[kind]( [name], [description], [other required parameters], [optional configuration] )
[kind]
| The type of property or event (i.e. Immutable Property, Dependency Property, etc). |
| [name]
| The name of the member (i.e. "count"
). |
| [description]
| The documentation summary for the member. |
| [optional configuration]
| An optional callback method that allows for further customization of a type. See below where the SetDefaultValue
configuration method is used to set the default value of the immutable "count"
property to 11
. |
Supported members are listed below. See the "PartialType.Implementers.cs" section of the Boilen.tt
file for the most up to date list of supported members.
Method | Parameters |
---|---|
AddEvent<THandler> |
name, description, |
AddConstantProperty<T> |
name, description, value, |
AddImmutableProperty<T> |
name, description, |
AddMutableProperty<T> |
name, description, |
AddLazyProperty<T> |
name, description, initializerExpression, |
AddDependencyProperty<T> |
name, description, |
AddDependencyProperty |
existingProperty, |
AddMetadataOverride<T> |
existingProperty, defaultValue |
AddTemplatePart<T> |
name, description, |
ImplementINotifyPropertyChanged |
{configure} |
ImplementIEquatable |
equatableProperties, |
ImplementPropertyNameConstants |
{configure} |
Documentation Replacements
Note: Boilen now supports importing documentation from external xml files as an alternative to the [description]
parameter. Set the GlobalSettings.ExternalDocumentationPrefix
in Includes.tt
to the directory where xml files are kept (i.e. "Documentation\"
, or ""
for the current directory).
The [description]
parameter supports both simple and expandable replacement values:
- Simple replacements change one value to another, just like the standard string.Replace
method. For example, if you had a replacement from "b"
to "X"
, the documentation string "abc"
would be output as "aXc"
. Custom simple replacements can be added to any implementer using the Replacements.Add
configration method.
- Expandable replacements can take arguments and perform a formatted replacement. Expanders are surrounded by %
s. Arguments are separated by :
s, and can use no-argument expanders as their value. For example, using the standard see
replacement, the documentation string "See %see:X.Y%."
would be output as "See <see cref='X.Y'/>."
; using the type
expander argument on a property of type Example
, the documentation string "See %see:type.Y%."
would be output as "See <see cref='Example.Y'/>."
.
Default replacements are listed below. See the "Doc.cs" section of the Boilen.tt
file for the most up to date list of default replacements.
Simple | Value |
---|---|
null |
<see langword='null'/> |
true |
<see langword='true'/> |
false |
<see langword='false'/> |
Expander | Value |
---|---|
name |
The name of the property or event (i.e. in the example below, the name of the Count property is Count ). |
type |
The type of the property or event (i.e. in the example below, the type of the Count property is int ). |
parent_type |
The type the property or event is declared on (i.e. in the example below, the declaring type of the Count property is Example ). |
see |
<see cref='{0}'/> |
seealso |
<seealso cref='{0}'/> |
langword |
<see langword='{0}'/> |
paramref |
<paramref name='{0}'/> |
typeparamref |
<typeparamref name='{0}'/> |
Configuration Methods
- PartialType
SetIsSealed( bool )
- Sets whether the partial type is declared assealed
.SetConstructorAccessibility( Accessibility )
- Sets the accessibility of the partial type's constructor (Public
,Protected
,Internal
, orPrivate
).AddConstructorSuppressionAttribute( string, string, string, bool )
- Adds aSystem.Diagnostics.CodeAnalysis.SuppressMessage
attribute with the specified category, id, and justification values to the static (true
) or instance (false
) constructor.SetOverrideDefaultStyleKey( bool )
- Sets whether the partial type overrides theDefaultStyleKey
property for a control type.AddNamespace( Type|string )
- Adds ausing
declaration for a namespace to the generated file.InsertText( InsertionPoint, string )
- Inserts an arbitrary piece of text at the specified location in the generated code (Usings
,BeforeTypeDeclaration
,AfterTypeDeclaration
, orBody
).
- Implementer
Replacements.Add( string, string )
- Replaces first value with the second value in the output documentation (i.e. when using documentation from an existing type, such as for an existing dependency property).SetCondition( CompilationSymbol )
- Sets the compilation condition of the member (i.e.#if SILVERLIGHT
).- Accessor
SetAccessibility( Accessibility )
- Sets the accessibility of a member (Public
,Protected
,Internal
, orPrivate
).SetCategory( string )
- Adds aCategoryAttribute
with the specified value.SetInheritance( Inheritance )
- Sets the inheritance of a member (None
,Override
, orVirtual
).AddAttribute( Type, [CompilationSymbol,] T )
- Adds an attribute with the specified positional argument (and optional conditional compilation symbol).AddAttribute( Type, [CompilationSymbol,] string[], params string[] )
- Adds an attribute with the specified positional argument values, and the specified"name=value"
named arguments (and optional conditional compilation symbol).AddSuppressionAttribute( string, string, string )
- Adds aSystem.Diagnostics.CodeAnalysis.SuppressMessage
attribute with the specified category, id, and justification values.- Event
SetEnableArgsConvenienceMethod( bool )
- Sets whether to create a convenience method taking theEventArgs
constructor arguments, in addition to the method taking theEventArgs
instance.
- Property
SetDefaultValue( T )
- Sets the default value of the property.SetDefaultExpression( string )
- Sets the default value of the property, as returned by the expression (i.e."new List<T>()"
or"CalculatePropertyValue()"
).AddGuard( guard )
- Adds a validation guard to the property. See also standard guards:NotNull
,EnumIsDefined
,IsInRange
,Satisfies
.- ConstantProperty
- ImmutableProperty
SetIncludeInConstructor( bool )
- Sets whether to add a constructor parameter for the property. If set tofalse
, must set default value or default expression (i.e. for collection properties, commonly you initialize it with a new collection instance).
- MutableProperty
SetSetterAccessibility( Accessibility )
- Sets the accessibility of theset
accessor.- LazyProperty
- DependencyProperty
SetAttached( bool )
- Sets whether to define an attached dependency property.SetReadOnly( bool )
- Sets whether to define a read-only dependency property.SetSetterAccessibility( Accessibility )
- Sets the accessibility of a read-only dependency property'sset
accessor.SetOptions( FrameworkPropertyMetadataOptions, {string} )
- Sets theFrameworkPropertyMetadataOptions
for the property, with an optional Silverlight compatibility implementer.SetChanged( Changed )
- Sets what method signature to use for the property change handler (None
,Static
,Virtual
,Instance
, orParameterless
).SetCoerce( Coerce )
- Sets how the property should be coerced (None
,Custom
, orNonNegative
).SetValidate( Validate )
- Sets how the property should be validated (None
,Custom
,Enum
, orNotNull
).- NewDependencyProperty
- ExistingDependencyProperty
- MetadataOverride
SetOverrideInSilverlight( bool )
- Sets whether to override the default value in Silverlight, as well as overriding the dependency property metadata in WPF.
- TemplatePart
- Interface
- IEquatable
SetFormatSelector( Funct<ITarget,bool,string> )
- Sets a seletor to choose how values of each equatable property is compared and hashed (true
indicatingEquals
, andfalse
indicatingGetHashCode
). Default selector returns"EqualityComparer<{2}>.Default.Equals(this.{1}, {0}.{1})"
forEquals
(where0
is the name of the comparand,1
is the name of the property, and2
is the type of the property), and returns"EqualityComparer<{1}>.Default.GetHashCode(this.{0})"
forGetHashCode
(where0
is the name of the property, and1
is the type of the property).SetImplementOperators( bool )
- Sets whether==
and!=
operator overloads should be implemented. Default istrue
.SetEqualsImplementation( Implementation )
- Sets whether theEquals
implementation is automatic, custom, or mixed (Auto
,Custom
, orAutoAndCustom
).SetGetHashCodeImplementation( Implementation )
- Sets whether theGetHashCode
implementation is automatic, custom, or mixed (Auto
,Custom
, orAutoAndCustom
).SetVerifyExactType( bool )
- Sets whetherEquals
will verify that the current and given objects are the same type before comparing their members. Default isfalse
.
- INotifyPropertyChanged
SetInheritImplementation( bool )
- Sets whether to prevent adding new Raise helper methods if the base type already implementsINotifyPropertyChanged
.
- PropertyNameConstants
- IEquatable
Examples
Example.cs
#!c# public partial class Example { // implementation }
Example.properties.tt
#!c# <#@ include file="./Templates/Boilen.tt" #> <#@ include file="./Templates/Includes.tt" #> <# Partial.Type<Example>( ) .AddImmutableProperty<int>( "count", "the number of items in the %see:parent_type%", p => p .SetDefaultValue( 11 ) ) // other members .Run( this.Write ); #>
Example.properties.cs
#!c# // <AUTO-GENERATED> // !!! WARNING !!! // !!! This code was automatically generated from a T4 template. // !!! Do not edit this file directly. Changes to this file will be lost. // !!! WARNING !!! // // Source Template: Example.properties.tt // Last Generated: 02/12/2009 14:00:28 // </AUTO-GENERATED> using System; namespace Your.Project.Namespaces { partial class Example { private readonly int zz_count; /// <summary> /// Initializes a new <see cref='Example'/> instance with the specified count. /// </summary> /// <param name='count'> /// The number of items in the <see cref='Example'/>. /// </param> public Example(int count) { this.zz_count = count; this.InitializeInstance(); } partial void InitializeInstance(); /// <summary> /// Initializes a new <see cref='Example'/> instance. /// </summary> public Example() : this(11) { } /// <summary> /// Gets the number of items in the <see cref='Example'/>. /// </summary> public int Count { get { return this.zz_count; } } } }
Updated