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

Yet Another Code Generator Templates

4.85/5 (10 votes)
7 Jun 2010CPOL9 min read 1   417  
YACGen template construction introduction

Image 1

Introduction

This is the second Yet Another Code Generator (YACGen) article. The first article gave a basic introduction of what YACGen does, an overview of schema creation and generating output. This article will cover basic template generation. The download includes the following sample templates used throughout the article.

TemplateDescription
BasicObjectsCS.tldBasic C# representing a table object with properties
BuildHTMLTable.tldOutput table structure into HTML table
BuildHTMLTableB.tldOutput table structure into HTML table
BuildBasicGridView.tldBuild a ASP.Net gridview with only fields flagged in YACGen schema
BuildBasicGridViewCS.tldBuild gridview page C# code-behind file

There are corresponding .grp generation files for each template. These files assume the templates are located in C:\Program Files\YACGEN\Templates. You should be running YACGen release 2008.7.17 Beta 1.

Template Design

YACGen is a database schema driven code generator. It builds output based on codeless templates. The templates are similar to a report generator layout, with bands of logic and headers and footer. The difference being YACGen generates output based on a database layout.

The first example creates a template to output table properties to a HTML document similar to the following layout:

YacgenTemplate0.jpg

To create the template:

  1. Move to the Template Layout tab
  2. Select New Template File from the toolbar .

You are now ready to create your template. The highest level (root) gives you the option of post and pre template boxes. The contents of these two text boxes will appear at the beginning and end of the output document.

To save typing the appropriate sections are copied and pasted from the HTML file mocked up in an editor. Using this approach the bulk of the page can be copied and pasted and the appropriate schema properties inserted where required. The header section is pasted in the pre template text box and the closing HTML tags are placed in the post template text box.

There are a few properties that need replacing. The table name will appear as the document title as well as a header line. To insert a property, either type it or double click on the appropriate property from the properties list that appears when you enter a text box. Properties as surrounded by a <# and #> sequence. When you enter a template box a floating property list will appear:

YacgenTemplatesProp.jpg

Double click on any property in the list to insert the property. (Note: this is not a complete list.) The result will look something like this:

YacgenTemplate1.jpg

You can now add one or more sections. A section is a grouping of fields. The output fields are determined by the logic in the section. If no detail logic is supplied (see further in article on how to create conditional logic) output is generated for all fields for that section. You may have as many sections as you want.

The following image shows section row generation logic:

YacgenTemplate2.jpg

You can also drag sections to reorder or move them.

This next sample template is called BuildHTMLTable.tld in the included file. The file BuildHTMLTable.gpr will build output for all tables for the Northwind database.

In the first example all fields were output. Depending on what you are generating, you may only want to output a selection of fields. For example, for one section you may only want primary key fields, while in another section you may have different output depending on a field's data type.

To control the output, you may add conditional detail. Select the section to add the detail to and select the Add Detail toolbar button.

YacgenTemplate3.jpg

You can add as many conditional sections you want. The controls are described as follows:

LevelProcess level. If you require multiple steps then create additional levels.
DescriptionCondition description
Data TypeAny Data Type, specific data groupings such as String, Decimal, Integer, Date or specific database data types
Field TypeAll fields, all fields except primary keys, primary keys only and foreign keys only

The Conditions list provides an additional level of control. You can add as many conditional expressions as you wish within this box. Conditions are split into 3 columns: Property, Operator and Value.

Property represents a YACGen schema value. Operator represents a comparison operator, such as equal, great than or less than. Value is the value you are comparing against.

Below the list of conditions is the actual template. The template contents will be processed and output if all the conditions are met. If you are using conditions the section detail template is ignored.

By default all conditions in the condition list have to be met (and operation) to process the template. If you wish to perform an or operation, where the output is generated if only one or more of the conditions are met, click the Or checkbox. There is also an Empty Output checkbox. If you select this no output will be generated if all conditions are met. This is useful for conditions you wish to ignore.

The sections are evaluated in the order they are added. To minimize logic it is usually best to start with conditions that generate no output, then general logic and finish off with logic with no conditions (i.e. process everything) to catch anything the preceding levels missed. You can drag conditions to reorder as needed and use Ctrl+drag to make a copy of a condition.

In the first example, all fields were output into a formatted table. The length is output, even for image, currency and integer values where it isn't that useful. So the first condition would output all columns except width for currency, date, image and large text objects:

YacgenTemplate4.jpg

The second condition would output all columns for any remaining fields that didn't get processed in the first condition:

YacgenTemplate5.jpg

There is also a condition grid on the sections level. These conditions can be used to control if certain sections are processed.

Expressions

As we have seen, anything within the <# and #> sequence are evaluated by the template engine. YACGen can also return content based on conditions within the template layout itself. The expression syntax is <#Expresion\|\true value\|\false#>

The expression can be any Boolean YACGen property or a Python expression of the form <#Flag1 == "True"\|\Flag1 is set \|\Flag1 is set#>. (Note that Python expressions are case sensitive.) YACGen Boolean properties include IsPrimaryKey, IsForeignKey, IsVirtualField, IS_NULLABLE and ISIDENTITY. Other YACGen properties are stored as strings. For example: <#IS_NULLABLE\|\this field can store null values\|\this field doesn't store null values#>

