Codedomprovider-generate code

Source: Internet
Author: User

Codedom is provided by. netSource codeGenerator, which can generate a source through codedomproviderCodeBecause codedomprovider is the abstract base class of csharpcodeprovider and vbcodeprovider, it indicates that codedomprovider is a cross-language source code generator. You only need to provide the corresponding codeprovider to generate the source code of the corresponding language.

Codedom is in the system namespace, and csharpcodeprovider is in the Microsoft. CSHARP namespace. Vbcodeprovider is in the Microsoft. VisualBasic namespace.

Classes in codedom and their usage

1. codecompileunit class

This class is used for codedomProgramThe container provides a container. You can add a namespace through the add method of the namespaces set.

For example:

Codecompileunit unit = new codecompileunit ();
Codenamespace thenamespace = new codenamespace ("mynamespace ");
Unit. namespaces. Add (thenamespace );

2. codenamespace class

Used to indicate a namespace object. Other Namespaces can be introduced in this namespace, or classes can be added.

For example, add a class to the namespace.

Codetypedeclaration etclass = new codetypedeclaration ("etmyclasses ");
Thenamespace. types. Add (etclass );

Introduce a namespace

Codenamespaceimport systemimport = new codenamespaceimport ("system ");
Thenamespace. Imports. Add (systemimport );
3. codetypedeclaration class

A type declaration that represents a class, structure, interface, or enumeration.

Declare a class such

Codetypedeclaration etclass = new codetypedeclaration ("etmyclasses"); A set of basetypes base classes or interfaces, which can be added through the Add Method
Typeattributes class or interface modifier, such as public or sealed, directly assign values. You can use | to perform or operations.
A set of members of the members class. The add method can be used to add fields, attributes, and methods.

Set or retrieve if this type is Enumeration
Isclass to set or obtain whether this type is a class
Isinterface to set or obtain whether this type is an interface
Ispartial: whether to set or obtain the complete declaration or partial declaration of this class
Isstruct sets or obtains whether this type is structured.
Set or obtain the name of this type.

