Use a C # to create a code generator

xiaoxiao2021-03-06  24

Use a C # to create a code generator

Author: Chen edge Contact: luandao2000@gmail.com blog: http: //blog.9cbs.net/luandao2000 home page: http: //www.spbase.com

Comrades using the VS.NET development web application will come into contact with two very classic examples on the .NET platform: Duwamish and Petshop, two examples are examples developed by Microsoft to demonstrate the N-layer architecture, because it is a group of different in Microsoft. The style has been developed. I don't dare to evaluate, but in my current project, the structure of Duwamish is designed to design the entire system. On the current situation, the effect is still better. DUWAMISH's data representation layer completes the mapping of the business entity, uses a type of Dataset to describe the structure of the business entity, depending on the structure of the data sheet constituting the business entity, everyone can see this from duwamish point. The code format indicating the layer is simple, without any logic, basically only describes the structure, so the code generator can be accomplished for this part of the code. Take a look at the data access layer, basically similar, the data access layer completes the actual data reading and writing work, but most of the simple increase, deletion, change, check, the code is still simple, the format is fixed: the entrance to the stored procedure is constructed Parameters, construct the COMMAND object of the corresponding operation, call the adapter complete operation, if there is no special requirements, this part of the code is completed automatically. After analyzing the format of the completed code, let's consider what code generator we need? First, a code that represents a layer and a data access layer can be generated according to a data sheet format constituting the business entity, followed by the corresponding configuration. This can basically reduce many repetitive work. For systems that use DUWAMISH architectures, some simple operations of the business entity can be generated. Finally, it is best to automatically generate the modified stored procedure, so that the prototype of a database system is basically completed. In fact, most of the code generators are also completed these features. According to your choice, generate a template nature code, so many work will not be repeated, and there will be many times in late maintenance. If you have a nonsense, you will not say it. Start your hands: 1, first design the template files and replacement parameters of each layer, generate the dynamic code section 3 according to the selected data table, generate the corresponding code file and stored procedure

First, the template files of each layer are first, in fact, the code that represents the layer can be apparent: The data entity described by the type Dataset is basically the mapping of the data sheet in the program, of course, we must consider the relationship of the master-detail table. Most business entities are not clearly described alone. Here is an example of a data access layer template file:

