How to use. NET generates C # source code

Source: Internet
Author: User
Source code last week to everyone said how to use. NET implementation directly evaluates an expression that can be extended to execute a method within a class or to use in other more useful places, as the article says, the article is just a way of describing what can be done and a simple implementation of the method.

Today we'll see how to use it. NET an automatic generation source code, with the previous article you can use your own to generate code for their own consumption (last article please refer to: http://www.csdn.net/Develop/read_article.asp?id=34659).

Does that sound cool? Some friends might say it's a bit hard, but it's not. Our project uses the CodeDom namespace provided by Microsoft, so it can be easily implemented. The details about the CodeDom can be referenced in MSDN, which is very clear! I'm not going to be a Russell here. Connection reference: Http://msdn.microsoft.com/library/en-us/cpref/html/frlrfSystemCodeDom.asp?frame=true

This article introduces a simple data access layer source code generation implementation, all the code is written in Hard-code, if you are interested in other methods, such as the database (resource file) to obtain resources, generate source code, you can also implement some o-r mapping operations.

The data access layer in this article has one field and one method for the property. property is a property that obtains the connection object, which is a private member of a connection object, a Get method, and a query result set. Source code generation is 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 ();
}
}
}
}
Let's see what we're using to generate this code, so we need a project to generate the code, I've built a Windows application to do it, and you can use a console or ASP.net program to publish your generated source code to the web for more people to see. We have written a method in the project Createpowerdataaccesslayer, this method creates the above source code, below we will look at the source code fragment:

First we need a stream to save the source code, we use the following code to create the stream:
Stream Codestream = File.Open ("Sample.cs", FileMode.Create);
StreamWriter codewriter = new StreamWriter (Codestream);


Then we want to write the CSharp code so we use CSharpCodeProvider to create a code generator.
CSharpCodeProvider Provider = new CSharpCodeProvider ();
ICodeGenerator CodeGenerator = provider. CreateGenerator (Codewriter);
CodeGeneratorOptions codegeneratoroptions = new CodeGeneratorOptions ();


To allow our source code to run correctly, we use the following method to add namespaces to our source code
CodeSnippetCompileUnit literal = new CodeSnippetCompileUnit ("Using system;\nusing system.data;\nusing System.data.sqlclient;\n ");
Codegenerator.generatecodefromcompileunit (literal,codewriter,codegeneratoroptions);


Then we're going to set up a namespace for our source code and create a class under this namespace
CodeNamespace CodeNamespace = new CodeNamespace ("power.cuike519");//namespace name
CodeTypeDeclaration codetypedeclaration = new CodeTypeDeclaration ();
Codetypedeclaration.name = "Powerdataaccess"; Class name
Codetypedeclaration.isclass = true;
Codetypedeclaration.typeattributes = Typeattributes.public;
CODENAMESPACE.TYPES.ADD (CodeTypeDeclaration);


We then create a constructor for the class, where only one default constructor is created
CodeConstructor codeconstrustor = new CodeConstructor ();
Codeconstrustor.attributes = Memberattributes.public;
CODETYPEDECLARATION.MEMBERS.ADD (Codeconstrustor);


Then create a field for our class, which is private, and it's the 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 a property that can be manipulated and read for the word, we specify the set and get methods for it, and it is public and SqlConnection type, as follows:
Codememberproperty 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 contents of the function. You can write the body of the function one at a time, and the reason for not doing so is to provide an opportunity to see that Microsoft provides a lot of other classes in the namespace that are used in the source code.


It's public. The name of the method that returns the dataset type is called Getallauthors. That's the name, though. But we also provide a parameter to provide more flexible use of space, but also to illustrate the function of the method of using parameters.
CodeMemberMethod 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 our source code stronger we used the Try-catch-finnaly statement as follows:
Codetrycatchfinallystatement try1 = new Codetrycatchfinallystatement ();


To determine if our m_connection has been initialized we use the following judgment statement to determine:
Codeconditionstatement conditionalstatement = new Codeconditionstatement ();
Conditionalstatement.condition = new Codevariablereferenceexpression ("This.m_connection!=null");


We want our source code to execute the following codes when the conditions are true:
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"));


and execute the following statement at the time of the false:
CONDITIONALSTATEMENT.FALSESTATEMENTS.ADD (New codevariablereferenceexpression ("return null"));


We then add the IF statement to the middle of the try statement, as follows:
Try1. Trystatements.add (conditionalstatement);


Also, we use the following method to add a try statement to our method:
CODEMEMBERMETHOD.STATEMENTS.ADD (Try1);


Then we expect to throw exception information when we encounter an exception, as follows:
CodeCatchClause catch1 = new CodeCatchClause ("Ex", New CodeTypeReference ("System.ApplicationException"));
Catch1. Statements.add (New Codevariablereferenceexpression ("throw ex"));
Try1. Catchclauses.add (CATCH1);


Then there is the code that needs to recycle the resources, we are here to close the connection (in fact, we should check the state and then close, although the SqlDataAdapter does not need to be explicitly closed, but if you add the judgment written here there is nothing wrong)
Try1. Finallystatements.add (New Codevariablereferenceexpression ("This.m_connection"). Close ()));
CODETYPEDECLARATION.MEMBERS.ADD (CodeMemberMethod);


The following code can be generated
Codegenerator.generatecodefromnamespace (codenamespace,codewriter,codegeneratoroptions);


In the end don't forget to close the resource
Codewriter.close ();
Codestream.close ();



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.