The constructor parameter of codetypedeclaration can be the name of this class or its name can be specified directly after instantiation without a parameter. You can directly use the class name when adding a base class to a type, for example, etclass. basetypes. add ("entitisgateway"); you can also add codetypereference instances, such as etclass. basetypes. add (New codetypereference (typeof (system. console); [nextpage]

4. codenamespaceimport class

Used to represent the mapped namespace object. The constructor parameter is a non-parameter or namespace name. Use the add method of the imports set of codetypedeclaration to add the namespace Class 5. codememberfield

Used to indicate the field objects in the class. The constructor parameters are of the type and name, as shown in figure

Codememberfield tablenamefiled = new codememberfield (typeof (string), "c_str_tablename ");
This indicates that a class member field whose type is string and name is c_str_tablename is defined.

Attributes sets the class description symbols such as const and public, which can be used | for or operations
Initexpression
Note that the codeprimitiveexpression class must be used to assign values to initexpression. It is used to indicate that the specified object is used for initialization, for example:

Tablefieldfield. initexpression = new codeprimitiveexpression (field. fieldname );

6. codememberproperty class

Indicates that the property object constructor in the class is the name of the name attribute of the non-argument constructor.
The type of the type attribute. codetypereference is used to assign values.
Attributes indicates the attribute modifiers public and override.
Hasget gets or sets whether the property has a get method accessor.
Hasset obtains or sets whether the set method accessors are available for this attribute.
Getstatements indicates the set of get method accessors. Add the statement using the add method.
Setstatements indicates the set statement set of the Set Method accessors. Add the statement using the add method.

Add the following statement to the get or set method accessors:

// Define an expression to indicate a local variable reference
Codevariablereferenceexpression fieldexpression = new codevariablereferenceexpression ("c_str_tablename ");
// Define a return statement to indicate the get return statement. The returned variable is fieldexpression.
Codemethodreturnstatement propertyreturn = new codemethodreturnstatement (fieldexpression );
// Add the Return Statement to the get statement set
Tablenameproperty. getstatements. Add (propertyreturn );

7. codemembermethod class

Indicates a member method in the class. Only the non-argument constructor name indicates the method name.
The descriptor of the attributes method. | can be used for or operations.
Set parameters of the parameters method. Add parameters using the add method.
The statement set in the statements method, which is added through the Add Method

// construct a method object
codemembermethod loaddatabyprocessidmethod = new codemembermethod ();
// specify the method name
loaddatabyprocessidmethod. name = "loaddatabyprocessid";
// modifier of the specified method
loaddatabyprocessidmethod. attributes = memberattributes. public | memberattributes. final;
// Add a parameter of the int type and processid to the method. The parameter
loaddatabyprocessidmethod is expressed by codeparameterdeclarationexpression. parameters. add (New codeparameterdeclarationexpression (typeof (INT), "processid");
loaddatabyprocessidmethod. parameters. add (New codeparameterdeclarationexpression (typeof (dbtransaction), "objtrans");

// A reference to a given method indicates that a method must be called.
Codemethodreferenceexpression loaddataexpression = new codemethodreferenceexpression ();
// Name of the called Method
Loaddataexpression. methodname = "loaddataby ";

// Define the expression of a method call and pass in the reference of the call method. codevariablereferenceexpression is used to indicate the reference [nextpage]
Codemethodinvokeexpression loaddatainvoke = new codemethodinvokeexpression (loaddataexpression, new codevariablereferenceexpression ("c_str_processid +" = "+ processid"), new partition ("objtrans "));

// Add the method call expression to the method amount statement set
Loaddatabyprocessidmethod. Statements. Add (loaddatainvoke );
// Add the method to the class
Etclass. members. Add (loaddatabyprocessidmethod );
Codeparameterdeclarationexpression is a parameter that initializes a method with the specified type and parameter name. Codevariablereferenceexpression is used to indicate a reference to a local variable name.

8. codeconstructor class

It is used to represent the constructor of A Class. baseconstructorargs is a set of parameters used to represent the constructor of the base class. You can add a codevariablereferenceexpression object through the add method, you do not need to initialize two of them, for example:

Wfpropertyconstructor1.baseconstructorargs. Add (New codevariablereferenceexpression ());
9. codetypeofexpression class

Used to represent a typeof expression

10. codethisreferenceexpression class

Expression used to represent this

11. codebasereferenceexpression class

Expression used to represent the base

Codethisreferenceexpression and codebasereferenceexpression can be combined with other expressions to form an expression, for example:

Codemethodinvokeexpression initbyentityidinvoke = new codemethodinvokeexpression (New codebasereferenceexpression (), "constructbyid", new partition (m_model.entitiestable + "ID"), new partition ("objtrans "));
The above code initializes a method call expression. It uses the codebasereferenceexpression and constructbyid methods, and adds two local variables as parameters of a method call to form a function call expression [nextpage].

12. codesnippetstatement class

Indicates a statement. to be compatible with the VB syntax, codedom does not support some syntaxes and can be called without classes. It is impossible to write a statement using codesnippetstatement, however, this statement cannot be used in VB.. net

Codesnippetstatement exceptionstatement = new codesnippetstatement ("throw new exception (" property not Implementation ")");
The above exception thrown statement is directly written code. Of course, codedom has an object with an exception statement. I stole it here.

13. indentedtextwriter class

Indicates the indentation of the generated code statement.

Indentedtextwriter Tw = new indentedtextwriter (New streamwriter (sourcecodepaht + "\" + m_model.entitiesassembly + ". cs", false ),"");

The four spaces between double quotation marks after "false" indicate that the Code indent value is four spaces.

All we have left is to generate code.

Indentedtextwriter Tw = new indentedtextwriter (New streamwriter (sourcecodepaht + "\" + m_model.entitiesassembly + ". cs", false ),"");
Codedomprovider provide = new csharpcodeprovider ();

Provide. generatecodefromcompileunit (unit, TW, new codegeneratoroptions ());
Tw. Close ();
The provider provides several generation methods. generatecodefromcompileunit can generate all the code in a code container. If we only write one class, we can generate it using the generatecodefromtype method, you can also generate code in a namespace, or even generate only one statement or expression generatecodefromnamespace, generatecodefromstatement

The rest is to compile the source code.

Compilerparameters compilerparams = new compilerparameters ();
// Specify the compilation option, which is a class library
Compilerparams. compileroptions = "/Target: Library/optimize ";
// Do not generate an execution File
Compilerparams. generateexecutable = false;
// Generate output in memory
Compilerparams. generateinmemory = true;
// Does not contain debugging information
Compilerparams. includedebuginformation = false;
// Add the DLL used for compilation. If it is not the built-in DLL, you must specify the complete path.
Compilerparams. referencedassemblies. Add ("mscorlib. dll ");
Compilerparams. referencedassemblies. Add ("system. dll ");
Compilerparams. referencedassemblies. Add ("system. Data. dll ");
Compilerparams. referencedassemblies. Add (appdomain. currentdomain. setupinformation. applicationbase + "dawnpro. webarchitechture. Dal. dll ");
Compilerparams. referencedassemblies. Add (appdomain. currentdomain. setupinformation. applicationbase + "dawnpro. workflowinterface. dll ");
// Specify the output path of the compiled file
Compilerparams. outputassembly = outputasseblypath + "\ bin \" + m_model.entitiesassembly + ". DLL "; finally, compile using the compileassemblyfromdom method provided by the provider. provider provides three methods, one is from Dom and the other is from file, compile compilerresults result = provide from a string. compileassemblyfromdom (compilerparams, Unit); compilerresults is the return value of these three methods. You can view compilation errors through the errors set of compilerresults.

ArticleReprinted from the Network Management Network: http://www.bitscn.com/pdb/dotnet/200803/135308.html

In addition: http://blog.csdn.net/heguodong/archive/2009/12/28/5094185.aspx

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.