posts - 217, comments - 218, trackbacks - 239

My Links

News




I am a Microsoft Certified Application Developer MCAD Chartered Member (C# .Net) and born in Bangladesh.
I work for Ocean Informatics Pty Ltd as a Senior Developer - Analyst.
I am also co-founder and core developer of Pageflakes (acquired by LiveUniverse) www.pageflakes.com
and most recently created SmartCodeGenerator

My Articles
Flexible and Plugin based .Net Application..
Mass Emailing Functionality with C#, .NET 2.0, and Microsoft® SQL Server 2005 Service Broker'
Write your own Code Generator or Template Engine in .NET
Smart Code Generator .NET: Usage Overview
Smart Code Generator .NET: Architectural Overview
Smart Code Generator .NET: using with NAnt and Cassini

Archives

Free Programming Language Training

Example 3: SmartCodeGenerator (asp.net 2.0) Writing your first template

Example 3 Writing your First Template

Objective

We will write a template which will take two properties classname and propertyname and generate code 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;

    }

  }

}

Step1. Installing VS2005 Project and Item Template for SmartCodeGenerator.

Make sure you copied the Visual Studio 2005 Project Templates for SmartCodeGenerator in 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.

Step2. Create a New SmartCodeGenerator Project

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

Step3.Declare Properties in Profile Section.

Here we want to have 2 string properties one for classname and one for propertyname. Se we will define 2 properties in the profile -- "ScProperties" group. The framework will read from ScProperties and profile properties that require dynamic UIProperty needs to be declared under "ScProperties" group.

It should look something like the following. (alternatively compare with web.config of the Example3)

<profile defaultProvider="TextFileProfileProvider">

      <properties>

        <group name ="ScProperties">

          <add name="ClassName" type="string" defaultValue="TestClass"/>

          <add name="PropertyName" type="string" defaultValue="TestProperty"/>

        </group>

      </properties>

Step4.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"

Step5.Write Codebehind codes for your Template

Define property

private string theclassname;

public string TheClassName

    {

get { return theclassname; }

set { theclassname = value; }

    }

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

public override void PreGenerateTemplateCode( )

    {

        theclassname = Profile.ScProperties.ClassName;

    }

go to source view of your example3Template.ascx and write a template as followings. 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 <%=Profile.ScProperties.ClassName%>()

  {

    //Add constructor here

  }

  private string <%=Profile.ScProperties.PropertyName.ToLower()%>;

  public string <%=Profile.ScProperties.PropertyName %>

  {

    get

    {

        return <%=Profile.ScProperties.PropertyName.ToLower()%>;

    }

    set

    {

<%=Profile.ScProperties.PropertyName.ToLower()%> = value;

    }

  }

}

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

Step6. Finally Generate The Output

Open the default.aspx.cs file.

Go to region Todo : Write/Modify Code As Required

Map 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 has a Item Property, which is infact a Dictionary<string,object>. So you have the flexibility to pass anyobject and is flowed through 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);

        }

     }

The above code is self explanatory and 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 prevous method in the pipeline and shown in 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 Dictionary<string,object> and use them in different stage of the execution.

Step7. Run the Project and Click the Generate Button

If there is any compilation error Visual Studio should pick it up and you can fix them easily. Remember you are writing an Asp.net webpage. So from the compilation and running point nothing new to learn here.

Print | posted on Saturday, November 25, 2006 10:12 AM |

Feedback

No comments posted yet.

Post Comment

Title  
Name  
Email
Url
Comment   
Please add 4 and 4 and type the answer here:

Powered by: