Skip to content

T4 Templates for ASP.NET Web Form CRUD Application

December 31, 2011

My projects are usually simple ASP.NET web form applications with SQL database basic CRUD operations. That’s what you do everyday when you are an in-house developer for a manufacturing company. I was tired of writing the same pattern of code on and on and finally I decided to learn T4 and this is what I came up. It’s very basic and the outputs are not complete code files but just code snippets so that you can insert into your existing ASP.NET web form framework files .

I created an independent Visual Studio 2010 project for my T4 templates following Oleg Sych’s blogs.  Three template files are shown under ‘Templates’ folder. they should be disabled for code generation by removing ‘TextTemplatingFileGenerator‘ in Properties:Custom Tool field leaving it as blank.

You need three code templates for an aspx web form project: an aspx file, a data access layer(DAL) VB file, a SQL stored procedures file for CRUD operations which will be called from the DAL code. The code behind VB code for aspx.vb was simply attached in the aspx template as a script block.

The three green lined ones are the script files which actually generate the ouput code referencing the previously mentioned templates. You can execute each of them by ‘Run custom tool’ context menu. Then, the actual output files are generated under each script file and will have a proper target extensions such as .aspx, .sql, .vb.

Here is an example of an aspx template and script files. Other templates and script files are attached as docx files at the end of this post.

MakeAspx.tt:

<#@ template language="VB" hostSpecific="True" #>
<#@ output extension="aspx" #>

<#@ include file="T4Toolbox.tt" #>
<#@ include file="Templates\AspxTemplate.tt" #>

<#
    Dim template As AspxTemplate = New AspxTemplate()
    template.ServerName="SQL2008"
    template.DatabaseName = "SupplierTest"
    template.TableName = "BudgetCategory"
    template.Render()
#>

AspxTemplate.tt:

<!--
    This template is for generating Aspx page code for DetailsView and GridView with basic CRUD functions. 
    It assumes the databse table includes columns of [ID],[UpdatedBy],[DateUpdated]. -->
<#@ template language="VB" debug="true" #>
<#@ output extension="aspx" #>
<#@ assembly name="Microsoft.SqlServer.ConnectionInfo" #>
<#@ assembly name="Microsoft.SqlServer.Management.Sdk.Sfc" #>
<#@ assembly name="Microsoft.SqlServer.Smo" #>
<#@ assembly Name="System.Xml" #>
<#@ assembly Name="System.Core.dll" #>
<#@ assembly Name="System.Xml.Linq.dll" #>
<#@ assembly Name="System.Windows.Forms.dll" #>
<#@ import namespace="System" #>
<#@ import namespace="System.IO" #>
<#@ import namespace="System.Diagnostics" #>
<#@ import namespace="System.Linq" #>
<#@ import namespace="System.Xml" #>
<#@ import namespace="System.Xml.Linq" #>
<#@ import namespace="System.Collections" #>
<#@ import namespace="System.Collections.Generic" #>
<#@ import namespace="Microsoft.VisualBasic" #>
<#@ import namespace="Microsoft.SqlServer.Management.Smo" #>
<#@ import namespace="T4Toolbox" #>
<#@ include file="Utility.tt" #>
<#+
Public Class AspxTemplate
 Inherits Template
 
 Public ServerName As String
 Public DatabaseName As String
 Public TableName As String
 
 Private InputParamTypeName As String
  
 Public Overrides Function TransformText() As String
  If TableName is nothing then
   Throw new Exception("TableName is not given.")
   Return ""
  End if
 
  Dim server As Server = New Server(ServerName)
        Dim database As Database = New Database(server, DatabaseName)
        Dim table As Table = New Table(database, TableName)
        table.Refresh()  
#>
<%@ Page Title="<#= table.Name #>" Language="vb" AutoEventWireup="false"
    CodeBehind="MakeVb.vb" Inherits="ProjectName.<#= table.Name #>" %>
