Monday, June 29, 2009

Buy Visual T4 Pro, Get Free Pro ASP.NET MVC Book!

Yes, the best T4 Editor meets the best ASP.NET MVC book.

AspNetMvcFreeBook

If you’re into ASP.NET MVC and want to play and customize the MVC T4 templates with wonderful support getting full Preview, IntelliSense, syntax coloring and more for both T4 and C# embedded code this deal is for you!

Buy here the Visual T4 Editor Professional and you will get the book for free.

This promotion is only valid till July, 3rd, 2009  or until we ran out of our 100 books stock, whatever comes first.

As we know no one wants to wait a week for a book we will ship it using a 2nd-day service to get you the book really quick.

Please note we can only ship to an US address, sorry.

Monday, April 20, 2009

Visual T4 in the news!

Our Visual T4 products continue to be mentioned by pretty much everyone out there working with T4. You already know our tools were used in MIX09 (besides other major conferences in the past) and that pretty big teams at Microsoft recommend it.

We did google a bit and these are the most “remarkable” mentions we’re getting (it’s just great to see we have built the “standard” tool for editing T4 files!):

Scott Hanlseman (Principal Program Manager, Microsoft) on T4 (Text Template Transformation Toolkit) Code Generation - Best Kept Visual Studio Secret:

"if you want really get the most out of T4, first, head over to Clarius Consulting and get their "T4 Editor Community Edition." That'll get you some basic coloring. They have a pay version that gets you more if you want."

 Oleg Sych, uses Visual T4 Editor in his must-read series of T4 articles mentions:

“…Instead, the approach used by Clarius in their implementation of this directive included with T4 Editor relies on CallContext, is a lot more robust and elegant…”

“…Text editing and debugging support for T4 templates is currently rather limited. T4 Editor (a free download) from Clarius Consulting provides IntelliSense and syntax highlighting in Visual Studio text editor for .tt files…”

Miguel de Icaza, on Mono's Text Template Transformation Toolkit (T4):

“To my surprise T4 thing is wildly used by lots of people. Daniel Cazzulino's company has a product just to improve Visual Studio's support for editing .tt files.”

Redmond Developer News , on Code Generation Made Easy :

"There are a lot of tools out there that do code generation," Conery says. "Great tools like CodeSmith and Clarius Consulting's T4 Editor”

Gareth Jones (Visual Studio team member, Microsoft) , on Clarius take T4 editing to the next level :

“…I see that Clarius have now got to an alpha stage for the next stage of their T4 editing toolset.

As well as their Community Edition and Pro Edition, they're now going to offer a full-featured code generation environment they're calling Visual T4 Code Generator, including tight integration with server explorer, database tables and XML as well as a multi-file generation implementation out of the box and lots more beside…”

Pedro Silva (Visual Studio team member, Microsoft) , on T4 Editor Beta Released:

“The folks at Clarius have an update to their T4 template editor. They're now in Beta. It's a very useful editor for anyone doing large amounts of T4 template editing with good factoring of template code vs script and color coding of keywords.”

Kathleen Dollard (Microsoft MVP) , on What’s Wrong with T4?:

“There’s good news here. Clarius provides a colorizing editor as a community edition to get you started. If you want fancier features, their main product is just $100”

Hanselminutes on Code Generation

In case you missed this (as we did) Scott interviews Kathleen Dollard (Microsoft MVP) on code generation in .Net and Visual Studio.

It’s an interesting chat on the past and current state of code gen, with emphasis on T4. You can listen to the podcast here.

Make sure you don’t miss the audio @ 19m:43s where Clarius Visual T4 Editor is recommended if you are into serious editing of T4 templates :)

Thursday, March 26, 2009

The process of building a Code Generation template

More often than not, you’ll have several related classes and you’ll want to turn them into generated code. There is a process I like to use to make a generation template that’s based on this idea. You can also use the process even if you don’t have the classes, by building them manually.

First, you’ll need a class. For example, we’re going to use generation to create a strongly type representation of a directory structure and files on disk. In the example, these files will be configuration files spread throughout a few directories, but we’ll open them as simple strings to make the sample easier. Let’s look at the code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace MyCompany.MyProduct
{
class Configuration
{
private string baseDir = "Configuration";

public Configuration(string baseDir)
{
this.baseDir = string.Concat(baseDir, "\\Configuration");
}

public Network Network
{
get
{
return new Network(baseDir);
}
}
}

class Network
{
private string baseDir;

public Network(string baseDir)
{
this.baseDir = string.Concat(baseDir, "\\Network");
}

public string ProxiesConfig
{
get
{
return File.ReadAllText(string.Concat(baseDir, "\\Proxies.Config");
}
set
{
File.WriteAllText(string.Concat(baseDir, "\\Proxies.Config"), value);
}
}

public string HostsConfig
{
get
{
return File.ReadAllText(string.Concat(baseDir, "\\Hosts.Config");
}
set
{
File.WriteAllText(string.Concat(baseDir, "\\Hosts.Config"), value);
}
}
}

class Security
{
private string baseDir;

public Security(string baseDir)
{
this.baseDir = string.Concat(baseDir, "\\Security");
}

public string RolesConfig
{
get
{
return File.ReadAllText(string.Concat(baseDir, "\\Roles.Config");
}
set
{
File.WriteAllText(string.Concat(baseDir, "\\Roles.Config"), value);
}
}
}
}


Notice that this code already has a “generated” look and feel. The idea is to create a Configuration object with the base path for configuration, and to go down from there to all the configuration items. Network and Security will be directories within Configuration, and the other properties will refer to files in the directories. Notice also that at this point it’s not very important to have complete classes. A rough layout is enough.



The next step is to find varying parts. This is really simple: variables will generally be present as constants or as variable properties. Constants is far more common. In this step, we’ll replace the constants with representative code blocks:



    class Configuration
{
private string baseDir = <#= baseDirectoryName #>;

public Configuration(string baseDir)
{
this.baseDir = string.Concat(baseDir, “<#= baseDirectoryPath #>”);
}

public Network Network
{
get
{
return new Network(baseDir);
}
}
}

class Network
{
private string baseDir;

public Network(string baseDir)
{
this.baseDir = string.Concat(baseDir, “<#= baseDirectoryPath #>”);
}

public string ProxiesConfig
{
get
{
return File.ReadAllText(string.Concat(baseDir, “<#= configFileName #>”);
}
set
{
File.WriteAllText(string.Concat(baseDir, “<#= configFileName #>”), value);
}
}

public string HostsConfig
{
get
{
return File.ReadAllText(string.Concat(baseDir, “<#= configFileName #>”);
}
set
{
File.WriteAllText(string.Concat(baseDir, “<#= configFileName #>”), value);
}
}
}


Then we’ll also replace the varying property names (and class and method names if necessary) with code blocks too:



    class <#= baseDirectoryName #>
{
private string baseDir = <#= baseDirectoryName #>;

public Configuration(string baseDir)
{
this.baseDir = string.Concat(baseDir, “<#= baseDirectoryPath #>”);
}

public <#= childDirectoryName #> <#= childDirectoryName #>
{
get
{
return new <#= childDirectoryName #>(baseDir);
}
}
}

class <#= baseDirectoryName #>
{
private string baseDir;

public <#= baseDirectoryName #>(string baseDir)
{
this.baseDir = string.Concat(baseDir, “<#= baseDirectoryName #>”);
}

public string <#= configFileName #>
{
get
{
return File.ReadAllText(string.Concat(baseDir, “<#= configFileName #>”);
}
set
{
File.WriteAllText(string.Concat(baseDir, “<#= configFileName #>”), value);
}
}

public string <#= configFileName #>
{
get
{
return File.ReadAllText(string.Concat(baseDir, “<#= configFileName #>”);
}
set
{
File.WriteAllText(string.Concat(baseDir, “<#= configFileName #>”), value);
}
}
}


At this point, you should have some duplication. The next step is to remove that duplication by looping through duplicated constructs:



<#
for (int classes = 0; classes < n; classes++)
{
#>
class <#= baseDirectoryName #>
{
private string baseDir;

public <#= baseDirectoryName #>(string baseDir)
{
this.baseDir = string.Concat(baseDir, “<#= baseDirectoryName #>”);
}

<#
for (int props = 0; props < n; props++)
{
#>
public string <#= configFileName #>
{
get
{
return File.ReadAllText(string.Concat(baseDir, “<#= configFileName #>”);
}
set
{
File.WriteAllText(string.Concat(baseDir, “<#= configFileName #>”), value);
}
}
<#
}
#>
}
<#
}
#>


You should also add whatever’s left behind (in this case, the “directory” properties:



<#
for (int classes = 0; classes < n; classes++)
{
#>
class <#= baseDirectoryName #>
{
private string baseDir;

public <#= baseDirectoryName #>(string baseDir)
{
this.baseDir = string.Concat(baseDir, “<#= baseDirectoryName #>”);
}

<#
for (int childClasses = 0; childClasses < n; childClasses++)
{
#>
public <#= childDirectoryName #> <#= childDirectoryName #>
{
get
{
return new <#= childDirectoryName #>(baseDir);
}
}
<#
}
#>
<#
for (int props = 0; props < n; props++)
{
#>
public string <#= configFileName #>
{
get
{
return File.ReadAllText(string.Concat(baseDir, “<#= configFileName #>”);
}
set
{
File.WriteAllText(string.Concat(baseDir, “<#= configFileName #>”), value);
}
}
<#
}
#>
}
<#
}
#>


At this point, you should have a pretty good skeleton. The point now is to make it work:



<#
foreach(string directory in Directory.GetDirectories("myconfigurationdir"))
{
#>
class <#= directory #>
{
private string baseDir;

public <#= directory #>(string baseDir)
{
this.baseDir = string.Concat(baseDir, "<#= directory #>");
}

<#
foreach (string childDirectory in Directory.GetDirectories(directory))
{
#>
public Network <#= childDirectory #>
{
get
{
return new <#= childDirectory #>(baseDir);
}
}
<#
}
#>
<#
foreach (string file in Directory.GetFiles(directory))
{
#>
public string <#= file #>
{
get
{
return File.ReadAllText(string.Concat(baseDir, "<#= file #>");
}
set
{
File.WriteAllText(string.Concat(baseDir, "<#= file #>"), value);
}
}
<#
}
#>
}
<#
}
#>


At this point you should be added any imports that are needed for the generation code to work (System.IO in this case). You may also need to separate processes in methods, as to make them recursive. For instance, our classes need to be generated for each directory in the hierarchy. Finally, you must solve generation-specific problems. For instance, this generation will probably have many invalid class and property names (“Proxies.Config” is not a valid class name). You can change that by using the CleanName procedure that we already reviewed in this blog. The result will look something like this:



using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

<#
GenerateClass("myconfigdir");
#>
<#+
void GenerateClass(string directoryName)
{
foreach(string directory in Directory.GetDirectories(directoryName))
{
#>
class <#= CleanName(directory) #>
{
private string baseDir;

public <#= CleanName(directory) #>(string baseDir)
{
this.baseDir = string.Concat(baseDir, "<#= directory #>");
}

<#+
foreach (string childDirectory in Directory.GetDirectories(directory))
{
#>
public <#= CleanName(childDirectory) #> <#= CleanName(childDirectory) #>
{
get
{
return new <#= CleanName(childDirectory) #>(baseDir);
}
}
<#+
}
#>
<#+
foreach (string file in Directory.GetFiles(directory))
{
#>
public string <#= CleanName(file) #>
{
get
{
return File.ReadAllText(string.Concat(baseDir, "<#= file #>");
}
set
{
File.WriteAllText(string.Concat(baseDir, "<#= file #>"), value);
}
}
<#+
}
#>
}
<#+
GenerateClass(directory);

}
}


string CleanName(string)

{

//some code cleaning here

}
#>


The final step is to separate the code into modules. For instance, you can put the CleanName procedure in an include T4 file to be used as a helper, put the header in a “main” T4 and the methods in generation T4 files, separate the properties into its own include, or whatever feels good to you.



--

Written by Joaquin, joj AT clariusconsulting DOT net. Disclaimer: opinions expressed in this post are my own and not necessarily reflect those of Clarius Consulting.

Monday, March 23, 2009

Visual T4 @ MIX09

We’ve been catching up on web techs watching MIX09 videos and guess what…?

Scott Hanselman in his File|New -> Company: Creating NerdDinner.com with Microsoft ASP.NET Model View Controller (MVC) and Phil Haack in his Microsoft ASP.NET Model View Controller (MVC): Ninja on Fire Black Belt Tips talks both mention the Clarius Visual T4 Editor for editing T4 templates!

Here is a screenshot of Phil, on stage, using the Visual T4 Editor Professional edition:

VisualT4Mix09

Good to see Visual T4 being used everywhere!!

NHibernate: Why override GetHashCode and Equals?

When using NHibernate collections, or when comparing two objects that are configured via NHibernate configuration, NHibernate code will use the Equals and GetHashCode methods in the class. It is very important to implement this methods in a way that will make two different entities return different values and to identical entities return identical values. That’s the only condition. The value doesn’t need to be related to anything in the table at all as long as it passes that test. This is both easy and hard. Let me show you why.

The point here is to always generate a value that will represent a row in the table. In a normal table, any candidate key (that is, a unique index or a primary key) will serve this role. In the samples that come with Visual T4 Editor Professional edition we use the primary key to generate these methods:

        public override int GetHashCode()
{
int hashCode = 0;
hashCode = hashCode ^ CustomerID.GetHashCode();
return hashCode;
}

public override bool Equals(object obj)
{
Customers toCompare = obj as Customers;
if (toCompare == null)
{
return false;
}
if (this.CustomerID != toCompare.CustomerID)
{
return false;
}
return true;
}


The Equals method is fairly simple to override. Just compare keys, and if everything matches return true. GetHashCode is a little different. You must return an integer value tailored to the needs of the two rules. For the sample, we have chosen to use xor to compare, due to a high success rate. For production code, you should choose to “shift and or” or to concatenate and get the hash code of the string. Both methods will give you a 100% success rate, on varying levels of complexity and performance.



There is an additional problem here, specially for code generation: if you have a transient object (that is, one that is not yet saved to the database) and identity value will always be a bad choice. The problem is that until NHibernate saves the object to the database, the value of the identity (or primary key, depending on configuration) will be the default value for the datatype (0 in this case). Hence, two unsaved values will be equal. Although this is technically correct (unsaved values may be considered “null” for some purposes) it is highly impractical.



In this case, the best solution is to take an alternate key (an unique non-null key) and use that for the comparison. As long as the user actually fills that value when constructing the object, everything should be fine. A code generator may find a candidate key and use it. It will not, however, be able to know if this candidate key will be filled when needed. As a default solution both primary key and a candidate key may work. As a definitive solution, you should use the class knowing that you may run into this issue and manually override (as explained in Extending Code Generation with Partial Classes and Inheritance) when needed. To be 100% sure, you should always create the GetHashCode manually, and override equals with this:



        public override bool Equals(object obj)
{
Customers toCompare = obj as Customers;
if (toCompare == null)
{
return false;
}
return (this.GetHashCode() != toCompare.GetHashCode())
}


--

Written by Joaquin, joj AT clariusconsulting DOT net. Disclaimer: opinions expressed in this post are my own and not necessarily reflect those of Clarius Consulting.

Transforming Type Names

There are many situations in code generation where you may need to render the name of a Type in the generated file. For instance, you may have a method somewhere that translates a data type in a specific format to a Type, and then you want to render that type. The easy way to do it is obviously
    Type.ToString() 

but this has many drawbacks. The first problem, and this is mostly aesthetic, is that standard types like “int”, “long”, “double”, etc will be rendered as “System.Int32”, “System.Int64”, “System.Double”. Although this will work, the resulting code will have a “generated” look and feel. Your code should always be as “not-generated” as possible. That will make it easier to read and debug.

The second problem is that there are types that will simply not translate to your preferred language easily. For instance, “List<string>” will be translated as “System.Collections.Generic.List’1[System.String]”. There is no way for that text to be useful in a generation context!

There are a few ways to work around this. You may code a few methods that will translate from the Type to your language. This is not a trivial task, but there are a few implementations readily available. For instance, the class ContractNameServices.cs in MEF (http://www.codeplex.com/MEF/SourceControl/changeset/view/26383#370431) has a method named GetDefaultContractName which does just that, and it is very cleanly implemented.

The easiest way is to use a CodeDomProvider for your language. The following few lines of code illustrate this concept:
CodeTypeReferenceExpression type = new CodeTypeReferenceExpression(typeof(System.Collections.Generic.List<float>));
CodeDomProvider csProvider = Microsoft.CSharp.CSharpCodeProvider.CreateProvider("C#");
CodeDomProvider vbProvider = Microsoft.VisualBasic.VBCodeProvider.CreateProvider("VB");
StringWriter writer = new StringWriter();
csProvider.GenerateCodeFromExpression(type, writer, new CodeGeneratorOptions());
writer.Write(writer.NewLine);
vbProvider.GenerateCodeFromExpression(type, writer, new CodeGeneratorOptions());
Console.WriteLine(writer.ToString());


The output of this code will be:
System.Collections.Generic.List<float>
System.Collections.Generic.List(Of Single)


which is both useful and language independent at the same time.

--

Written by Joaquin, joj AT clariusconsulting DOT net. Disclaimer: opinions expressed in this post are my own and not necessarily reflect those of Clarius Consulting.