Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to generate code based on another class?

To create our test data, we use the following variation of the Builder pattern (simplified example!):

Sample class:

public class Person
{
   public string Name { get; set; }
   public string Country { get; set; }
}

The builder:

public class PersonBuilder
{
    private string name;
    private string country;

    public PersonBuilder()
    {
        SetDefaultValues();
    }

    private void SetDefaultValues()
    {
        name = "TODO";
        country = "TODO";
    }

    public Person Build()
    {
        return new Person
                   {
                       Name = name,
                       Country = country
                   };
    }

    public PersonBuilder WithName(string  name)
    {
        this.name = name;            
        return this;
    }

    public PersonBuilder WithCountry(string country)
    {
        this.country = country;
        return this;
    }
}

NOTE: The context of the example itself is not relevant. The important thing here is how in the example, the a builder class like PersonBuilder can completely be generated by looking at the entity class (Person) and applying the same pattern - see below.

Now imagine that the person class has 15 properties instead of 2. It would take some monkeywork to implement the builder class, while theoretically, it could automatically be generated from the Person class. We could use code generation to quickly set up the builder class, and add custom code later if needed.

The code generation process would have to be aware of the context (name and properties of the person class), so simple text-based code generation or regex magic doesn't feel right here. A solution that is dynamic, not text-based and can be triggered quickly from inside visual studio is preferred.

I'm looking for the best way to perform code generation for scenarios like this. Reflection? Codesmith? T4 templates? Resharper Live templates with macros?

I'm looking forward to see some great answers :)

like image 929
Bram De Moor Avatar asked Mar 22 '11 14:03

Bram De Moor


2 Answers

The T4 solution is a well Visual Studio integrated option. You can use reflection inside the T4 template to actually generate the code.

like image 168
Felice Pollano Avatar answered Sep 19 '22 15:09

Felice Pollano


We added a feature in CodeSmith Generator 5.x that allows you to generate off of existing code. Please take a look at that documentation here. Also you can use reflection or any .NET library in a CodeSmith Generator Template.

Thanks -Blake Niemyjski

like image 43
Blake Niemyjski Avatar answered Sep 17 '22 15:09

Blake Niemyjski