The expression can span multiple lines in the template. If the second (false) evaluation string isn't specified, a blank string is returned if the expression evaluates to false. The following example demonstrates code generating a C# Integer variable declaration, with a question mark returned if the field is nullable.

YacgenTemplate7.jpg

YACGen includes the generic repetition operator REP. The REP operator simply repeats the sequence following REP while there are still fields to be processed for the current condition. For example, the following condition would return all primary key fields separated by a comma:

YacgenTemplate6.jpg

In addition, YACGen has a special property OrdinalMatched which is a counter that increases for every condition matched. as well as a number of flags that can be used to control template output. For example, you may wish to control what fields appear in a grid. In the field property page you can set up to 15 flags for each field as follows:

YacgenTemplate8.jpg

The pages generated require a data source to be defined in the Web.Config file. The data source name is populated using the database schema's Data Source Name property. To create a valid C# ASP.NET page you need the aspx and corresponding aspx.cs file. The included BuildBasicGridView.tld and BuildBasicGridViewCS.tld files builds the aspx file with a data source, select statement and gridview only with the columns specified by the Flag1 as well as the page code behind file.

YacgenTemplate9.jpg

YACGen Properties

One way of determining a property name is hovering over a value on the appropriate field and the control's tool tip showing the property name will appear. The majority of properties have suggested names, but you don't have to store formatting information in the Format property.

The following tables list available YACGen properties. They are grouped according to the object they apply to.

Field Properties

Property NameDescriptionExample
NETDataType Int32
FixedName  
FKTFieldName  
  
FKTNetDataType  
FTKEY  
KeyType  
FKTABLE_NAME  
AssociationType  
IsAssociation  
FKTABLE_ALIAS  
FKPopulateLocal  
FKPopulateLocalField  
FKTFieldNameAlias  
FKDirectStatement  
FKSelectMethod  
Width 10
AltFieldName Category ID
Description  
Format, Format2, Format3  
Index True, False
Validation1,Validation2  
Validation2  
ValidationMessage  
Message  
FKDataSource  
MultiLine,MultiLine2,MultiLine3 True, False
CharWidth, CharWidth2,CharWidth3  
CharRows, CharRows2,CharRows3  
PixelWidth,PixelWidth2
PixelWidth3
  
PixelHeight,PixelHeight2
PixelHeight3
  
Custom1-4  
Snippet1-2  
DefaultValue  
DefaultEmptyString False
XCoord-3 0
YCoord-3 0
Flag1-15 True, False
FKDropDownEmptyMessage  
TabStop  
ControlType  
COLUMN_NAMEDatabase field nameCategoryID
ORDINAL_POSITIONDatbase position1
DATA_TYPEDatabase data typeint
CHARACTER_MAXIMUM_LENGTHDatabase field length 
NUMERIC_PRECISION 10
NUMERIC_SCALE 0
COLLATION_NAME  
COLUMN_DEFAULT  
IS_NULLABLE Boolean value. True, False
ISIDENTITY Boolean value. True, False
ProperNETDataType Int32
BaseDataType Integer, Double, DateTime
GenericType int
Ordinal 0
lastFieldLast field in current condition?True, False
IsPrimaryKey Boolean value. True, False
IsForeignKey Boolean value. True, False
IsVirtualField Boolean value. True, False
Ignore Boolean value. True, False

Database Properties

Property NameDescriptionExample
DataSourceName   
DBConnectionString  
ServerName  

Output Generation Properties

A first chance exception of type System.NullReferenceException occurred in C3I.CodegenTools.dll
Property NameDescriptionExample
TemplateFile C:\Program Files\YACGEN\Templates\TableSPs.tld
OutputDirectory C:\Program Files\YACGEN\Output\
OutputLanguage C#
DatabaseFile C:\Program Files\YACGEN\Templates\northwind.dbd
DatabaseName Northwind
TableName Categories
Namespace  
OutputFile Category.txt
AuthorName Stein Borge
Modified  
NameSpace  
Assembly  
ShortDateTime  
LongDateTime  
ClassName   
ConnectionString  
Trademark  
Company  
FileVersion  
Version  
ShortTime 11:23 AM
ProcessDetermines what to processAll Tables, All Views, Single Table or View, All Tables and Views

Table Properties

Property NameDescriptionExample
TableAltName  
TableAltNameB Categories
SelectSQL  
TableFlag1-10 String value. True or False
TableMessage1-4  
TableComment1  
SQLSelectFields  
SQLFromStatement  
AllFieldsNoKeysCurrent fields without key field separated by commastring CategoryName,string Description,Byte[] Picture
AllFieldsAll fields separated by commasInt32 CategoryID,string CategoryName,string Description,Byte[] Picture
AllKeysAll key fields separated by commasInt32 CategoryID
LongDate Tuesday, July 15, 2008
ShortDate 7/15/2008
LongTime 11:23:02 AM
ShortTime 4:39 PM
FieldCount 4
FieldWidth 8

History

July 17th 2008. First release

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)