Namespace servicecard.dataaccess {using system; using system.data; using system.data.racleclient; using system.configuration; using servicecard.common;

///

/// card info /// public class $ classname $: accessbase {// // datasetcommand object // // private oracleDataadapter dscommand; /// stored procedure parameter names //// private OracleCommand loadCommand; private OracleCommand insertCommand; private OracleCommand updateCommand; private OracleCommand deleteCommand; // private string ServiceCardConnectionString = ConfigurationSettings.AppSettings [ "ServiceCardConnectionString"]; private const string PROCESS_PARM = "GH_PACKAGE.LOAD_WORKSHEET"; private const string CURSOR_PARM = "ret_cur" Private const string value_parm = "in_value"; $ PARM $

public $ classname $ () {// // TODO: add your code // dsCommand = new OracleDataAdapter (); dsCommand.TableMappings.Add (. "$ tablename $", $ dataname $ $ constname $);} public $ classname $ (OracleConnection base_connect, OracleTransaction base_mytrans) {// // TODO: add your code // dsCommand = new OracleDataAdapter (); dsCommand.TableMappings.Add ( "$ tablename $", $ dataname $ $ constname $.); connect = Base_connect; myTrans = base_mytrans; btrans = true;

///

/// Dispose of this Object's resources. /// // {// dispose (true); // gc.suppressFinalize (TRUE); // AS a service to those who might inherit from us //}

///

/// free the instance variables of this object. /// /// protected Override void dispose (bool disposing) /// {/// if (! disposing) //////// Return; // We're Being Collected, So Let the GC Take Care of this Object //////// {/// IF (DSCommand.selectCommand! = null) // / {/// if (dscommand.selectcommand.connection! = Null) /// {/// dscommand.selectcommand.connection.dispose (); ///} /// dscommand.selectCommand.dispose (); // /} /// dscommand.dispose (); // DScommand = null; ///} ///} // ---------------------- ------------------------------------------ // Sub BuildLoadCommands: // Initialize THE parameterized loading command for the dataadapter // ----------------------------------------- ----------------------- Private OracleCommand getloadCommand () {if (loadingcommand == null) {/// Construct the Command Since We don't have IT already // loadcommand = new oracleCommand (Proces) S_PARM, new OracleConnection (ServiceCardConnectionString)); loadCommand.CommandType = CommandType.StoredProcedure; loadCommand.Parameters.Add (new OracleParameter (CURSOR_PARM, OracleType.Cursor));

Loadcommand.Parameters [CURSOR_PARM] .direction = parameterDirection.output;

Loadcommand.Parameters.Add (New OracleParameter (Value_Parm, Oracletype.varchar);

} Return loadingCommand;

private OracleCommand GetDeleteCommand () {if (deleteCommand == null) {// // Construct the command since we do not have it already // if (bTrans) deleteCommand = new OracleCommand ( "$ deletecommand $", connect); else deleteCommand = new OracleCommand ( "$ deletecommand $", new OracleConnection (ServiceCardConnectionString)); deleteCommand.CommandType = CommandType.StoredProcedure; deleteCommand.Transaction = mytrans; OracleParameterCollection OracleParams = deleteCommand.Parameters; $ deleteconest $} return deleteCommand;} private OracleCommand GetUpdateCommand () {if (updateCommand == null) {// // Construct the command since we do not have it already // if (bTrans) updateCommand = new OracleCommand ( "$ updatecommand $", connect); else updateCommand = new OracleCommand ("$ updateCommand $", New OracleConnection (ServiceCardConnectionString); UpdateCommand.commandtype = CommandType. StoredProcedure; updateCommand.Transaction = mytrans; OracleParameterCollection OracleParams = updateCommand.Parameters; $ updateparmadd $ // // Define the parameter mappings from the data table in the // dataset // $ updateprarmequ $} return updateCommand;.}

/ / -------------------------------------------------------------------------------------------- ---------------- // Sub BuildInsertCommands: // Initialize the parameterized load command for the dataadapter // ----------------- ---------------------------------------------- Private OracleCommand GetInsertCommand () {if (insertCommand == null) {// // Construct the command since we do not have it already // if (bTrans) insertCommand = new OracleCommand ( "$ insertcommand $", connect); else insertCommand = new OracleCommand ( "$ insertcommand $", new OracleConnection (ServiceCardConnectionString)); insertCommand.CommandType = CommandType.StoredProcedure; insertCommand.Transaction = mytrans; OracleParameterCollection OracleParams = insertCommand.Parameters; $ updateparmadd $ // // Define the parameter mappings from the data Table in the // dataset. // $ updatePRARMEQ $} Return INSERTCOMMAND;

///

/// INSERTS A New Card INTO The Database. /// a carddata containing detailed card information. /// Success OR Failure Of THE . database insert /// public bool Insert $ workobject $ ($ dataname $ $ paraname $) {if (dsCommand == null) {throw new System.ObjectDisposedException (GetType () FullName.); DSCommand.insertCommand = getInsertCommand (); DScommand.Update ($ Paraname $, $ DATANAME $. $ Constname $); /// Check for Table Errors to See eti the update failed. //Iff ($ paraname $ .haaserror) {$ PaaName $. $ Constname $]. GetErrorS () [0] .clearerrrs (); Return False;} else {$ paraName $ .acceptchange (); return true;}} //// /// INSERTS A New Card Into the Database. // a carddata containing detailed card information. /// Success or fiveure of the database inse . Rt /// public $ dataname $ Load $ workobject $ (string SN) {if (dsCommand == null) {throw new System.ObjectDisposedException (GetType () FullName.);} $ Dataname $ $ paraname $ = new $ dataname $ (); dsCommand.SelectCommand = GetLoadCommand (); dsCommand.SelectCommand.Parameters [VALUE_PARM] .Value = SN; dsCommand.Fill ($ paraname $, $ dataname $ $ constname $.); /// Check post conditions //

Return $ paraName $;}

public bool Update $ workobject $ ($ dataname $ $ paraname $) {if (dsCommand == null) {throw new System.ObjectDisposedException (GetType () FullName.);} dsCommand.UpdateCommand = GetUpdateCommand (); dsCommand.Update ($ PARANAME $, $ DATANAME $. $ constname $); // Check for Table Errors to see et........................... .. $]. GetErrorS () [0] .clearerrrs (); return false;} else {$ paraname $ .acceptchange (); return true;}} public bool delete $ workObject $ (string thekey) {bool result = false; oracleCommand deleteCommand = new OracleCommand ( "$ deletecommand $", new OracleConnection (ServiceCardConnectionString)); deleteCommand.Connection.Open (); deleteCommand.CommandType = CommandType.StoredProcedure; deleteCommand.Parameters.Add (new OracleParameter (CHARGE_CODE_PARM, OracleType.VarChar, 10 ))); DeleteCommand.Parameters [charge_code_parm] .value = charge_code; try {deletecomman d.ExecuteNonQuery (); result = true;} catch (Exception ex) {result = false; throw new Exception (ex.Message);} finally {deleteCommand.Connection.Close (); deleteCommand.Connection.Dispose (); deleteCommand .Parameters.clear (); deleteCommand.dispose ();} Return Result;

}

The template file is very simple: and the data sheet format is used instead, the program is generated according to the structure of the table, and the label settings in the template file generate the final code according to the structure of the table.

The code of the replacement section is as follows:

private StringBuilder ReplaceValue (StringBuilder content) {constList.Clear (); valueList.Clear (); InitConstList (); InitValueList (); int index = 0; foreach (string item in constList) {content.Replace (item, valueList [index ] .Tostring ()); index = 1;

} Return Content;} private void initconstlist () {string str = ""; // 1 str = "$ classname $"; constlist.add (str); // 2 str = "$ PARM $"; constelist.add ( Str); // 3 str = "$ TABLENAME $"; consTList.add (str); // 4 str = "$ dataname $"; constlist.add (str); // 5 Str = "$ constname $"; Constlist.add (str); // 6 str = "$ loadCommand $"; constlist.add (str); // 7 str = "$ deleteCommand $"; constlist.add (str); // 8 str = "$ DeleteConest $ "; constlist.add (str); // 9 str =" $ INSERTCOMMAND $ "; constlist.add (str); // 10 Str =" $ updateCommand $ "; constlist.add (str); // 11 Str = "$ updateParmAdd $"; constlist.add (str); // 12 str = "$ updatePRARMEQU $"; constlist.add (str); // 13 str = "$ paraname $"; constlist.add (STR) ;

// 14 Str = "$ systemclassname $"; constlist.add (str); // 15 str = "$ WorkObject $"; constlist.add (str);

} Private void initvaluelist () {string str = ""; // $ classname $ = class name 1 Data Access layer class name Str = DataName.Text "S"; // ClassName.Text; Valuelist.Add (STR); / / $ PARM $ = Declaring the parameter 2 Str = T1; valuelist.add (str); // $ TABLENAME $ = database name 3 str = start (STR); // $ dataname $ = Represents the class name of the data object class 4 str = DataName.Text "data"; valuelist.add (str); // $ constname $ = representing the constant name of the data object table name 5 str = startAblename "_ table" Valuelist.add (str); // $ loadCommand $ = loading stored procedure name 6 str = "load _" start (STR); // $ deleteCommand $ = Delete stored procedure name 7 str = "delete_" Strtables; Valuelist.add (STR); // $ deleteconest $ = Delete Parameter Description 8 Str = "// You Shuld Add Delete PARM"; Valuelist.Add (STR); // $ INSERTCOMMAND $ = New Save Procedure Name 9 str = "INSERT _" strablename ;; valuelist.add (str); // $ updateCommand $ = update stored procedure name 10 str = "update _" stratablename ;; valuelist.add (str); // $ updateparmadd $ = Increase the parameter 11 Str = T2; valuelist.add (str); // $ updateprarmequ $ = Source column 12 str = T3; valuelist.add (str); // $ paraName $ = Service object name from logic layer 13 str = dataname.text.tolower () ;; valuelist.add (str); // increase the processing of the business logic layer Str = DataName.Text "System"; Valuelist. Add (STR);

// Add the object str = DataName.Text; Valuelist.Add (STR);

}

General thought has been described, clearly required, please contact us

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

New Post(0)