Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / web / ASP.NET

Smart Code Generator .NET : Code Generation experience with Visual Studio and ASP.NET – Usage Overview

3.26/5 (13 votes)
14 Feb 200710 min read 1   1K  
SmartCodeGenerator is a full-fledged template-based code generator. Templates are written in Visual Studio as ASP.NET User Controls.This article is more of a usage guideline and tries to answer how to use SmartCodeGenerator for template based output.
Sample image

Introduction

SmartCodeGenerator is an ASP.NET 2.0 website or an ASP.NET 1.1 web application and is a full-fledged template-based code generator that allows you to generate code for any text language. Templates are written in Visual Studio as ASP.NET User Controls.

The current feature list of SmartCodeGenerator includes:

  • All development done in VS2005 OR VS2003 Extensible Template Generation Engine
  • Open source Database Schema discovery API for Microsoft SQL, Oracle and MySQL
  • Uses existing ASP.NET 2.0 website application OR ASP.NET 1.1 web application concepts
  • Generates text based output
  • Generates output in batch mode
  • Fully customizable template-based code generation
  • Remembers custom property data entries
  • Intellisense, compilation, debug, code snippet, source view, design view and all other countless features that are offered by Visual Studio

The entire development life cycle of creating custom templates using SmartCodeGenerator is done using Visual Studio by creating an ASP.NET application. And templates are ASP.NET UserControls, so during the generation of templates, intellisense, compilation, debug, source view, design view, code behind file and all other features of Visual Studio (2005 or 2003) are available to you.

For latest downloads please refer to Codeplex. This article is based on CTP 2.6 and is more of a usage guideline that tries to answer how to use SmartCodeGenerator for template based output. This demonstration will focus on using SCG with Visual Studio 2005, however, this framework can be used with any ASP.NET IDE that exists in the world today. You simply need to create an ASP.NET project, add a reference to the DLLs supplied with SCG. For an architectural overview of SCG framework please refer to this article at The Code Project, "SmartCodeGenerator - Code Generation experience with Visual Studio and ASP.NET- Architectural Overview".

Without any further delay let's explore SCG in more details.

Installing SmartCodeGenerator

Note: This article is based on CTP 2.6.0. For latest versions please refer to CodePlex.
Once you have downloaded the file (that comes as one zip file with this article) simply extract it to your favorite project directory. Here is a glimpse of what you will see when you extract the zip file.

Sample image
Fig 1

CSharp Developers extract the SCG_CTP2.6_CSharp_VsTemplate.zip file and copy SmartCodeGenerator.zip to your My Documents\Visual Studio 2005\Templates\ProjectTemplates folder. In addition copy SmartCodeGeneratorTemplate.zip to your My Documents\Visual Studio 2005\Templates\ItemTemplates folder. Here is a glimpse of the extracted SCG_CTP2.6_CSharp_VsTemplate.zip.

Sample image
Fig 2

VB.NET Developers extract SCG_CTP2.6_Vb_VsTemplate.zip and copy SmartCodeGeneratorVb.zip to your My Documents\Visual Studio 2005\Templates\ProjectTemplates folder. In addition copy SmartCodeGeneratorTemplateVb.zip to your My Documents\Visual Studio 2005\Templates\ItemTemplates folder.

Sample image
Fig 3

This is what it takes to install SmartCodeGenerator within Visual Studio 2005 and we are ready to create a SmartCodeGenerator project.

Creating SmartCodeGenerator Project

Lets open Visual Studio 2005 and create our first SmartCodeGenerator project. Click File > New > Web Site…

Sample image
Fig 4

You will notice SmartCodeGenerator Project Available. Select SmartCodeGenerator and click OK.

Sample image
Fig 5

This will automatically generate SmartCodeGenerator Project for you with the necessary files and project structure. A glimpse of the solution explorer is as follows.

Sample image
Fig 6

Please keep note of the TheProperties.cs, DefaultTemplate.ascx and Default.aspx files. These are the files which you have to modify to customize your template to meet your needs. You can run the project straight away and the output will look something like this.

