Codesmith quick wizard

Source: Internet
Author: User

The purpose of this document is to let you know how to use codesimth to generate the complete Program .
In this wizard, I plan to teach you how to use the templates provided by codesmith, create a template, and create a data
Library driver template.

Codesimth is a template-based Code Generate a tool. You can create and
Defines a template for generating code. One important thing you should know is that the Code produced by codesimth is text,
Therefore, you can use it to generate code or text in other languages that you do not need to write.

Before you can see how to create your own template, let's first use the template that comes with codesmith. You can use: Start-> Program->
Codesmith-> codesmith explorer to start codesmith explorer. The interface after startup is shown in:

Codesmith explorer is used to implement templates that you can use. The default sample templates are loaded. Many common templates are on the top of the set,
Double-click the ararraylist. CST template to open it, as shown in:

This is a template attribute panel. You can view and specify attributes of multiple templates. For the arraylist template, We need to specify
The name of arraylist and the type of item we want to store in arraylist. (You can also specify a namespace to use arraylist .)
In the example, we specify Carlist as classname, and car as itemtype. After adding the attribute, click Generate. The template will generate a strong type for you.
Arraylist.
(Note: My codesmith v 2.6 Professional version does not respond after I click Generate. You can go to codesmith studio for an interview)

The window on the right shows the output result after a strong arraylist template is generated for the car class,
Then you can copy and copy it to Visual Studio, or compile it in another editor you use.

(Note: My codesmith v 2.6 Professional version does not respond after I click Generate. You can go to codesmith studio .)
In the interview. Start> program> codesimith v2.6> codesmith studio,
On the right panel, expand collections-> double-click arraylist. CST and enter
The following properties panel contains the classname and itemtype values.->
Click Run in the toolbar (small triangle ))

Compile your first template
Codesmith is the most valuable compared with other code generation tools:
You can compile the code generation template for the code you need to generate. You can
Specifies how the code is generated, and even specifies the tabs and space in the code
Quantity. You have full control over your code output, and other tools are almost impossible to complete.
Such a function.

The tools you use to generate templates already have a bunch of different functions. If you are using the Personal Edition
Codesmith, you can use codesmith studio, which has a variety of codesmith
Template environment. If you have not used the Personal Edition or the trial has expired, you can use any text editing
To create your template.

Next we will create a simple template that accepts some strings and then creates
Class. This is a simple example, but it will show the basis for codesmith template creation. I found that designing a model
The best way to create a template is to first create the code that needs to output the result. The following is
Rong:

//////////////////////////////////////// //////////////////////////////////////// ///////
// File: myclass. CS
// Description: Enter summary here after generation.
//---------------------
// Copyright? 2003 our client
//---------------------
// History
// 11/30/2003 developer ''' name original version
//////////////////////////////////////// //////////////////////////////////////// ///////

Using system;

Namespace mynamespace
{
/// <Summary>
/// Summary description for myclass.
/// </Summary>
Public class myclass
{
Public myclass ()
{
//
// Todo: Add constructor logic here
//
}
}
}

This is the final result we want the template to generate, but we need to specify something when the template is run every time.
Now let's start writing templates.

Open a blank text file and add a codetemplate label to the file header.
The codetemplate label tells codesmith that this is a template file and the template is written in any language,
The language and description of the template. The following is a codetemplate label:
<% @ Codetemplate Language = "C #" targetlanguage = "C #"
Description = "generates a class including a special informational Header" %>

First, set the template language to C #, set the language generated by the template to C #, and then add the template description.
Some other attributes can be added to the tag, which will be replaced elsewhere in the document.

Then declare the variables required by the template during running. In this example, you want to specify the namespace name, class name, and
Developer name. The following are three attributes to be declared:

<% @ Property name = "namespace" type = "string"
Category = "context"
Description = "The namespace to use for this class" %>

<% @ Property name = "classname" type = "string"
Category = "context"
Description = "the name of the class to generate" %>

<% @ Property name = "canonical sname" type = "string"
Category = "context"
Description = "the name to include in the comment Header" %>

Each attribute tag includes the name attribute, which is used as a reference for the attribute values and attribute types in other places of the template.
We have set a category and description for each attribute, which can be used when the template is opened by codesmith.
Defines related attributes.

