Code generator and .net

xiaoxiao2021-03-06  26

http://www.microsoft.com/china/msdn/library/langtool/vsdotnet/realworld1102004.mspx

Code generator and .net

Release Date: 12/23/2004

| Update Date: 12/23/2004

Pierre Couzywinwise

Summary: Code Builder is part of your daily life, even if you don't realize this. Pierre Couzy illustrates how to use them in your project.

This page

Introduction Tools and sample version control summary

Introduction

Suppose you work in a company that rule everything by DBA: You can't generate an application that is just "going to Oracle to take some records". You can only rely on the stored procedure because there is a security layer at this level.

Generating applications typically involve the following steps:

1. Create a batch of stored procedures. 2. Create a C # class that can communicate with the stored procedure. 3. Create a higher level of class that will manage the Microsoft ASP.NET form or Microsoft Windows form or form another layer.

Steps 1 and Step 2 are closely related: they share a large number of structures, they consume something generated by another step, and so on. The problem is that you have two different languages ​​(in this example, PL-SQL and C #) and cannot reference another language from one of the languages.

Do you say that this is not big? The first developers in the team will keep everything normally because he understands the essence of .NET, PL / SQL, and security models. He may write two things: first is a set of help classes, then a valid example - other developers will use these helper classes, copy / paste effective examples, and modify them for them.

If you have worked for a long enough time in the software industry, you will know what will happen next: With the increase in the demand, the helpor class will slowly become bigger, and some will be out of time. Of course, no one dares to modify them, as this may destroy the old project. At the same time, developers will reuse valid examples that are no longer synchronized with new rules, and they will have no way to understand which parts are still use, and which parts can be discarded without risk. You will fall into a chaotic (copy / paste programming).

There are a lot of ways to overcome this complexity, and I will introduce a useful approach you may have ignored - code generator. In fact, you have already used them, even if you don't realize this: Whenever you create a new ASPX page, the hidden mechanism converts it to the C # or Microsoft Visual Basic class. When you reference COM components, web services or even data structures (Type Data Sets) in your project - there is a class that is automatically generated, which hides the complexity you don't want to understand.

Back to top

Tools and examples

The first code generator you will encounter is just a tool for hiding complexity. They don't allow you to explain how to generate a code and don't let you change the generated code (they will clear the updates you).

For example, "Add Web Reference Wizard" does not even display code inserted into the project (unless you request it).

Figure 1. Displayed as a code generated by the web reference

The Windows Form Designer is also a code generator. Here you can view the code, but it is best not to move it.

#Region Windows Form Designer Generated Code

///

/// Required Method for Designer Support - Do Not Modify

/// the contents of this method with the code editor.///

Private vidinitiRizeComponent ()

{

This.button1 = new system.windows.Forms.Button ();

THIS.SUSPENDLAYOUT ();

Let us further explore the issue further: The code generator can provide the main trunk of the format specification for you to add your own code. You may know the Reflector, but you know some of the Reflector's add-in (http://www.dotnetwi.org/default.aspx?tabid=52) containing the code generator? They allow you to do the following:

Figure 2. Generate code using Reflector

When you press the "Generate" button, a new file will be created:

// generated by refly

Namespace mytestnamespace

{

Using system;

///

Test fixture for the Class

///

///

[TestFixTure ()]

Public Class SomebusinessClassTest

{

///

///

Private somebusinessClass_SomebusinessClass = NULL;

///

///

Public Virtual SomebusinessClassClass SomebusinessClass

{

get

{

Return this._somebusinessclass;

}

}

///

Tests the estimatesomenumber method

///

/// test coverage (Estimated): 100, 0%

/// target path:

/// / * 0 * / return 0x2a;

///

///

[Test ()]

[Ignore ()]

Public Virtual Void Estimatesomenumber0 ()

{

Throw new system.notimplementException ();

}

///

Tests the IssometyingalReadyindatabase method

///

/// test coverage (Estimated): 100, 0%

/// target path:

/// / * 0 * / return false;

///

///

[Test ()]

[Ignore ()]

Public virtual void issomethingalReadyindatabase0 ()

{

Throw new system.notimplementException ();

///

sets up the fixture

///

[Setup ()]

Public Virtual Void Setup ()

{

Throw new system.notimplementException ();

}

///

Release resource allocated in the fixture

///

[Teardown ()]

Public Virtual Void TEARDOWN ()

{

Throw new system.notimplementException ();

}

}

}

You don't know anything about "Unit Test", but you can still generate a valid test class. The difference from the previous example is that this time you must be encoded internally in the generated class. However, we still can't create our own template.

The next step is to create our own code generator. All what we need is a common information according to a set of common information (eg, the name of the column to be obtained, to request information, etc.) to generate text files (C #, PL-SQL, etc. Wait a way. Of course, you can't generate all things, therefore need a tool that can generate custom trunk, and a developer will then add specific implementation details.

This tool can be Perl, Microsoft Vbscript or normal legacy ASP (in this article) - after all, it is a good tool that can generate text files based on parameters. You may use ASP to generate an HTML file, but it also applies to generating Microsoft Excel or CSV, WML - therefore, why don't you use it to generate T-SQL or C #?

Your ASP file may be as follows:

<% @ Language = VBScript%>

<% IF Request ("generate"). count = 0 THEN%>

Property Name:

What is the TYPE OF Your Property?

read only

<% else

DIM PropertyName, PropertyType, Readonly, PropertyModifier

PropertyName = Request ("PropertyName")

PropertyType = Request ("PropertyType")

Readonly = ("Readonly") = "true") if readonly kiln proteysodifier = "Readonly" else PropertyModifier = ""

Response.contentType = "text / plain"

%>

PRIVATE _ <% = protyname%> as <% = propertytytype%>

Public <% = protymodifier%> Property <% = protyname%> as <% = propertytype%>

Get

Return _ <% = PropertyName%>

END GET

<% IF not readonly life%>

Set (Byval value as <% = propertytype%>)

_ <% = Protyname%> = value

End set

<% end if%>

End Property

<% end if%>

When you perform this file, you will get the following:

Figure 3. Generated web page

Figure 4. Generated code

You can also find the code generator on the Internet. I usually use CODesmith; it is free and easy to understand, but you can find a lot of other code generators. Figure 5 is a screenshot of a screen showing a smart way to wait for generic; it generates a strong type of hash table.

Figure 5. Codesmith

These tools usually accept two inputs - a template file (like our ASP file) and an XML parameter file (like the content of the form), and generate a new file.

Developers are given these templates and they usually use two different templates through the same set of parameters. In this way, they give the same information to two templates and get a T-SQL file and a C # file of sharing information, and do not need to take forgetting or typing errors; this will complete the boring part of this work.

Back to top

version control

Of course, things will become complicated when using templates and automatically generated code. In real life, the template will evolve (for example, you may wish to give C # class a way to call some stored procedures); if so, then you need a corresponding approach to cope with developers after the development Implementation.

To do this, you must ensure that the developer adds code independent of the code generated by your template. The easiest technology to achieve this is to create two different classes: a code for generated, another inheritance from the first one, but will not be generated.

Figure 6. Version control of the generated code

Due to the inheritance mechanism of this technology, it is very applicable when you generate .NET code; however, if you want to generate other types of code (VBScript, SQL), you will not work in this way. In that case, you mainly rely on yourself to solve the problem. I am using the mechanism: I provide a placeholder in the generated code (in the C # is zone; a block surrounded by a specific annotation), and when the code is regenerated, only these areas The code is retained. Transferring custom code itself is equally simple: Templates always accept the previousfile parameters. When this parameter exists, the previous file will be analyzed to obtain custom code and reinsert it into the current generated file. If there is no way to restore the original, don't mess with the code generated: You will find yourself in progress / pasting programming.

Back to top

summary

Below is some things you need to remember when using the code generator:

• If you don't intend to modify the generated code, please reply. • Don't forget that developers have no time to understand the internal structure of the generated code, so please help them, and explain the entry points as detailed. • Consider the version control and clearly explain what you will allow people to do. Maybe you want the developer to add custom code only in the specific area of ​​the code, or you want them to inherit from your class. • The new version of the template should always regenerate the code generated by the old version. If the new version needs more code than the old version to work correctly, please make a clear position of the code, and insert some code that generates an error (if possible - if possible). • If you determine the version control mechanism of the interrupt template (for example, the original code cannot be restored by adding the new version), keep the template and a copy of the parameters you use. If you need to generate another similar code file for an old item, and you have lost the template version used in developing the old project, it will happen very bad things. I just put the templates and parameters to the project in SourceSafe. • Thoroughly test it before publishing a template. The template will spread quickly between developers because they can solve problems without much knowledge. If the update generated file means loss of custom, the program error will be difficult to find and more difficult to fix.

How far can you use this method? Simply put, the code generator allows developers to get an abstract level. He doesn't have to focus on the technical process (because the process has been embedded in the template) and can consider integrated the process. It enables developers to better understand customer needs and make technical processes have better quality. Microsoft Visual Studio has widely used these technologies, and the upcoming version has already added a lot of improvements (striking is a class modeling program and incomplete mechanism, which can be used to separate the generated code with custom code separation ).

.NET in the real world

Pierre Couzy is a trainer and consultant specializing in the research distributed system architecture. As the author of more than 20 bars, he is currently hired as an ASP.NET and BIZTALK experts by WinWise. He has always been a regional supervisor since 2003 and delivered a speech at many important meetings in France. If you want to discuss the French jazz, the bridge (yes, that is the simple game) or even a computer, please contact him with Pierre.Couzy@winwise.fr.

转载请注明原文地址:https://www.9cbs.com/read-77109.html

New Post(0)