[Go] Bill: How to generate code in bulk using Codesmith

Source: Internet
Author: User
Tags powerdesigner

This article transferred from: http://www.cnblogs.com/huangcong/archive/2010/06/14/1758201.html

In the previous article we have created the required test database with PowerDesigner, and we can begin to use it to complete the batch code generation work.

Below I will step by step explain how to achieve the expected results with Codesmith, in advance to declare, in this only a simple demo, not detailed explanation codesmith each powerful function, Interested friends can open Codesmith's help documentation to learn about it. I just want to make a start, hoping to stir up the spark of more thoughts.

Let's see how Codesmith works:

Simply put: Codesmith first will go to the database to obtain the structure of the database, such as the name of the table, table fields, the relationship between the table and so on, then according to the user-defined template file, the database structure of the key words to replace the template dynamic variables, the final output and save as we need the target file. Okay, When the principle is clear, start practicing:

1. Run Codesmith, you can see the following interface:

2. Codesmith is the place to create a template, first of all, of course, create a template, click on the toolbar leftmost New Document-C # Template,:

3. Click the Run button to run the following results:

OK, let's analyze why we get this result, click the template button in the lower left corner of the run window to return to the Templates design window, you can find that as long as it is not <%%> or <scriptrunat= " Template "></script> contains the text is directly output, these will be replaced by some of our layered schema in some of the immutable template code:

4. Ok, simple to understand some of the Codesmith code structure, and then began to use it to generate our layered code, I do not introduce the concept of hierarchical architecture, or deviate from the topic. For a more straightforward explanation, We'll just use codesmith to create a layered layer of layers. Let's see what code we need to manually knock out if we don't use Codesmith:

Major.cs

Using System;
Using System.Collections.Generic;
Using System.Linq;
Using System.Text;

Namespace Entity
{
Publicpartialclass Major
{
PublicInt32 majorid{Get;set;}
Publicstring name{Get;set;}
Publicstring remark{Get;set;}
}
}

Student.cs

Using System;
Using System.Collections.Generic;
Using System.Linq;
Using System.Text;

Namespace Entity
{
Publicpartialclass Student
{
Publicstring studentid{Get;set;}
PublicInt32 majorid{Get;set;}
Publicstring name{Get;set;}
Publicboolean sex{Get;set;}
PublicInt32 age{Get;set;}
Publicstring remark{Get;set;}
}
}

I deepened the duplicated code in the two files using the yellow background color, and we can see that if each table is to be created manually, there will be a lot of code (yellow background) that requires a copy-and-paste operation, which is tedious and meaningless. So we'll want to make the code of the yellow background part a template, Other changes in the code are generated dynamically by the structure of the database, so that we no longer have to be annoyed about these annoying copy-and-paste operations.

5. Let's start with our practice, just start with the file you just created, go ahead and save it to a directory, name it test.cst, delete the extra code, keep the first line, the line that shows what language our template uses, and here we use C #.

<%@ codetemplatelanguage= "C #" targetlanguage= "Text" src= "" inherits= "" debug= "False" compilerversion= "v3.5" description= "Template Description here." %>

6. Referring to how Codesmith works, we will first provide a database for codesmith, how can it be associated with SQL Server 2005? Just add the following code:

<%--loads the component Schemaexplorer that accesses the database and declares its use of the namespace--%>
<%@ assemblyname= "Schemaexplorer"%>
<%@ importnamespace= "Schemaexplorer"%>

<%--Database--%>
<%@ propertyname= "SourceDatabase" deepload= "True" optional= "False" category= "01. Gettingstarted-required "description=" Database that the tables views, and StoredProcedures should is based on. IMPORTANT!!! If sourcetables and Sourceviews areleft blank, the entire Database would then be generated. " %>

7. OK, with the database connection, and then a template, in order to facilitate management, we create a new file for the design template,file-new-Blanktemplate, and add the following code, it is best to save to In the folder where test.cst is located, named ENTITY.CST:

<%@ codetemplateinherits= "Codetemplate" targetlanguage= "Text" description= "nettiers main template." Debug= "True" responseencoding= "UTF-8"%>

<%@ assemblyname= "Schemaexplorer"%>
<%@ importnamespace= "Schemaexplorer"%>

<%--the table to be printed--%>
<%@ propertyname= "Table" deepload= "True" optional= "False" category= "01. Getting started-required "description=" Database that the tables views, and stored procedures shouldbe based on. IMPORTANT!!! If Sourcetables and Sourceviews is left blank, Theentire Database would then be generated. "%>

Then continue to add the following code:

Using System;
Using System.Collections.Generic;
Using System.Linq;
Using System.Text;

Namespace Entity
{
publicpartialclass<%= table.name%>
{
<%foreach (Columnschema col intable.columns) {%>
public<%= Col. DataType%><%=col. Name%>{Get;set;}
<%}%>
}
}

<%=Table.Name%> represents the name of the output table here

<%foreach (Columnschema col in table.columns) {%> <%}%> is a looping statement that outputs column information in {}.

<%=col. DataType%> indicates the type of column to output here

<%=col. Name%> indicates the names of the columns to output here

:

8. After the template is created, to register in the TEST.CST file, how else would they know that you have such a template exists Ah, in the TEST.CST file continue to enter the following code:

<%--registering Entity Layer entities Template--%>
<%@ registername= "Entitytemplate" template= "ENTITY.CST" mergeproperties= "flase" excludeproperties= ""%>

9. Ok, the template is registered well, according to Codesmith work principle, we want to combine the template and database structure to generate code in bulk, but we generate the target file to output where? We will need a user-defined property to set the output directory of the target file. Enter the following code at the end of the TEST.CST file:

Code

10. Now even the output directory has, should find a way to write some functions to complete the database schema to pass the work of the template, at the end of the Test.cst file, enter the following code:

Code

Codetemplatetemplate = new Entitytemplate (); is to create a new template.

foreach (tableschematable in this. Sourcedatabase.tables) {} represents a table in a looping output database

Template.setproperty ("table", table); is to set a property to the template, remember that we set a table property in the ENTITY.CST, which is how we value this property.

Template.rendertofile (filedirectory,true); Indicates that the contents of the temlate are all output to the FileDirectory directory, true if the file has a direct overwrite.

11. Function write well, not far from success, we add the following code at the end of the TEST.CST to invoke the function that was just written. The template file has been created.

<%
To create a solid layer entity class
This. Generateentityclasses ();

Debug.WriteLine ("OK");
%>

12. OK, now just set up the database and output directory we want to export to run to see the results, click on the Codesmith main form in the lower right corner of the properities panel SourceDatabase property Bar to the right of ... button to pop up the Database Settings dialog box where we will add a new database connection:

13. Click on the Add button to set the properties, we chose to create a good pd_test database in the previous chapter with PowerDesigner:

14. Click OK to go back to the Database Selection dialog box and select the database connection you just created:

15. Next is to set the destination file output directory, where I set up a new folder for the desktop:

OK, everything is ready, you can click the Run button to let Codesmith generate code for us in bulk:

Open the generated file and you will see the code we expect to see:

Well, these are the foundation, but as long as you have mastered these can start their own codesmith trip, I can only send everyone to this ~ other more knowledge point hope that we can view Help articles or online query, it is very happy to share with you a little experience, Next want to go back to review the design pattern, also intends to write some articles, welcome to the attention ~

The file source code in the above practice:

TEST.CSTENTITY.CST

Wow, biennial, why so many exams AH ~ ~ ~ ~ Fast reading only to do

[Go] Bill: How to generate code in bulk using Codesmith

Related Article

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.