Modify the template text so that the text can be inserted to the correct position when the attribute is specified.
You can use a syntax and attribute name similar to ASP. NET for operations, such:
//////////////////////////////////////// //////////////////////////////////////// ///////
// File: <% = classname %>. CS

The value will be replaced by text, as you can say, the syntax is similar to Asp.net. We want to see the rest
And replace hard-coded with attribute names. All content of this instance template:
<% @ Codetemplate Language = "C #" targetlanguage = "C #"
Description = "generates a class including a special informational Header" %>

<% @ Property name = "namespace" type = "string"
Category = "context"
Description = "The namespace to use for this class" %>

<% @ Property name = "classname" type = "string"
Category = "context"
Description = "the name of the class to generate" %>

<% @ Property name = "canonical sname" type = "string"
Category = "context"
Description = "the name to include in the comment Header" %>

//////////////////////////////////////// //////////////////////////////////////// ///////
// File: <% = classname %>. CS
// Description: Enter summary here after generation.
//---------------------
// Copyright? <% = Datetime. Now. Year %> our client
//---------------------
// History
// <% = Datetime. Now. tow.datestring () %> <% = developersname %> original version
//////////////////////////////////////// //////////////////////////////////////// ///////

Using system;

Namespace <% = namespace %>
{
/// <Summary>
/// Summary description for <% = classname %>.
/// </Summary>
Public class <% = classname %>
{
Public <% = classname %> ()
{
//
// Todo: Add constructor logic here
//
}
}
}

As you can see, we applied the attributes we defined in several different places, and we also used
The datetime object shows us a time. Now we need to call
Run your codesmith explorer and click the folder icon to select the directory where the template file is located.
. You will see a list of all templates in the directory, and then double-click the template to load it. After the template is loaded, we can
View its attribute list on the panel,

We can see three declared attributes, including Category Description and description. After you click the generate button, codesmith uses
And the template code to generate the following content.

//////////////////////////////////////// //////////////////////////////////////// ///////
// File: myclass. CS
// Description: Enter summary here after generation.
//---------------------
// Copyright? 2003 our client
//---------------------
// History
// 12/2/2003 mr. smith Original Version
//////////////////////////////////////// //////////////////////////////////////// ///////

Using system;

Namespace mynamespace
{
/// <Summary>
/// Summary description for myclass.
/// </Summary>
Public class myclass
{
Public myclass ()
{
//
// Todo: Add constructor logic here
//
}
}
}

You can copy and paste the generated code to Visual Studio or other compilers you use, and then
Compile them.

This is the simplest example of what codesmith can do, but it lists some key points:
. The template should include a codetemplate statement;
. A template can have many attributes and declared attributes declared with attributes.
. Use Asp.net syntax to insert attribute values to the output template.
. The template is customized in 100%. You can use codesmith to generate any types of text.

However, the above example does not really show the powerful capabilities of codesmith.
We will see how to dynamically generate code based on database objects.

Compile a database-driven Template

Now we know how codesmith works with us,
Next we will learn how to generate what you may download the first thing codesmith wants to generate.
Data access logic may be the most redundant part of the program. You can
To automatically generate fairly formal data access layer code. The last chapter shows how
Write a simple template that supports parameters, but now we want to see how
You can use the schemaexplorer component of codesmith to write a template. Schemaexplorer
A component is an assembly that provides multiple classes that can be used to browse the content of your database.
By using the schemaexplorer component, you can browse tables, stored procedures, and obtain data.
Type, unique column, column name, and other information.

As an example of how to use schemaexplorer, we plan to write
Table columns automatically generate a stored procedure template. Before writing a template, we should write
We hope that the text content generated by the template can be used as the template's
Start. The following is the expected text:
-----------------------------------------------------------------
-- Date created: Thursday, December 04,200 3
-- Created by: generated by codesmith
-----------------------------------------------------------------

Create procedure DBO. updateorders
@ Orderid int,
@ Customerid nchar (5 ),
@ Employeeid int,
@ Orderdate datetime,
@ Requireddate datetime,
@ Shippeddate datetime,
@ Shipvia int,
@ Freight money,
@ Shipname nvarchar (40 ),
@ Shipaddress nvarchar (60 ),
@ Shipcity nvarchar (15 ),
@ Shipregion nvarchar (15 ),
@ Shippostalcode nvarchar (10 ),
@ Shipcountry nvarchar (15)
As

