Click here to Skip to main content
15,895,809 members
Articles / Database Development / SQL Server

Template based code generation

Rate me:
Please Sign up or sign in to vote.
4.48/5 (10 votes)
10 Mar 2005CPOL9 min read 70.7K   1.6K   56  
An article about template based code generation and a demonstration of how to quickly generate a wrapper class for stored procedures.
@@Template@@
<%-references
    System.Data.dll
    System.Threading
   
    DatabaseCatalogReader.dll
%>>
<%-namespaces
using System.Text;
using System.Data;

using DatabaseCatalogReader;
%>>
<%-class
    
    string pp(ProcParameter[] Parameters)
    {
        int i=0;
        StringBuilder sb = new StringBuilder();
        
        string separator = ", ";
        if(Parameters.Length > 8)
        {
            separator = ",\n\t\t\t";
            sb.Append("\n\t\t\t");
        }
        
        foreach(ProcParameter p in Parameters)
        {   
            if(i++ > 0)
                sb.Append(separator);
                
            if(p.Direction == ParameterDirection.Output)                
                sb.AppendFormat("out {0} {1}", p.ToNetType(), p.Name.Substring(1));
            else
                sb.AppendFormat("{0} {1}", p.ToNetType(), p.Name.Substring(1));
        }
        
        return sb.ToString();
    }
%>>
<%
   
    DatabaseCatalog cat = new DatabaseCatalog();
    if(!cat.IsConnected())
        throw new ApplicationException("No connection to database");
        
    string nameSpace = "ClearViews.Repository.Module.Sql";
    string className = cat.Name;
    
%>>
/* 
    This file was created by a code generation tool.
    Do not modify it.
*/ 

using System;
using System.Data;
using System.Data.SqlClient;
using System.Xml;


namespace <%= nameSpace %>
{
    public class <%= className %>
    { 
        string connString = "<%=cat.ConnectionString%>";
        SqlConnection GetSqlConnection()
        { 
            return new SqlConnection(connString);
        }
        
        public <%= className %>()
        { 
        }
        
        <%
        foreach(SqlStoredProcedure proc in cat.GetStoredProcedures())
        {
            string retType = "void";
            string retValue = null;
            string cmdExecute = "cmd.ExecuteNonQuery();";
            if(proc.ExecuteType == ExecuteType.Reader)
            {
                retType = "SqlDataReader" ;
                cmdExecute = "SqlDataReader reader = cmd.ExecuteReader();" ;
                retValue = "return reader;";
            }
            else
            if(proc.ExecuteType == ExecuteType.XmlReader)
            {
                retType = "XmlReader" ;
                cmdExecute = "XmlReader reader = cmd.ExecuteXmlReader();" ;
                retValue = "return reader;";
            }
            else
            if(proc.ExecuteType == ExecuteType.Scalar)
            {
                retType = "object" ;
                cmdExecute = "object scalar = cmd.ExecuteScalar();" ;
                retValue = "return scalar;";
            }
        %>
        public <%=retType%> <%=proc.Name%>(<%=pp(proc.GetParameters())%>)
        {
            SqlConnection conn = GetSqlConnection();
            using(conn)
            { 
                if(conn.State == ConnectionState.Closed)
                    conn.Open();
                    
                SqlCommand cmd = new SqlCommand("<%= proc.Name %>", conn);
                cmd.CommandType = CommandType.StoredProcedure; SqlParameter param;
            <% 
            foreach(ProcParameter p in proc.GetParameters()) { 
            %>
                param = new SqlParameter("<%=p.Name%>", SqlDbType.<%=p.Type%>, <%=p.Length%>);
                cmd.Parameters.Add(param);
                param.Direction = ParameterDirection.<%=p.Direction%>;
                <%if(p.Direction == ParameterDirection.Input) {%>>
                param.Value = <%=p.Name.Substring(1)%>;
                <%}%>>
            <%
            } // foreach(..)
            %>
                // execute the stored procedure
                <%=cmdExecute%>
                
            <%
            foreach(ProcParameter p in proc.GetParameters()) {
                if(p.Direction == ParameterDirection.Output) {
            %> <%! fdfdf %>>
                <%=p.Name.Substring(1)%> = (<%=p.ToNetType()%>)cmd.Parameters["<%=p.Name%>"].Value;
            <%
                } // if(..)
            } // foreach(..)
            %>>
            <% if(retValue != null) { %>
                <%= retValue %>
            <% } %>>
            }
        }
        <%
        } // foreach(..)
        %>
		public SqlDataReader GetReader(string query)
		{
		    SqlConnection conn = GetSqlConnection();
            using(conn)
            {
				if(conn.State == ConnectionState.Closed)
					conn.Open();
				SqlCommand cmd = new SqlCommand(query, conn);
				return cmd.ExecuteReader();
			}
		} 
		            
		public XmlReader GetXmlReader(string query)
		{
		    SqlConnection conn = GetSqlConnection();
            using(conn)
            {
				if(conn.State == ConnectionState.Closed)
					conn.Open();
				SqlCommand cmd = new SqlCommand(query, conn);
				return cmd.ExecuteXmlReader();
			}
		}
		
		public object GetScalar(string query)
		{
		    SqlConnection conn = GetSqlConnection();
            using(conn)
            {
				if(conn.State == ConnectionState.Closed)
					conn.Open();
				SqlCommand cmd = new SqlCommand(query, conn);
				return cmd.ExecuteScalar();
			}
		}                    
    }
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Web Developer
United States United States
I am a consultant, trainer, software archtect/engineer, since the early 1980s, working in the greater area of Boston, MA, USA.

My work comprises the entire spectrum of software, shrink-wrapped applications, IT client-server, systems and protocol related work, compilers and operating systems, and more ....

I am currently focused on platform development for distributed computing in service oriented data centers.

Comments and Discussions