SmartCodeGenerator Quick start v2.0

Author: Shahed Khan, Last Updated: 1 December 2006.
Note this tutorial is based on CTP 2.0
http://www.codeplex.com/smartcodegenerator/Release/ProjectReleases.aspx?ReleaseId=1181

Table of Contents

 

SmartCodeGenerator Quick start v2.0. 1

Table of Contents 1

Introduction. 2

Example 1: Getting familiar with SmartCodeGenerator 3

Step 1 – Opening an Existing Template. 3

Step 2 - Launching the Generator 3

Step 3 - Generating the Text or Code. 4

Step 4 - Reviewing the Template. 4

Example 2: Generating Code from an existing project/template. 6

Step 1 – Opening an Existing Template, Launching and Generating Code. 6

Step 2 - Launching the Generator 6

Step 3 - Generating the Text or Code. 7

Step 4 - Reviewing the Template. 7

Step 5 - Understanding the role of the “TheProperties” class in the SmartCodeGenerator Framework  10

Step 6 - Understanding the “Generate” PipeLine and the InputTemplateAndOutPutPath Class 11

Step 7 - Summary. 12

Example 3: Writing your First Template. 13

Step 1 – Installing the VS2005 Project and Item Template for SmartCodeGenerator 13

Step 2 - Create a New SmartCodeGenerator Project 14

Step 3 - Declare Properties in the “TheProperties” class 14

Step 4 - Adding a new SmartCodeGeneratorTemplate. 15

Step 5 - Write Codebehind code for your Template. 15

Step 6 - Finally Generate The Output 17

Step 7 - Run the Project and Click the Generate Button. 18

Example 4: Generating a Class from SqlServer TableSchema. 19

Step 1 - Opening Existing Template. 19

Step 2 - Launching the Generator 19

Step 3 - Generating the Text or Code. 21

Step 4 - Review the Generated Code. 22

Step 5 - Review the Profile section in web.config. 23

 


Introduction

 

SmartCodeGenerator is an ASP.NET 2.0 website OR an ASP.NET 1.1 web application and is a fully-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 code generation process can be dynamically customised by using properties. The SmartCodeGenerator Framework generates UIProperty objects in the web page by reading the customised. The UIProperty objects are custom User Interface objects which are created based on the property types of a defined class.

 

You can define any.NET Object Type as properties of the “TheProperties” class in the project. Each property type in the “TheProperties” class is then mapped to a UIProperty object. At this stage it supports common types such as string, int, boolean and a ScTableSchema type (which represents the SQL Server database table schema). However, the SmartCodeGenerator Framework is extensible and UIProperty objects for any .NET types are easily written.

 

The SmartCodeGenerator Project is simply an ASP.NET website project, and the SmartCodeGenerator Templates are ASP.NET User Controls, so there is no need to learn any new technologies. Code is written as you would normally write for an ASP.NET application.

 

The current feature list of SmartCodeGenerator includes:

 

  • All development done in VS2005 OR VS2003.
  • Extensible Template Generation Engine.
  • SQL Server schema discovery API
  • Uses existing ASP.NET 2.0 website application OR ASP.NET 1.1 web application concepts
  • Generates text based output
  • Fully customisable template-based code generation

 

 

The entire development life cycle of creating custom templates using SmartCodeGenerator is done using Visual Studio by creating an ASP.NET application. So during the generation of templates, intellisense, compilation, debug, sourceview, designview, codebehind file and all other features of Visual Stution (2005 or 2003) are available to you.

 

 

This document refers to the examples that are supplied with SmartCodeGenerator. If you have not downloaded the examples yet, please download them now from CodePlex.


Example 1: Getting familiar with SmartCodeGenerator

Generating code from existing project/template


Note this tutorial is based on CTP 2.0
http://www.codeplex.com/smartcodegenerator/Release/ProjectReleases.aspx?ReleaseId=1181


Step 1 – Opening an Existing Template

Open Example1 from the Example_Projects folder, as a website project in Visual Studio 2005.

 

Step 2 - Launching the Generator

 

Run the project you have opened from Visual Studio 2005 and this will display the default.aspx page.

 

 

Notice the property1 and its textbox for entering a value. Properties such as this let you customise the generated code. Here, we are collecting a value for property1 and this can be used in the generated template.

 

Step 3 - Generating the Text or Code

Simply click the Generate Button. This will generate the code for you. If there were any compilation errors, Visual Studio 2005 would have picked that up very easily as it normally does for your ASP.NET applications.

 

 

 