Update [orders] Set
[Customerid] = @ customerid,
[Employeeid] = @ employeeid,
[Orderdate] = @ orderdate,
[Requireddate] = @ requireddate,
[Shippeddate] = @ shippeddate,
[Shipvia] = @ shipvia,
[Freight] = @ freight,
[Shipname] = @ shipname,
[Shipaddress] = @ shipaddress,
[Shipcity] = @ shipcity,
[Shipregion] = @ shipregion,
[Shippostalcode] = @ shippostalcode,
[Shipcountry] = @ shipcountry
Where

[Orderid] = @ orderid

This is a stored procedure for updating the orders table of the northwind database, because it is
It is a very common stored procedure, so it is a good code generation model. Template category
The mark is to read information from the table and then automatically generate the corresponding stored procedure. Of course, it can be used
Other tables are not just tables.

First, create a codetemplate label in the template to describe the Template Name and description.
<% @ Codetemplate Language = "C #" targetlanguage = "T-SQL"
Description = "generates a update stored procedure." %>
Next we need to call the Assembly containing schemaexplorer, which is advantageous
To access the database through the Assembly tag.

<% @ Assembly name = "schemaexplorer" %>

We need to use the import label to import the namespace of schemaexplorer and load schemaexplorer
Assembly, so that we can access its class in the template,
<% @ Import namespace = "schemaexplorer" %>

Because we want to read data from the table, we need to add
A tableschema type attribute.
<% @ Property name = "sourcetable" type = "schemaexplorer. tableschema"
Category = "context"
Description = "table that the stored procedures shoshould be based on." %>

When we execute the template, this attribute allows us to select a database and table. We can refer to this attribute
To detect the table and create our template based on the table content and attributes.

Then start some template nodes that output text. The first node is the following visible file header.
-----------------------------------------------------------------
-- Date created: <% = datetime. Now. tolongdatestring () %>
-- Created by: generated by codesmith
-----------------------------------------------------------------
The code is similar to that in the last example. We use the datetime object to generate
Time. Then we need to create the first line of the stored procedure script:
Create procedure DBO. Update <% = sourcetable. name %>
In this row, we use the sourcetable name attribute defined earlier, which inserts
We are testing the table name, so in this example, because we correspond to the orders table
The stored procedure will be updateorders.

Next we will create a parameter list for the stored procedure, because we want to create an updated Storage
Each column name in the table is required as a parameter. Using tableschema objects, we can follow
The column in the ring table reads the column name and column data type, and uses the value to create our list.
<% For (INT I = 0; I <sourcetable. Columns. Count; I ++) {%>
<% = Getsqlparameterstatement (sourcetable. Columns [I]) %>
<% If (I <sourcetable. Columns. Count-1) {%>,< %} %>
<% }%>
As

Create an SQL statement for updating a table with parameters. Therefore, I need to recycle the
column set, but replace normal with nonprimarykeycolumns
columns. We do this because we only want to create columns for non-primary rows. We
use the primary key column in The where condition of the update statement.
Update [<% = sourcetable. name %>] Set
<% for (INT I = 0; I
[<% = sourcetable. nonprimarykeycolumns [I]. name %>] =@<%= sourcetable. nonprimarykeycolumns [I]. name %> <% if (I ,<%}%>
<%}%>

In the following statement, we want to create a set list. The list contains the column name and parameter name. below is
The text generated after codesmith execution:
Update [orders] Set
[Customerid] = @ customerid,
[Employeeid] = @ employeeid,
[Orderdate] = @ orderdate,
[Requireddate] = @ requireddate,
[Shippeddate] = @ shippeddate,
[Shipvia] = @ shipvia,
[Freight] = @ freight,
[Shipname] = @ shipname,
[Shipaddress] = @ shipaddress,
[Shipcity] = @ shipcity,
[Shipregion] = @ shipregion,
[Shippostalcode] = @ shippostalcode,
[Shipcountry] = @ shipcountry

In the last part of the template, We need to write the WHERE clause of the update statement.
The column loop is used again, but this time we cyclically from the main column in the table
To generate the WHERE clause.

