浅谈代码生成工具《CodeSmith》的使用(1)

      尽管现在网上的代码生成工具很多,如国内知名的李天平写的 动软.Net代码生成器(Codematic是一款为程序员设计的自动代码生成器,网址http://www.maticsoft.com/ )、我以前的同事写的繁星网站代码生成器(繁星代码生成器也正是也模板为灵魂为实现的,模板库体现的是我们大家的智慧结晶。他的目标就是:灵活实现您的需求,通过模板分享让您轻松、快速开发。网址:http://www.cnblogs.com/lxf120/archive/2009/01/19/1371118.html)等等,但在我看来他们都不能满足目前大多数软件企业的框架代码生成,因为同样的基于工厂模式Petshop框架各个公司有不同的用法,灵活多变。我非常赏识国外著名CodeSmith代码生成器,它可以根据自己的框架代码模板灵活的书写CodeSmith语法模板,这样我们只是前期维护好模板就可以快速开发出框架代码。
      首先我们要导入CodeSmith语法命名空间:(语法类似C#)      

      <%@ CodeTemplate Language="C#" TargetLanguage="C#" ResponseEncoding="UTF-8" Description="Generates a very simple business object." %>

      <%@ Property Name="NameSpace" Type="System.String" Default="Wnkj" Category="Text" Description="Namespace for this class" %>
      <%@ Assembly Name="SchemaExplorer" %>
      <%@ Assembly Name="System.Data" %>
      <%@ Import Namespace="SchemaExplorer" %>
      <%@ Import Namespace="System.Data" %>
      <%@ Import Namespace="System.Text" %>
      其次我们在下面书写代码模板,下面我就以SqlHelper为例:
      

ContractedBlock.gif ExpandedBlockStart.gif Code
using System;
using System.Data;
using System.Xml;
using System.Data.SqlClient;
using System.Collections;
namespace <%= NameSpace %>.IDataAccessLayer
ExpandedBlockStart.gifContractedBlock.gif
{
ExpandedSubBlockStart.gifContractedSubBlock.gif    
/**//// <summary>
    
/// The SqlHelper class is intended to encapsulate 
    
/// common uses of SqlClient.
    
/// </summary>

    public sealed class SqlHelper
ExpandedSubBlockStart.gifContractedSubBlock.gif        
{
ExpandedSubBlockStart.gifContractedSubBlock.gif          
private SqlHelper() {}

ContractedSubBlock.gifExpandedSubBlockStart.gif
ExecuteNonQuery#region ExecuteNonQuery

ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**//// <summary>
        
/// Execute a SqlCommand (that returns no resultset and takes no parameters) against the database specified in 
        
/// the connection string. 
        
/// </summary>
        
/// <remarks>
        
/// e.g.:  
        
///  int result = ExecuteNonQuery(connString, CommandType.StoredProcedure, "PublishOrders");
        
/// </remarks>
        
/// <param name="connectionString">a valid connection string for a SqlConnection</param>
        
/// <param name="commandType">the CommandType (stored procedure, text, etc.)</param>
        
/// <param name="commandText">the stored procedure name or T-SQL command</param>
        
/// <returns>an int representing the number of rows affected by the command</returns>

        public static int ExecuteNonQuery(string connectionString, CommandType commandType, string commandText)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
{
            
//pass through the call providing null for the set of SqlParameters
            return ExecuteNonQuery(connectionString, commandType, commandText, (SqlParameter[])null);
        }


ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**//// <summary>
        
/// Execute a SqlCommand (that returns no resultset) against the database specified in the connection string 
        
/// using the provided parameters.
        
/// </summary>
        
/// <remarks>
        
/// e.g.:  
        
///  int result = ExecuteNonQuery(connString, CommandType.StoredProcedure, "PublishOrders", new SqlParameter("@prodid", 24));
        
/// </remarks>
        
/// <param name="connectionString">a valid connection string for a SqlConnection</param>
        
/// <param name="commandType">the CommandType (stored procedure, text, etc.)</param>
        
/// <param name="commandText">the stored procedure name or T-SQL command</param>
        
/// <param name="commandParameters">an array of SqlParamters used to execute the command</param>
        
/// <returns>an int representing the number of rows affected by the command</returns>

        public static int ExecuteNonQuery(string connectionString, CommandType commandType, string commandText, params SqlParameter[] commandParameters)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
{
            
//create & open a SqlConnection, and dispose of it after we are done.
            using (SqlConnection cn = new SqlConnection(connectionString))
ExpandedSubBlockStart.gifContractedSubBlock.gif            
{
                cn.Open();

                
//call the overload that takes a connection in place of the connection string
                return ExecuteNonQuery(cn, commandType, commandText, commandParameters);
            }

        }


ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**//// <summary>
        
/// Execute a stored procedure via a SqlCommand (that returns no resultset) against the database specified in 
        
/// the connection string using the provided parameter values.  This method will query the database to discover the parameters for the 
        
/// stored procedure (the first time each stored procedure is called), and assign the values based on parameter order.
        
/// </summary>
        
/// <remarks>
        
/// This method provides no access to output parameters or the stored procedure's return value parameter.
        
/// 
        
/// e.g.:  
        
///  int result = ExecuteNonQuery(connString, "PublishOrders", 24, 36);
        
/// </remarks>
        
/// <param name="connectionString">a valid connection string for a SqlConnection</param>
        
/// <param name="spName">the name of the stored prcedure</param>
        
/// <param name="parameterValues">an array of objects to be assigned as the input values of the stored procedure</param>
        
/// <returns>an int representing the number of rows affected by the command</returns>

        public static int ExecuteNonQuery(string connectionString, string spName, params object[] parameterValues)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
{
            
//if we receive parameter values, we need to figure out where they go
            if ((parameterValues != null&& (parameterValues.Length > 0)) 
ExpandedSubBlockStart.gifContractedSubBlock.gif            
{
                
//pull the parameters for this stored procedure from the parameter cache (or discover them & populate the cache)
                SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(connectionString, spName);

                
//assign the provided values to these parameters based on parameter order
                AssignParameterValues(commandParameters, parameterValues);

                
//call the overload that takes an array of SqlParameters
                return ExecuteNonQuery(connectionString, CommandType.StoredProcedure, spName, commandParameters);
            }

                
//otherwise we can just call the SP without params
            else 
ExpandedSubBlockStart.gifContractedSubBlock.gif            
{
                
return ExecuteNonQuery(connectionString, CommandType.StoredProcedure, spName);
            }

        }


ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**//// <summary>
        
/// Execute a SqlCommand (that returns no resultset and takes no parameters) against the provided SqlConnection. 
        
/// </summary>
        
/// <remarks>
        
/// e.g.:  
        
///  int result = ExecuteNonQuery(conn, CommandType.StoredProcedure, "PublishOrders");
        
/// </remarks>
        
/// <param name="connection">a valid SqlConnection</param>
        
/// <param name="commandType">the CommandType (stored procedure, text, etc.)</param>
        
/// <param name="commandText">the stored procedure name or T-SQL command</param>
        
/// <returns>an int representing the number of rows affected by the command</returns>

        public static int ExecuteNonQuery(SqlConnection connection, CommandType commandType, string commandText)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
{
            
//pass through the call providing null for the set of SqlParameters
            return ExecuteNonQuery(connection, commandType, commandText, (SqlParameter[])null);
        }


ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**//// <summary>
        
/// Execute a SqlCommand (that returns no resultset) against the specified SqlConnection 
        
/// using the provided parameters.
        
/// </summary>
        
/// <remarks>
        
/// e.g.:  
        
///  int result = ExecuteNonQuery(conn, CommandType.StoredProcedure, "PublishOrders", new SqlParameter("@prodid", 24));
        
/// </remarks>
        
/// <param name="connection">a valid SqlConnection</param>
        
/// <param name="commandType">the CommandType (stored procedure, text, etc.)</param>
        
/// <param name="commandText">the stored procedure name or T-SQL command</param>
        
/// <param name="commandParameters">an array of SqlParamters used to execute the command</param>
        
/// <returns>an int representing the number of rows affected by the command</returns>

        public static int ExecuteNonQuery(SqlConnection connection, CommandType commandType, string commandText, params SqlParameter[] commandParameters)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
{    
            
//create a command and prepare it for execution
            SqlCommand cmd = new SqlCommand();
            PrepareCommand(cmd, connection, (SqlTransaction)
null, commandType, commandText, commandParameters);
            
            
//finally, execute the command.
            int retval = cmd.ExecuteNonQuery();
            
            
// detach the SqlParameters from the command object, so they can be used again.
            cmd.Parameters.Clear();
            
return retval;
        }


ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**//// <summary>
        
/// Execute a stored procedure via a SqlCommand (that returns no resultset) against the specified SqlConnection 
        
/// using the provided parameter values.  This method will query the database to discover the parameters for the 
        
/// stored procedure (the first time each stored procedure is called), and assign the values based on parameter order.
        
/// </summary>
        
/// <remarks>
        
/// This method provides no access to output parameters or the stored procedure's return value parameter.
        
/// 
        
/// e.g.:  
        
///  int result = ExecuteNonQuery(conn, "PublishOrders", 24, 36);
        
/// </remarks>
        
/// <param name="connection">a valid SqlConnection</param>
        
/// <param name="spName">the name of the stored procedure</param>
        
/// <param name="parameterValues">an array of objects to be assigned as the input values of the stored procedure</param>
        
/// <returns>an int representing the number of rows affected by the command</returns>

        public static int ExecuteNonQuery(SqlConnection connection, string spName, params object[] parameterValues)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
{
            
//if we receive parameter values, we need to figure out where they go
            if ((parameterValues != null&& (parameterValues.Length > 0)) 
ExpandedSubBlockStart.gifContractedSubBlock.gif            
{
                
//pull the parameters for this stored procedure from the parameter cache (or discover them & populate the cache)
                SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(connection.ConnectionString, spName);

                
//assign the provided values to these parameters based on parameter order
                AssignParameterValues(commandParameters, parameterValues);

                
//call the overload that takes an array of SqlParameters
                return ExecuteNonQuery(connection, CommandType.StoredProcedure, spName, commandParameters);
            }

                
//otherwise we can just call the SP without params
            else 
ExpandedSubBlockStart.gifContractedSubBlock.gif            
{
                
return ExecuteNonQuery(connection, CommandType.StoredProcedure, spName);
            }

        }


ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**//// <summary>
        
/// Execute a SqlCommand (that returns no resultset and takes no parameters) against the provided SqlTransaction. 
        
/// </summary>
        
/// <remarks>
        
/// e.g.:  
        
///  int result = ExecuteNonQuery(trans, CommandType.StoredProcedure, "PublishOrders");
        
/// </remarks>
        
/// <param name="transaction">a valid SqlTransaction</param>
        
/// <param name="commandType">the CommandType (stored procedure, text, etc.)</param>
        
/// <param name="commandText">the stored procedure name or T-SQL command</param>
        
/// <returns>an int representing the number of rows affected by the command</returns>

        public static int ExecuteNonQuery(SqlTransaction transaction, CommandType commandType, string commandText)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
{
            
//pass through the call providing null for the set of SqlParameters
            return ExecuteNonQuery(transaction, commandType, commandText, (SqlParameter[])null);
        }


ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**//// <summary>
        
/// Execute a SqlCommand (that returns no resultset) against the specified SqlTransaction
        
/// using the provided parameters.
        
/// </summary>
        
/// <remarks>
        
/// e.g.:  
        
///  int result = ExecuteNonQuery(trans, CommandType.StoredProcedure, "GetOrders", new SqlParameter("@prodid", 24));
        
/// </remarks>
        
/// <param name="transaction">a valid SqlTransaction</param>
        
/// <param name="commandType">the CommandType (stored procedure, text, etc.)</param>
        
/// <param name="commandText">the stored procedure name or T-SQL command</param>
        
/// <param name="commandParameters">an array of SqlParamters used to execute the command</param>
        
/// <returns>an int representing the number of rows affected by the command</returns>

        public static int ExecuteNonQuery(SqlTransaction transaction, CommandType commandType, string commandText, params SqlParameter[] commandParameters)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
{
            
//create a command and prepare it for execution
            SqlCommand cmd = new SqlCommand();
            PrepareCommand(cmd, transaction.Connection, transaction, commandType, commandText, commandParameters);
            
            
//finally, execute the command.
            int retval = cmd.ExecuteNonQuery();
            
            
// detach the SqlParameters from the command object, so they can be used again.
            cmd.Parameters.Clear();
            
return retval;
        }


ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**//// <summary>
        
/// Execute a stored procedure via a SqlCommand (that returns no resultset) against the specified 
        
/// SqlTransaction using the provided parameter values.  This method will query the database to discover the parameters for the 
        
/// stored procedure (the first time each stored procedure is called), and assign the values based on parameter order.
        
/// </summary>
        
/// <remarks>
        
/// This method provides no access to output parameters or the stored procedure's return value parameter.
        
/// 
        
/// e.g.:  
        
///  int result = ExecuteNonQuery(conn, trans, "PublishOrders", 24, 36);
        
/// </remarks>
        
/// <param name="transaction">a valid SqlTransaction</param>
        
/// <param name="spName">the name of the stored procedure</param>
        
/// <param name="parameterValues">an array of objects to be assigned as the input values of the stored procedure</param>
        
/// <returns>an int representing the number of rows affected by the command</returns>

        public static int ExecuteNonQuery(SqlTransaction transaction, string spName, params object[] parameterValues)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
{
            
//if we receive parameter values, we need to figure out where they go
            if ((parameterValues != null&& (parameterValues.Length > 0)) 
ExpandedSubBlockStart.gifContractedSubBlock.gif            
{
                
//pull the parameters for this stored procedure from the parameter cache (or discover them & populate the cache)
                SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(transaction.Connection.ConnectionString, spName);

                
//assign the provided values to these parameters based on parameter order
                AssignParameterValues(commandParameters, parameterValues);

                
//call the overload that takes an array of SqlParameters
                return ExecuteNonQuery(transaction, CommandType.StoredProcedure, spName, commandParameters);
            }

                
//otherwise we can just call the SP without params
            else 
ExpandedSubBlockStart.gifContractedSubBlock.gif            
{
                
return ExecuteNonQuery(transaction, CommandType.StoredProcedure, spName);
            }

        }



        
#endregion
 ExecuteNonQuery
        }

        
}

这是一般不需要改变的东西,直接贴成你需要的模板样式。后面待续……



转载于:https://www.cnblogs.com/xj0112/archive/2009/07/26/1531589.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值