Step 4 - Reviewing the Template

Expand the Template Folder and open Example1Template.ascx file and go to the source view. This should look similar to below.



And the Code Behind is where I have declared a property CurrentDateTime.


 

The Generated Code should look like this. The DateTime.Now.ToString() is simply replaced by the current datetime.


 

 

Remember, you have full access to the features of the Visual Studio 2005 Environment [Debugging, Compilation, CodeSnippet and countless others]

 


Example 2: Generating Code from an existing project/template

Getting familiar with the Asp.Net Profile object

 

Step 1 – Opening an Existing Template, Launching and Generating Code

Open Example2 from the Example_Projects folder, as a website project in Visual Studio 2005.

 

Step 2 - Launching the Generator

Run the project you have opened from Visual Studio 2005 and this will display the default.aspx page.

 

 

Notice the ClassName property and its textbox for entering a value. Properties such as this let you customise the generated code. Here we are collecting a value for ClassName and this can be used in the generated template.

 

Step 3 - Generating the Text or Code

Simply click the Generate Button. This will generate the code for you. If there were any compilation errors, Visual Studio 2005 would have picked that up very easily as it normally does for your ASP.NET applications.

 

 

 

Step 4 - Reviewing the Template

Expand the Template Folder and open Example2Template.ascx file and go to the source view. This should look similar to below.






The Code Behind is where I have declared a public property TheClassName. I have also assigned the TheProperties.ClassName to theclassname in the PreGenerateTemplateCode() method. [I will discuss this further, soon].





 

The Generated Code should look like this.


 

Step 5 - Understanding the role of the “TheProperties” class in the SmartCodeGenerator Framework

 

In Step 3, you might have already noticed the ClassName Property at runtime and are wondering where this is coming from.

 

This is a snippet of the TheProperties Class:


public class TheProperties

{

 

    public TheProperties( )

    {

        //Please Assign Default Values here       

        this.ClassName = "TestClass";       

    }

 

    private string className;

 

    public string ClassName

    {

        get { return className; }

        set { className = value; }

    }

}

 

The SmartCodeGenerator framework checks the properties of TheProperties class and automatically creates UIProperty for you. In this case, it created the ClassName based on the declaration in the TheProperties class. Also notice the defaultvalue is assigned in the constructor.

 

As you may have guessed, if you add more properties in your TheProperties class, the framework will also pick them up and generate a UIProperty object for you. Initially up to CTP1.1 I used ASP.NET Profile object but when I wanted to provide support for .Net1.1 I realized I cannot use it. Then I introduced this TheProperties class and this also has Intellisense support, so when we write our templates, this will be very helpful. Also, it acts as a Global variable and can be accessed from anywhere in the website project [in our case we can use it easily in our template]. Check the Example2Template.ascx (source view) and Example2Template.ascx.cs and you can see how the properties of TheProperties class are accessed easily.

 

Note: The communitydrop1 at this stage only supports UIProperty for the following types: string, integer, boolean and SmartCodeGen.WebUtil.PropTypes.ScSqlTablesProperty

The framework is extensible and adding support to any types you desire is very easy. I’ll discuss that in a separate tutorial.

 

Step 6 - Understanding the “Generate” PipeLine and the InputTemplateAndOutPutPath Class

 

You might be also wondering where we are are defining read from (Example2Template.aspx) and write to (Example2.cs) as output. Open the Default.aspx.cs file and you will find the region ToDo : Write/Modify Code As Required.

 

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/Example2Template.ascx", @"c:\temp\Example2.cs"));

        //Adding a report item in the args

        ((ScEventArgs)e).Item.Add("report", string.Empty);

        lblReport.Text = string.Empty;

}

Notice the 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 it to the list object (IOList) like I did here.

 

 

You may have also noticed this 3 methods in the region Todo : Write/Modify Code As Required

 

void _Default_OnPreGenerate(object sender, EventArgs e)

    

void _Default_OnGenerate(object sender, EventArgs e)

 

void _Default_OnGenerateComplete(object sender, EventArgs e)

 

 

As the name suggests, it executes in this order : PreGenerate => Generate => GenerateComplete

So, you can insert bits and pieces before Generate => OnGenerate and After Generate. These methods will always be called.

 

What I did here is:

 

PreGenerate: I Prepared the List of InputOutputTemplate

OnGenerate: I Generated the File/Files

OnGenerateComplete: I Displayed the result in the screen...

 

Easy, isn’t it?

 

I have also used ScEventArgs and _Util.xxx in this example and I’ll explain them in my next example.

 

