How to use. Net to generate C # source code

Source: Internet
Author: User

I told you how to use it last week. net implementation directly calculates an expression. In fact, this method can be extended to execute a method in a class or used in other more useful places, as described in the article, this article only describes a method that can be implemented and a simple implementation of this method.

Today we want to see how to use. Net an automatic generation of source code, with the previous article you can use your own generated code for your own consumption (the previous article please refer to: http://www.csdn.net/Develop/read_article.asp? Id = 34659 ).

Does it sound great? Some friends may say this is a bit difficult, but it is not. Our project uses the codedom namespace provided by Microsoft, so it can be easily implemented. For details about codedom, refer to msdn. The above is very clear! I am not here. Connection reference: http://msdn.microsoft.com/library/en-us/cpref/html/frlrfSystemCodeDom.asp? Frame = true

This article describes how to automatically generate the source code of a simple data access layer. All the code is written in hard-code mode. If you are interested, you can use other methods, for example, the database (resource files) to obtain resources, generate source code, but also to achieve some O-R ing operations.

The data access layer in this article contains an attribute field and a method. A property is an attribute used to obtain the connection object. A field is a private member of the connection object. The method is a get method to obtain a query result set. After the source code is generated, it will look like the following:
Using system;
Using system. Data;
Using system. Data. sqlclient;

Namespace power. cuike519 {


Public class powerdataaccess {

Private sqlconnection m_connection;

Public powerdataaccess (){
}

Public Virtual sqlconnection connection {
Get {
Return this. m_connection;
}
Set {
This. m_connection = value;
}
}

Public Virtual dataset getallauthors (string s_state ){
Try {
If (this. m_connection! = NULL ){
System. Data. sqlclient. sqldataadapter da = new sqldataadapter (string. Format ("select * from authors where state like '{0}'", s_state), this. m_connection );
System. Data. dataset DS = new dataset ();
Da. Fill (DS );
Return Ds;
}
Else {
Return NULL;
}
}
Catch (system. applicationexception ex ){
Throw ex;
}
Finally {
This. m_connection.close ();
}
}
}
}
Next, let's take a look at the method we used to generate this code. to generate this code, we need a project. I have created a Windows application to do this, you can also use the console or ASP. net Program releases the source code you generated to the network for more people to see. We have written a method createpowerdataaccesslayer in the project, which creates the source code above. Let's take a look at the source code snippet:

First, we need a stream to save the source code. We use the following code to create a stream:
Stream codestream = file. Open ("mydataaccess. cs", filemode. Create );
Streamwriter codewriter = new streamwriter (codestream );

Then we want to write the CSHARP code, so we can use csharpcodeprovider to create a code generator.
Csharpcodeprovider provider = new csharpcodeprovider ();
Icodegenerator codegenerator = provider. creategenerator (codewriter );
Codegeneratoroptions = new codegeneratoroptions ();

In order to make our source code run correctly, we use the following method to add a namespace for our source code.
Codesnippetcompileunit literal = new codesnippetcompileunit ("using system;/nusing system. Data;/nusing system. Data. sqlclient;/N ");
Codegenerator. generatecodefromcompileunit (literal, codewriter, codegeneratoroptions );

Then we need to set a namespace for our source code and create a class under this namespace.
Codenamespace = new codenamespace ("power. cuike519"); // namespace name
Codetypedeclaration = new codetypedeclaration ();
Codetypedeclaration. Name = "powerdataaccess"; // Class Name
Codetypedeclaration. isclass = true;
Codetypedeclaration. typeattributes = typeattributes. Public;
Codenamespace. types. Add (codetypedeclaration );

Next, create a constructor for this class. Here, only one default constructor is created.
Codeconstructor codeconstrustor = new codeconstructor ();
Codeconstrustor. Attributes = memberattributes. Public;
Codetypedeclaration. members. Add (codeconstrustor );

Next, create a field for our class, which is private. It is a sqlconnection type named m_connection.
Codememberfield codemember = new codememberfield ();
Codemember. Name = "m_connection ";
Codemember. Attributes = memberattributes. Private;
Codemember. type = new codetypereference ("sqlconnection ");
Codetypedeclaration. members. Add (codemember );

With the field, we add an operation and read attribute for the word break. We specify the set and get methods for it, and it is public, which is of the sqlconnection type, as shown below:
Codememberproperty = new codememberproperty ();
Codememberproperty. Name = "connection ";
Codememberproperty. Attributes = memberattributes. Public;
Codememberproperty. type = new codetypereference ("sqlconnection ");
Codememberproperty. getstatements. Add (New codemethodreturnstatement (New codefieldreferenceexpression (New codethisreferenceexpression (), "m_connection ")));
Codememberproperty. setstatements. Add (New codeassignstatement (New codefieldreferenceexpression (New codethisreferenceexpression (), "m_connection"), new codepropertysetvaluereferenceexpression ()));
Codetypedeclaration. members. Add (codememberproperty );

To make our class look more useful, we use the following method to create a function and the content in the function. Here we can write the function body into it at one time, the reason for not doing so is to provide an opportunity to see that Microsoft provides many other statements related to the source code in this namespace.

It is public and returns the dataset type method named getallauthors. Although this name is called, we still provide a parameter to provide more flexible space for use, and also to illustrate the method of using parameters in the function.
Codemembermethod = new codemembermethod ();
Codemembermethod. Name = "getallauthors ";
Codemembermethod. Attributes = memberattributes. Public;
Codemembermethod. returntype = new codetypereference ("dataset ");
Codemembermethod. Parameters. Add (New codeparameterdeclarationexpression (typeof (string), "s_state "));

To make the source code stronger, we use the try-catch-finnaly statement, as shown below:
Codetrycatchfinallystatement try1 = new codetrycatchfinallystatement ();

To determine whether our m_connection has been initialized, we use the following judgment statement to judge:
Codeconditionstatement conditionalstatement = new codeconditionstatement ();
Conditionalstatement. condition = new codevariablereferenceexpression ("This. m_connection! = NULL ");
 

When the condition is true, we want our source code to execute the following code:
Codevariabledeclarationstatement variabledeclarationda = new codevariabledeclarationstatement (typeof (system. data. sqlclient. sqldataadapter), "da", new codevariablereferenceexpression ("New sqldataadapter (string. format (/"select * from authors where state like '{0}'/", s_state), this. m_connection )"));
Conditionalstatement. truestatements. Add (variabledeclarationda );
Codevariabledeclarationstatement variabledeclarationds = new codevariabledeclarationstatement (typeof (Dataset), "ds", new codevariablereferenceexpression ("new dataset ()"));
Conditionalstatement. truestatements. Add (variabledeclarationds );
Codeexpression invokeexpression = new codemethodinvokeexpression (New codetypereferenceexpression ("da"), "fill", new codevariablereferenceexpression ("ds "));
Codeexpressionstatement expressionstatement = new codeexpressionstatement (invokeexpression );
Conditionalstatement. truestatements. Add (expressionstatement );
Conditionalstatement. truestatements. Add (New codevariablereferenceexpression ("Return ds "));

Execute the following statement in case of false:
Conditionalstatement. falsestatements. Add (New codevariablereferenceexpression ("return null "));

Then we add the if statement to the middle of the try statement, as shown below:
Try1.trystatements. Add (conditionalstatement );

At the same time, we use the following method to add the try statement to our method:
Codemembermethod. Statements. Add (try1 );

Next we want to throw the exception information when encountering an exception. The Code is as follows:
Codecatchclause catch1 = new codecatchclause ("ex", new codetypereference ("system. applicationexception "));
Catch1.statements. Add (New codevariablereferenceexpression ("Throw ex "));
Try1.catchclauses. Add (catses );

Next, we need to clear the resource code. We will close the connection here (in fact, we should check the status before closing, although sqldataadapter does not need to be explicitly closed, however, there is nothing wrong with the judgment written here)
Try1.finallystatements. Add (New codevariablereferenceexpression ("This. m_connection.close ()"));
Codetypedeclaration. members. Add (codemembermethod );

The following code is generated:
Codegenerator. generatecodefromnamespace (codenamespace, codewriter, codegeneratoroptions );

Do not forget to close the resource at the end
Codewriter. Close ();
Codestream. Close ();

Most of the Code in this article is the code shown above. Please comment directly or send an email to the wu_jian830@hotmail.com. Thank you!

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.