<%@ Register TagPrefix="asp" Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit"  %>
xmlns="<a href="http://www.w3.org/1999/xhtml%22%3E%3Cbody%3E%3Cform">http://www.w3.org/1999/xhtml"><body><form</a> id="form1" runat="server">
 
    LinkButton ID="linkAdd" runat="server" Text="Add" />

    <asp:Panel ID="panelAdd" runat="server" Visible="false">
        DetailsView ID="DetailsView_<#= table.Name #>" runat="server"
            AutoGenerateRows="False"  CssClass="auc_formviewdata" DefaultMode="Insert" AllowPaging="true"
            DataSourceID="ObjectDataSource_BudgetCategory" EnableModelValidation="True"
            BorderColor="#999999" BorderStyle="Solid" BorderWidth="1px" ForeColor="#333333" GridLines="None"
            CellPadding="2" >

         <CommandRowStyle BackColor="#E2DED6" Font-Bold="True" Height="20px" />
         <FieldHeaderStyle BackColor="#E9ECF1" Font-Bold="True" Width="80px" HorizontalAlign="Right"/>
         <RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
         <EditRowStyle BackColor="#999999" />
         <AlternatingRowStyle BackColor="White" ForeColor="#284775" />
        
         <HeaderStyle BackColor="#897CAF" Font-Bold="True" ForeColor="White" />
         <FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" /--%>

            <Fields>