Where
<% For (INT I = 0; I <sourcetable. primarykey. membercolumns. Count; I ++) {%>
<% If (I> 0) {%> and <%} %>
[<% = Sourcetable. primarykey. membercolumns [I]. name %>] = @
<% = Sourcetable. primarykey. membercolumns [I]. name %>
<% }%>

The text generated by codesmith is as follows:
Where

[Orderid] = @ orderid

The following is a complete template:
<% @ Codetemplate Language = "C #" targetlanguage = "T-SQL"
Description = "generates a update stored procedure." %>

<% @ Property name = "sourcetable" type = "schemaexplorer. tableschema"
Category = "context"
Description = "table that the stored procedures shoshould be based on." %>

<% @ Assembly name = "schemaexplorer" %>

<% @ Import namespace = "schemaexplorer" %>

<SCRIPT runat = "template">
Public String getsqlparameterstatement (columnschema column)
{
String Param = "@" + column. Name + "" + column. nativetype;

Switch (column. datatype)
{
Case dbtype. Decimal:
{
Param + = "(" + column. Precision + "," + column. Scale + ")";
Break;
}
Default:
{
If (column. size> 0)
{
Param + = "(" + column. Size + ")";
}
Break;
}
}

Return Param;
}
</SCRIPT>

-----------------------------------------------------------------
-- Date created: <% = datetime. Now. tolongdatestring () %>
-- Created by: generated by codesmith
-----------------------------------------------------------------

Create procedure DBO. Update <% = sourcetable. name %>
<% For (INT I = 0; I <sourcetable. Columns. Count; I ++) {%>
<% = Getsqlparameterstatement (sourcetable. Columns [I]) %> <% if (I <sourcetable. Columns. Count-1) {%>, <%} %>
<% }%>
As

Update [<% = sourcetable. name %>] Set
<% For (INT I = 0; I <sourcetable. nonprimarykeycolumns. Count; I ++) {%>
[<% = Sourcetable. nonprimarykeycolumns [I]. name %>] =@<%= sourcetable. nonprimarykeycolumns [I]. name %> <% if (I <sourcetable. nonprimarykeycolumns. count-1) {%>,<%}%>
<% }%>
Where
<% For (INT I = 0; I <sourcetable. primarykey. membercolumns. Count; I ++) {%>
<% If (I> 0) {%> and <%} %>
[<% = Sourcetable. primarykey. membercolumns [I]. name %>] = @ <% = sourcetable. primarykey. membercolumns [I]. name %>
<% }%>

When we load the template in codesmith, we can see the sourcetable attribute.
The attribute contains a button on the right. You can select a table to run the storage
Template generated by the process. The following is the border chart:

Click the button on the right to select a table. You can see that:
In the graph, you can configure your data source (select another data source by clicking the expand button ).
Databases ). Then select the table where you want the template to generate code. Select Table Point Generation
The following text will be generated:
-----------------------------------------------------------------
-- Date created: Saturday, December 06,200 3
-- Created by: generated by codesmith
-----------------------------------------------------------------

Create procedure DBO. updateorders
@ Orderid int,
@ Customerid nchar (5 ),
@ Employeeid int,
@ Orderdate datetime,
@ Requireddate datetime,
@ Shippeddate datetime,
@ Shipvia int,
@ Freight money,
@ Shipname nvarchar (40 ),
@ Shipaddress nvarchar (60 ),
@ Shipcity nvarchar (15 ),
@ Shipregion nvarchar (15 ),
@ Shippostalcode nvarchar (10 ),
@ Shipcountry nvarchar (15)
As

Update [orders] Set
[Customerid] = @ customerid,
[Employeeid] = @ employeeid,
[Orderdate] = @ orderdate,
[Requireddate] = @ requireddate,
[Shippeddate] = @ shippeddate,
[Shipvia] = @ shipvia,
[Freight] = @ freight,
[Shipname] = @ shipname,
[Shipaddress] = @ shipaddress,
[Shipcity] = @ shipcity,
[Shipregion] = @ shipregion,
[Shippostalcode] = @ shippostalcode,
[Shipcountry] = @ shipcountry
Where

[Orderid] = @ orderid

This template can generate any database table update stored procedures.
Conclusion
I sincerely hope this quick help will help you use codesmith
Enough information and examples. codesmith is a very powerful and time-saving tool,
I hope you can find more use in your project, just like we do.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.