Sample image
Fig 7

Note here the Custom property "TestProperty" and the "Generate" Button. Custom properties will be used to collect data from the end user and generated output will change based on these inputs. Generate Button generates the output.

Adding New Templates to the Project

To add a new template, right click on the Template Folder and click Add New Item.

Sample image
Fig 8

Choose SmartCodeGenerator Template and Click Add. This will add a new SCGTemplate in the Templates Folder.

Sample image
Fig 9

Modifying a Template

Double click the DefaultTemplate.ascx file and go to source view mode in Visual Studio 2005. You will see something like this.

Sample image
Fig 10

Note a template is nothing but a ASP.NET UserControl and you can start writing your template with static and dynamic bits and pieces, and codes in code behind file as if you would write in any ASP.NET application. And notice you have the intellisense, debug, code snippet and all other cool features of Visual Studio 2005 available to you while writing your templates.

Modifying TheProperties.cs

You should have already noticed the TestProperty with a textbox at runtime (Fig 7) and wondered where this is coming from. Please open up TheProperties.cs class.

"TheProperties" Class: is simply a .NET class and any properties that are defined in this class are automatically picked up by the SCG Framework and a relevant UI is generated to collect data from an end user. For example, I have defined a string property TestProperty.

Sample image
Fig 11

C#
public class TheProperties
{
  private string _testProperty;
  public string TestProperty
  {
    get
    {
      return _testProperty;
    }
    set
    {
      _testProperty = value;
    }
  }
}

The SCG Framework will automatically generate a UI for this property like this.


Sample image
Fig 12: Custom Property UI

Lets add a new property named AddedProperty of type string in the "TheProperties.cs" and the new code should looks like this.

C#
public class TheProperties
{
  private string _testProperty;
  public string TestProperty
  {
    get
    {
      return _testProperty;
    }
    set
    {
      _testProperty = value;
    }
  }
  private string _addedProperty;
  public string AddedProperty
  {
    get
    {
      return _addedProperty;
    }
    set
    {
      _addedProperty = value;
    }
  }
}

If you run this project now, you will see the following.

Sample image
Fig 13