<#+
  PushIndent(Vbtab):PushIndent(Vbtab):PushIndent(Vbtab):PushIndent(Vbtab)
        For Each column As Column In table.Columns
   IF column.Name.ToUpper<>"ID" AND column.Name.ToUpper<>"DATEUPDATED" AND column.Name.ToUpper<>"UPDATEDBY" AND NOT column.Computed THEN
    
    WriteLine("")
    PushIndent(Vbtab):
     WriteLine("")
                    PushIndent(Vbtab):
      WriteLine("")
     PopIndent():
                 WriteLine("")
     WriteLine("")
     PushIndent(Vbtab):

    InputParamTypeName=Utility.FromSqlToSystemType(column.DataType.Name)
    IF InputParamTypeName="String" Then
     IF column.Name.ToUpper="NOTE" Then
                     WriteLine("
      PushIndent(Vbtab):
                         WriteLine("Text='' TextMode=""MultiLine"" Rows=""4"" /> ")
      PopIndent()
      
     Elseif column.Name.ToUpper="STATUS" Then
                     WriteLine("
                        PushIndent(Vbtab)
       WriteLine("SelectedValue=''>")
                            WriteLine("")
                            WriteLine("")
      PopIndent()  
                        WriteLine("")
     
     Else 'Normal String
                     WriteLine("
      PushIndent(Vbtab):
                         WriteLine("Text='' /> ")
       Writeline("
       PushIndent(Vbtab):
                             Writeline("ControlToValidate=""txtNew"+column.Name+""" ValidationExpression=""[ ]*[0-9]*[ ]*"" />--%>")
      PopIndent():PopIndent()
     End If
    
    ElseIF InputParamTypeName="Date" Then
                    WriteLine("
     PushIndent(Vbtab):
                        WriteLine("Text='' />")  
                        WriteLine("
                        PushIndent(Vbtab):
       WriteLine("TargetControlID=""txtNew"""+column.Name+""" PopupPosition=""BottomRight"" />")       
                 PopIndent():PopIndent()
     
    ElseIF InputParamTypeName="Boolean" Then
                    WriteLine("
     PushIndent(Vbtab):
                        WriteLine("Checked=''  /> ")
     PopIndent()
    End If
   
    PopIndent()
             WriteLine("")
    PopIndent()
             WriteLine("")
   End If
        Next
  PopIndent():PopIndent():PopIndent():PopIndent()  
#>
                CommandField ShowInsertButton="true" ShowCancelButton="true" />                            
            </Fields>
        </asp:DetailsView>
        <br /><br />
    </asp:Panel>   

    GridViewID="GridView_<#= table.Name #>" runat="server" CssClass="auc_gridviewdata"
        AllowSorting="True" AutoGenerateColumns="False" CellPadding="2" EnableModelValidation="True"
        DataSourceID="ObjectDataSource_BudgetCategory" DataKeyNames="ID" >

        <HeaderStyle HorizontalAlign="Center" VerticalAlign="Middle" CssClass="auc_gridviewheader"
            Wrap="True" BackColor="#726891" ForeColor="White" />
        <PagerStyle CssClass="textbox" Font-Size="X-Small"
            BorderStyle="Solid" BorderWidth="1px" BorderColor="Gray" />

        <Columns>
           CommandField ShowEditButton="true" ShowDeleteButton="true" ItemStyle-Width="60px" />

<#+
  PushIndent(Vbtab):PushIndent(Vbtab):PushIndent(Vbtab):PushIndent(Vbtab)
        For Each column As Column In table.Columns
   IF column.Name.ToUpper<>"ID" AND column.Name.ToUpper<>"DATEUPDATED" AND column.Name.ToUpper<>"UPDATEDBY" AND NOT column.Computed THEN
    
    WriteLine("")
    PushIndent(Vbtab):
     WriteLine("")
                    PushIndent(Vbtab):
      WriteLine("")
     PopIndent():
                 WriteLine("")
     WriteLine("")
     PushIndent(Vbtab):

    InputParamTypeName=Utility.FromSqlToSystemType(column.DataType.Name)
    IF InputParamTypeName="String" Then
     IF column.Name.ToUpper="NOTE" Then
                     WriteLine("
      PushIndent(Vbtab):
                         WriteLine("Text='' TextMode=""MultiLine"" Rows=""4"" /> ")
      PopIndent()
      
     Elseif column.Name.ToUpper="STATUS" Then
                     WriteLine("
                        PushIndent(Vbtab)
       WriteLine("SelectedValue=''>")
                            WriteLine("")
                            WriteLine("")
      PopIndent()  
                        WriteLine("")
     
     Else 'Normal String
                     WriteLine("
      PushIndent(Vbtab):
                         WriteLine("Text='' /> ")
       Writeline("
       PushIndent(Vbtab):
                             Writeline("ControlToValidate=""txt"+column.Name+""" ValidationExpression=""[ ]*[0-9]*[ ]*"" />--%>")
      PopIndent():PopIndent()
     End If
    
    ElseIF InputParamTypeName="Date" Then
                    WriteLine("
     PushIndent(Vbtab):
                        WriteLine("Text='' />")  
                        WriteLine("
                        PushIndent(Vbtab):
       WriteLine("TargetControlID=""txtNew"""+column.Name+""" PopupPosition=""BottomRight"" />")       
                 PopIndent():PopIndent()
     
    ElseIF InputParamTypeName="Boolean" Then
                    WriteLine("
     PushIndent(Vbtab):
                        WriteLine("Checked=''  /> ")
     PopIndent()
    End If
   
             PopIndent():
             WriteLine("")
    PopIndent():
             WriteLine("")
   End If
        Next
  PopIndent():PopIndent():PopIndent():PopIndent()  
#>                 

            BoundFieldDataField="UpdatedBy" HeaderText="Updated By" ReadOnly="true" />
            BoundField DataField="DateUpdated" HeaderText="Date Updated" ReadOnly="true" DataFormatString="{0:dd-MMM-yyyy}" />
            BoundField DataField="ID" ReadOnly="true" Visible="false" />
        </Columns>
    GridView>                  
   
ObjectDataSource ID="ObjectDataSource_<#= table.Name #>" runat="server"
    TypeName="MyCompanyERPService.ObjectDataSource<#= table.Name #>" SelectMethod="Get<#= table.Name #>List"
    UpdateMethod="Update<#= table.Name #>" InsertMethod="Insert<#= table.Name #>" DeleteMethod="Delete<#= table.Name #>">
    <SelectParameters>
        <!--asp:Parameter Name="bOpenOnly" Type="Boolean" DefaultValue="False" /-->
    </SelectParameters>
    <UpdateParameters>
        Int32" />
<#+     PushIndent(Vbtab):PushIndent(Vbtab)
  For Each column As Column In table.Columns
   IF column.Name.ToUpper<>"ID" AND column.Name.ToUpper<>"DATEUPDATED" AND column.Name.ToUpper<>"UPDATEDBY" AND NOT column.Computed THEN
    Write("<asp:Parameter Name="""+column.Name+""" Type=""")
    
    InputParamTypeName=Utility.FromSqlToSystemType(column.DataType.Name)
    Select Case InputParamTypeName.ToUpper
     Case "STRING"
      Write("String"" />")
     Case "INTEGER"
      Write("Int32"" />")
     Case "DOUBLE"
      Write("Double"" />")
     Case "DATE"
      Write("DateTime"" />")
     Case "BOOLEAN"
      Write("Boolean"" />")
     Case Else
      Write("Object"" />")
    End Select
   
    WriteLine("")
   END IF
        Next
  PopIndent():PopIndent()
  #>
  SessionParameter SessionField="UserID" Name="By" Type="String" />
    </UpdateParameters>
    <InsertParameters>
  <#+    
  PushIndent(Vbtab):PushIndent(Vbtab)
  For Each column As Column In table.Columns
   IF column.Name.ToUpper<>"ID" AND column.Name.ToUpper<>"DATEUPDATED" AND column.Name.ToUpper<>"UPDATEDBY" AND NOT column.Computed THEN
    Write("<asp:Parameter Name="""+column.Name+""" Type=""")
    
    InputParamTypeName=Utility.FromSqlToSystemType(column.DataType.Name)
    Select Case InputParamTypeName.ToUpper
     Case "STRING"
      Write("String"" />")
     Case "INTEGER"
      Write("Int32"" />")
     Case "DOUBLE"
      Write("Double"" />")
     Case "DATE"
      Write("DateTime"" />")
     Case "BOOLEAN"
      Write("Boolean"" />")
     Case Else
      Write("Object"" />")
    End Select
   
    WriteLine("")
   END IF
        Next
  PopIndent():PopIndent()
  #>
        SessionParameter SessionField="UserID" Name="By" Type="String" />
        <asp:Parameter Name="ID" Type="Int32" Direction="Output" />
    </InsertParameters>
    <DeleteParameters>
        <asp:Parameter Name="ID" Type="Int32" />
        SessionParameter SessionField="UserID" Name="By" Type="String" />
    </DeleteParameters>
</asp:ObjectDataSource>

<script type="text/VB">
 'This is the code-behind class of the aspx file

    Public Property EditorRoleSum As Integer
        Get
            Return ViewState("<#= table.Name.ToLower #>editorrolesum")
        End Get
        Set(value As Integer)
            ViewState("<#= table.Name.ToLower #>editorrolesum") = value
        End Set
    End Property

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        If Not IsPostBack Then
            If (Session("rolesum") And EditorRoleSum) = 0 Then
                linkAdd.Visible = False
                panelAdd.Visible = False
            End If
        End If
    End Sub

    Private Sub GridView_<#= table.Name #>_RowDataBound(sender As Object, e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GridView_<#= table.Name

#>.RowDataBound
        Dim gv As GridView = CType(sender, GridView)

        If e.Row.RowType = DataControlRowType.DataRow Then
            Utility.GridVewTool.AddDeleteConfirmScript(gv, e.Row, 0, True)

            'Role check
            If (Session("rolesum") And EditorRoleSum) = 0 Then
                e.Row.Cells(0).Visible = False
            Else
                e.Row.Cells(0).Visible = True
            End If
        End If
    End Sub

    Private Sub linkAdd_Click(sender As Object, e As System.EventArgs) Handles linkAdd.Click
        panelAdd.Visible = True
    End Sub

    Private Sub DetailsView_<#= table.Name #>_ItemCommand(sender As Object, e As System.Web.UI.WebControls.DetailsViewCommandEventArgs) Handles DetailsView_<#=

table.Name #>.ItemCommand
        panelAdd.Visible = False
    End Sub

    Private Sub DetailsView_<#= table.Name #>_ItemInserted(sender As Object, e As System.Web.UI.WebControls.DetailsViewInsertedEventArgs) Handles DetailsView_<#=

table.Name #>.ItemInserted
        GridView_<#= table.Name #>.DataBind()
    End Sub 
</script>
</form></body></html>
<#+
        Return Me.GenerationEnvironment.ToString()
 End Function
End Class
#>

Attachments:  AspxTemplate, VbTemplate, CrudTemplate, Scripts

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: