Super simple: Code Generator

Source: Internet
Author: User
Code :/Files/zhuqil/sqlclassfactory_src.zip

Introduction

This project provides a data source. In a ListBox, it lists all the databases in the data source service, and The ListBox next to it lists all the data tables in the corresponding database. Then the entity class abstraction layer of the table can be generated. The generated class name is the same as the data table name. Save the production code as. CS.Source codeFile.

 

Code Description:

Looking at the figure above, you will find that this solution includes a class library project and a tested windowsform project testform. Testform includes two forms, testmain. CS andInput. CS. Input form is used to obtain the data source (usually.) of the database server or to log on to the database server by entering the database server name, user name, and password. Testform is verified and will appear on the screen when the verification passes. No applicationProgramWill automatically exit.

 

There are many different classes in the sqlclassfactory class library project. All classes here are static. Start with the constants class. This class contains strings that do not change frequently, such as connection strings. The connstrargs. CS file contains a static class named args.This class is critical. Because it must be done first before other database operations. All other static classes obtain server information from this class. As shown below, you must first set:

 

Sqlclassfactory. args. Reset ();
Sqlclassfactory. args. Type = Sqlclassfactory. enmconnstrtype. trusted;
Sqlclassfactory. args. datasource = Datasource;
Sqlclassfactory. args. initialcatalog =   " Master " ;

The next class is the connections. CS class. This class has a private field named _ connection and the type is sqlconnection. It contains a static method getconnection ().. This method obtains a string formatted with parameters from constants, and then obtains the parameter value from The args class. Create a new connection and return it. As you can see, each time, this method calls a new connection again and again through the configured args.

The commands class is only the host of a sqlcommand. Commands classCommandtextAndConnectionAttribute inSet in adapters class. These attributes areThe adapters class will be set as follows:

 

Commands. listdbcmd. commandtext = Constants. listdbstr;
Commands. listdbcmd. Connection = Connections. getconnection ();
Adapters. _ serverda =   New Sqldataadapter (commands. listdbcmd );

 

For example, the listdbcmd command and serverda attributes are set here to use this command to create a new sqldataadapter.

The last class is generator. This static class contains a begingeneration (string) method. This method is like a constructor passing a string parameter to rawclasstext. I will use the code section to really explain them.

Class.txt

Class.txt contains a file of rawclasstext. Rawclasstext uses a specified database to generate a data table proxy class. Class.txt contains some special fields <...>. These fields will be replaced by matching attribute names or class names.

Code

Public Datatable doselect ( String Sqlcommandtext)
{
Sqlcommand selectcommand =   New Sqlcommand (sqlcommandtext );
Selectcommand. Connection = Sqlconnection;
Sqlda. selectcommand = Selectcommand;
Datatable retdt =   New Datatable ();
Sqlda. Fill (retdt );
Return Retdt;
}

 

Here you see the doselect () method of "class.txt. Sqlda is a member of the class and it is initialized in the constructor. This is the simplest method in this class. Fill in the dataset RET and return ret.

Code

Public   Bool Doinsert ( String Sqlcommandtext, Params   Object [] ARGs)
{
Sqlcommand insertcommand =   New Sqlcommand (sqlcommandtext );
String Argincmd =   Null ;
RegEx R =   New RegEx ( @" @ (\ S +) " , Regexoptions. ignorecase );
Int I =   0 ;
If (R. Matches (sqlcommandtext). Count = Args. length)
{
Foreach ( Object ARG In ARGs)
{
Argincmd = R. Matches (sqlcommandtext) [I]. tostring ();
Argincmd = Argincmd. Trim (). trimend ( New   Char [] { ' ) ' , ' , ' });
Insertcommand. Parameters. addwithvalue (argincmd, ARG );
I ++ ;
}
}
Else
Return   False ;
Insertcommand. Connection = Sqlconnection;
Sqlconnection. open ();
Bool RET = Insertcommand. executenonquery () >   0 ;
Sqlconnection. Close ();
Return RET;
}

 

Here you can see the doinsert () method of "class.txt. This method is complex. It is used as follows:Doinsert ("insert into employees (firstname, lastname) values (@ fname, @ lname)", "Ozgur", "sonmez ");This is the smartest way for all projects. This requires the Params type parameter args. ARGs contains all parameters added to sqlcommand. In the preceding example, '@ fname' is the first parameter in the string argincmd,@ LnameIs the second parameter. Argincmd is used to match rotation parameters.

New RegEx (@ "@ (\ s +)", regexoptions. ignorecase); is used to match'@ Matched_parameter'.This is followed by taking <R. Matches (sqlcommandtext) [I]. tostring ();>.For some reason, I cannot find a perfect matching for C #, so I will get '@ lname)' or '@ fname,' all the work I need to do. The fully matched characters will be saved in argincmd, added to the sqlcommand parameters through the parameter. addwithvalue () method, then opened the connection, and executed executenonquery.

Code:

This Code contains a class library project and a Windows form project of test form. To be concise, I use sqlclassfactory DLL to display two separate ListBox controls for databases and relational data tables. The main access port is testform.exe. You can use this sqlclassfactory. dll class library anywhere to get two lists. But this is not the only job of sqlclasslibrary. It also contains the general generator class. This class contains public static void begingeneration (string rawtext ). This method obtains the rawtext string from class.txt and replaces all <...> with the appropriate name. Here we provide the class.txt section as an example:

 

Namespace   < Database_name >  
{ Public   Class   < Table_name >  
{ < Column_name >  
Sqldataadapter sqlda =   Null ;
Sqlconnection =   Null ;

 

The core of the testform application is as follows:

Code

Sqlclassfactory. generator. begingeneration (rtxtclass. Text );
Sqlclassfactory. generator. addtabledbname (tablename, dbname );
Foreach (Datarow row In Dtcolumns. Rows)
{
Sqlclassfactory. generator. addfield
(Row [ " Data_type " ]. Tostring (), row [ " Column_name " ]. Tostring ());

}
Sqlclassfactory. generator. endgeneration ();
Rtxtclass. Text = Sqlclassfactory. generator. rawclasstext;

Here, the static method begingenerator () obtains text data from RichTextBox rtxtclass, which is inside the sqlclassfactory. Generator class. In rtxtclass. Text, generator. addtabledbname (...) replaces "<database_name>" and "<table_name>" with appropriate characters ". Then, every time in a foreach loop, the static topology in generatoraddaddfield((, this is used to name the source class, and the category is serialized as class.txt. This method replaces "<column_name>" with the attribute name ". That is, the name of the column in the given database table. You can use the preceding parameter row ["data_type"]. tostring (),

Row ["column_name"]. tostring ().

This feature is worth noting. The key code for this function is as follows:

Code

String Fieldtext =
String. Format ( " Public {0} {1} " , Propertytype, propertyname)
+   " {Get; Set ;}\ n \ t <column_name> " ;
Rawclasstext = Rawclasstext. Replace ( " <Column_name> " , Fieldtext );

 

Here, every time addfield () is called, fieldtext is set to a string similar to "Public int productid {Get; set;}". The attribute type is replaced first, and then the attribute name is replaced. Set column_name to be used when addfield () is called next time. First, add a new row to the attribute name and then add a row "<column_name> ".

Sqlclassfactory. generator. endgeneration ();

This line of code causes string. Empty to replace "<column_name>" to clear unnecessary parts.

Rtxtclass. Text = Sqlclassfactory. generator. rawclasstext;

Hope this articleArticleIt is helpful for anyone who wants to write their own code generators (Red translator +)

Original article:Http://www.codeproject.com/KB/database/SqlClassFactoryLibrary.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.