Step 7 - Summary

 

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. However, at this stage we can only use limited types, but the framework is 100% extensible and support for other types can be introduced very easily.

 

We can map input and output and generate files. The default.aspx contains methods...

 

1. void _Default_OnPreGenerate(object sender, EventArgs e)

2. void _Default_OnGenerate(object sender, EventArgs e)

3. void _Default_OnGenerateComplete(object sender, EventArgs e)

and these are executed in this order (1->2->3).

 


Example 3: 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.

public class TestClass

{

  public TestClass()

  {

    //Add constructor here

  }

  private string testproperty

  public string TestProperty 

  {

    get

    {

        return testproperty;

    }

    set

    {

        testproperty = value;

    }

  }

}

 

Step 1 – Installing the VS2005 Project and Item Template for SmartCodeGenerator


Make sure you have copied the Visual Studio 2005 Project Templates for SmartCodeGenerator to your computer.


Copy SmartCodeGenerator.zip to your My Documents\Visual Studio 2005\Templates\ProjectTemplates folder.


Copy SmartCodeGeneratorTemplate.zip to your My Documents\Visual Studio 2005\Templates\ItemTemplates folder.

 

Step 2 - 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 3 - Declare Properties in the “TheProperties” class

 

Here, we want to have 2 string properties one for classname and one for propertyname. So, we will define 2 properties in the “TheProperties” class. The framework will automatically read from the instance of TheProperties class, and will create required dynamic UIProperty in the webpage.

It should look something like the following.

 

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;}

      }

}

 

 

 

Step 4 - Adding a new SmartCodeGeneratorTemplate

 

Right Click the Templates Folder of your Project and Click "Add New Item".

Choose "SmartCodeGeneratorTemplate". Name this ascx File as "Example3Template.ascx".

 

 

Step 5 - Write Codebehind code for your Template


Define a property:

 

private string theclassname;

 

    public string TheClassName

    {

        get { return theclassname; }

        set { theclassname = value; }

    }

 

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

 

public override void PreGenerateTemplateCode( )

{

   theclassname = TheProperties.ClassName;

}

 

Go to the source view of your Example3Template.ascx and write a template as follows. While doing this, you should have already noticed Intellisense support.




 

<%@ Control Language="C#" AutoEventWireup="true" CodeFile="Example3Template.ascx.cs" Inherits="Templates_Example3Template" %>

 

//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;

    }

  }

}

 

Notice, I have used both this.TheClassName (which we have defined in our codebehind) and also TheProperties.ClassName, just to show different ways of accessing UIProperty values. I used propertyname directly from the Profile object.

 

Step 6 - Finally Generate The Output

 

Open the default.aspx.cs file.

 

Go to region Todo : Write/Modify Code As Required

 

Map the Input Template and Output file here.

 

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/Example3Template.ascx", @"c:\temp\Example3.cs"));

        //Adding a report item in the args

        ((ScEventArgs)e).Item.Add("report", string.Empty);

        lblReport.Text = string.Empty;

    }

 

Notice the ScEventArgs. This comes with the Framework and this args 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 to OnGenerate and OnGenerateComplete. In the above code I am adding "report" in the Dictionary.

 

Notice what is done in the following 2 methods.

 

void _Default_OnGenerate(object sender, EventArgs e)

{       

   GenerateFiles(IOList, e);

}

 

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);

        }

}

 

Here we loop through the InputOutputTemplate list (IOList) and generate files by calling _Util.GenerateOutputAsFile method that comes with the SmartCodeGenerator Framework. The "report" that we passed in the PreGenerate(....) function is extracted here and used to compile a report.

 

Now, notice the OnGenerateComple method. Here we extract the "report" that is passed from the previous method in the pipeline and shown on the screen via lblReport.Text.

 

void _Default_OnGenerateComplete(object sender, EventArgs e)

{       

   lblReport.Text = ((ScEventArgs)e).Item["report"].ToString();       

}

 

The PipeLine is very powerful and you can pass any object via the Hashtable and use them at different stages of the execution.

 

Step 7 - Run the Project and Click the Generate Button

 

If there are any compilation errors Visual Studio will pick them up, and then you will need to repair these issues. Remember, you are writing an ASP.NET webpage, so from the compilation and running point of view, there is nothing new to learn.

 


Example 4: Generating a Class from SqlServer TableSchema

 

Step 1 - Opening Existing Template

Open Example4 from the Example_Projects folder, as a website project in Visual Studio 2005.