Note: A textbox is automatically created for the new property we defined. You can also try adding other properties of int, Boolean etc. Out of the box SCG ships with support for Boolean, Enum, Integer, ScMandatoryStringProperty, ScSQLTablesProperty, StringCollection and String Type. The framework is extensible and adding support to any types you desire is very easy. You will find details about it in Team Blog ( http://www.community.smartcodegenerator.com )

Modifying Default.aspx.cs

When you run the project and click the Generate Button you see this line.

GeneratedCode for Template:~/Templates/DefaultTemplate.ascx 
                Output filename:c:\temp\Example1.cs 

You might be also wondering where it is defined to read from (DefaultTemplate.ascx) and write to (Example1.cs) as output. Please Open the Default.aspx.cs file and you will find the region "ToDo : Write/Modify Code As Required" with the following piece of code.

Sample image
Fig 14

SCG framework comes with the InputTemplateAndOutputPath Class where you can define an input location and an output location. So, your Templates folder may end up having 100s of templates but you can run your desired templates from this section. Simply add your required mappings to the list object (IOList) like I did in the above code. To add another input template named "Template2.ascx" and an output location of "c:\temp\Example2.cs" to the IOList you may do something like this

C#
InputTemplateAndOutputPath path2 =
  new InputTemplateAndOutputPath("~/Templates/Template2.ascx",
      @"c:\temp\Example2.cs");
this.IOList.Add(path2);

The SCG Framework also ships with ScEventArgs and object has an Item Property, which is in fact a Hashtable. So, you have the flexibility to pass any object and this will flow through the Generate (Output) pipeline. In the above code I am adding "report" in the Dictionary. For understanding Pipeline in more details, please refer to this article at The Code Project, "SmartCodeGenerator - Code Generation experience with Visual Studio and ASP.NET- Architectural Overview"

Sample image
Fig 15

The _Default_OnGenerate and _Default_OnGenerateComplete methods are worth having a look at.

C#
void _Default_OnGenerate(object sender, EventArgs e)
{
   GenerateFiles(IOList, e);
   SerializeThePropertiesToFile();
}
private void GenerateFiles(List<InputTemplateAndOutputPath> ioList,
  EventArgs e)
{
  //This is going to Loop through all the templates of
  //IOList for each TableSchemas
  foreach (InputTemplateAndOutputPath io in ioList)
  {
    //This part shows the use of ScEventArgs that is
    //passed in the pipeline
    string report = ((ScEventArgs)e).Item["report"].ToString();
    report = string.Format("{0} <BR>
      GeneratedCode for Template:{1} Output FileName:{2}",
         report, io.InputPathFilename, io.OutputPathFilename);
    ((ScEventArgs)e).Item["report"] = report;
    _Util.GenerateOutputAsFile(Page, io);
    //To Get GeneratedText use the following Method
    //string generatedText = _Util.GeneratedOutputAsText(Page, io);
  }
} 

The above code is self explanatory and I loop through the InputOutputTemplate list (IOList) and generate files by calling_Util.GenerateOutputAsFile method that comes with the SCG Framework. The "report" that we passed in the PreGenerate(....) function is extracted here and used to compile a report. The OnGenerateComple method extracts the "report" that is passed in the pipeline and shows it on the screen via lblReport.Text.

C#
void void _Default_OnGenerateComplete(object sender, EventArgs e)
{
   lblReport.Text = ((ScEventArgs)e).Item["report"].ToString();
}

In Short the pipeline has different events that you can hook codes into and they are executed in this sequence as shown in Fig 16.

Sample image
Fig 16

In the Default.aspx.cs I hooked up the following methods with the pipeline.

C#
void _Default_OnPreGenerate(object sender, EventArgs e)
void _Default_OnGenerate(object sender, EventArgs e)
void _Default_OnGenerateComplete(object sender, EventArgs e) 

What I did here within these methods are:

PreGenerate: I Prepared the List of InputOutputTemplate
OnGenerate: I Generated the File/Files
OnGenerateComplete: I Displayed the result on the screen...

The PipeLine is very powerful and you can pass any object via the Hashtable and use them at different stages of the execution. For more details please refer to this article at The Code Project, "SmartCodeGenerator - Code Generation experience with Visual Studio and ASP.NET- Architectural Overview".

From the above discussion we have learned how templates work in SmartCodeGenerator. Basically, we define properties in the TheProperties class section and that turns into UIProperty objects where we can enter desired values at runtime. We can enter as many properties as we wish. We can also map input template and output file using the InputTemplateAndOutputPath class and generate files in batch mode. We also learned that the default.aspx.cs acts as the host and hooks up different methods to the events in the pipeline.

Writing your First Template

Objective

We will write a template which will take two properties: classname and propertyname. Then, code will be generated like this based on the customized values entered for the properties.

C#
public class TestClass
{
  public TestClass()
  {
    //Add constructor here
  }
  private string testproperty
  public string TestProperty
  {
    get
    {
        return testproperty;
    }
    set
    {
        testproperty = value;
    }
  }
} 

Step 1 - Create a new SmartCodeGenerator Project

In Visual Studio 2005, Select File>New>Website>SmartCodeGenerator. You will notice (SmartCodeGenerator) Project Template in your (MyTemplates) Section.

Step 2 - Declare Properties in the "TheProperties" class

As defined in the objective we want to have 2 string properties one for classname and one for propertyname. So, we will define 2 properties in the "TheProperties" class. It should look somewhat like the following.

C#
public class TheProperties
{
    public TheProperties( )
    {
        //Please Assign Default Values here
        this.ClassName = "TestClass";
        this.PropertyName = "TestPropertyName";
    }
    private string className;
    public string ClassName
    {
        get { return className; }
        set { className = value; }
    }
    private string propertyName;

      public string PropertyName
      {
            get { return propertyName;}
            set { propertyName = value;}
      }
} 

We know the SCG framework will automatically read from the instance of TheProperties class, and will create required dynamic UIProperty on the webpage.

Step 3 - Add a new SCGTemplate

To add a new SCGTemplate right Click the Templates Folder of your Project and Click "Add New Item".

Select "SmartCodeGeneratorTemplate" and name this ascx File as "ExampleTemplate.ascx".

Step 4 – Modify SCGTemplate

Open the code behind file of ExampleTemlate.ascx and define a property TheClassName of type string:

C#
private string theclassname;
public string TheClassName
{
  get { return theclassname; }
  set { theclassname = value; }
}

Inside the PreGenerateTemplate( ) assign theclassname property to Profile.ScProperties.ClassName.

C#
public override void PreGenerateTemplateCode( )
{
   theclassname = TheProperties.ClassName;
} 

Go to the source view of your ExampleTemplate.ascx and modify as follows.

C#
<%@ Control Language="C#" AutoEventWireup="true"
  CodeFile="ExampleTemplate.ascx.cs" Inherits=" ExampleTemplate" %>
//This example Template shows creating a dynamic class from template

public class <%=this.TheClassName%>
{
  public <%=TheProperties.ClassName%>()
  {
     //Add constructor here
  }
  private string <%=TheProperties.PropertyName.ToLower()%>;
  public string <%=TheProperties.PropertyName %>
  {
      get
      {
        return <%=TheProperties.PropertyName.ToLower()%>;
      }
      set
      {
        <%=TheProperties.PropertyName.ToLower()%> = value;
      }
  }
}

Sample image
Fig 17

While doing this, you should have already noticed Intellisense support. In this demo we used both of these.TheClassName (which we have defined in our codebehind) and TheProperties.ClassName, just to show different ways of accessing UIProperty values.

Step 5- Modify Default.aspx.cs

Open the default.aspx.cs file. Go to region Todo : Write/Modify Code As Required Map the Input Template should be ExampleTemplate.ascx and Output file should be c:\temp\Example1.cs. It should look somewhat like this.

C#
void _Default_OnPreGenerate(object sender, EventArgs e)
{
  //You can use the handy IOList to Map Input Template and OutputPath
  this.IOList.Add(
    new InputTemplateAndOutputPath
      ("~/Templates/ExampleTemplate.ascx",
        @"c:\temp\Example1.cs"));
  //Adding a report item in the args
  ((ScEventArgs)e).Item.Add("report", string.Empty);
  lblReport.Text = string.Empty;
} 

Step 6 – Run the SCGProject and Generate output

After you run the project you will see something like this.

Sample image
Fig 18

Change the classname and propertyname as desired and click the generate button to generate the output. Other Example – Generating codes from Database Table Schema The CTP 2.6 also ships with full source code of database Schema Discovery API for Microsoft SQL, Oracle and MYSQL database. It also ships with an example "SCG_CTP2.6_DbSchema_Example_CSharp" which demonstrates how to generate templates depending on Database Table Schemas. Here is a glimpse of the template.

Sample image
Fig 19

Conclusion

SmartCodeGenerator is a very powerful code generation framework. Here it couples Visual Studio and ASP.NET. However, this framework can be used with any ASP.NET IDE that exists in the world today. You simply need to create an ASP.NET project, add a reference to the DLLs supplied with SCG. SCG also ships with Database Schema Discovery API's for Microsoft SQL Server, Oracle and MySQL, and implementing new providers for different databases is very easy. An SCG Project is simply a ASP.NET project and not dependent on any third party tools, and SCGTemplates are ascx UserControls. For a ASP.NET developer there is nothing new to learn to start using SmartCodeGenerator. I strongly believe that you will agree with me in saying: "Code Generation has never been this easy". Thank you for being with me so far and please join the community and share your SCGTemplates.

Resources and Links related to SmartCodeGenerator

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here