CodeSmith系列(三)——使用CodeSmith生成ASP.NET页面

  1. 云栖社区>
  2. 博客>
  3. 正文

CodeSmith系列(三)——使用CodeSmith生成ASP.NET页面

codelove 2011-05-24 17:29:00 浏览392
展开阅读全文

  仍然使用之前的XML文件,然后设置生成参数如下:

image

生成调整后的页面如下:

image

生成的代码如下:

<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="ConfirmationForPayment.ascx.cs"
    Inherits="NBShop.UserControls.Form.ConfirmationForPayment" EnableViewState="true" %>
<%@ Register Assembly="Ext.Net" Namespace="Ext.Net" TagPrefix="ext" %>
<ext:ResourceManager ID="ResourceManager1" runat="server" />
<script type="text/javascript">
    var valCss = '';
    function showMsg(title, content, cs) {
        if (valCss != cs) {
            valCss = cs;
            Ext.net.Notification.show({
                hideFx: {
                    fxName: 'switchOff',
                    args: [{}]
                },
                showFx: {
                    args: [
                              'C3DAF9',
                              1,
                              {
                                  duration: 2.0
                              }
                          ],
                    fxName: 'frame'
                },
                iconCls: cs,
                closeVisible: true,
                html: content,
                title: title + '   ' + new Date().format('g:i:s A')
            });
        }
    }
</script>
<center>
    <div style="width: 830px; text-align: left;">
        <ext:FormPanel ID="FormPanel1" Collapsible="true" Header="false" Icon="PageAdd" runat="server"
            MonitorValid="true" Padding="5" ButtonAlign="Right"
            Width="830px" Layout="Form">
			<Items>
				<ext:FormPanel ID="fpGroup0" Icon="PhoneAdd" Border="true" Collapsible="true" runat="server" Title="表单信息" AutoHeight="true" LabelWidth="120">
	<Items>
	<ext:TableLayout runat="server" ColumnWidth="0.5" Columns="2"><Cells><ext:Cell><ext:TextField ID="txtAreaName" runat="server" /></ext:Cell>
	<ext:Cell><ext:TextField ID="txtBranchCompany" runat="server" /></ext:Cell>
	<ext:Cell><ext:TextField ID="txtProvince" runat="server" /></ext:Cell>
	<ext:Cell><ext:TextField ID="txtCitys" runat="server" /></ext:Cell>
	<ext:Cell><ext:TextField ID="txtShopName" runat="server" /></ext:Cell>
	<ext:Cell><ext:TextField ID="txtName" runat="server" /></ext:Cell>
	<ext:Cell><ext:TextField ID="txtOracleNO" runat="server" /></ext:Cell>
	<ext:Cell><ext:TextField ID="txtMarginNumber" runat="server" /></ext:Cell>
	<ext:Cell><ext:DateField ID="txtPayTime" runat="server" /></ext:Cell>
	<ext:Cell><ext:TextField ID="txtPayer" runat="server" /></ext:Cell>
	<ext:Cell ColSpan="2"><ext:FormPanel Border="false" IsFormField="true" ID="tblPaymentAmount" runat="server" ><Items><ext:DisplayField runat="server" Text="---动态生成--" /></Items></ext:FormPanel></ext:Cell>
	<ext:Cell><ext:ComboBox Editable="false" ID="ddlCollectingCompany" runat="server" /></ext:Cell>
	<ext:Cell><ext:ComboBox Editable="false" ID="ddlDueBank" runat="server" /></ext:Cell>
	<ext:Cell><ext:ComboBox Editable="false" ID="ddlCollectingBankAccount" runat="server" /></ext:Cell>
	<ext:Cell><ext:TextField ID="txtBranchContacts" runat="server" /></ext:Cell>
	<ext:Cell><ext:TextField ID="txtContactPhoneNumber" runat="server" /></ext:Cell>
	<ext:Cell ColSpan="2"><ext:FormPanel Border="false" IsFormField="true" ID="tblFinancialConfirm" runat="server" ><Items><ext:DisplayField runat="server" Text="---动态生成--" /></Items></ext:FormPanel></ext:Cell>
	</Cells>   </ext:TableLayout></Items>
	</ext:FormPanel>
	
                    <ext:Panel ID="pnlExamineList" runat="server" Collapsible="true" Header="true" Icon="UserFemale" Border="true"
                    Title="审批历史" Height="200">
                    <AutoLoad Url="/FormServerTemplates/ExamineList.aspx" NoCache="true" Mode="IFrame"
                        ShowMask="true" />
                    <Listeners>
                        <Expand Handler="this.reload();" />
                        <Collapse Handler="this.clearContent();" />
                    </Listeners>
                </ext:Panel>
			</Items>
			<Buttons>
                <ext:Button ID="btnSave" runat="server" Text="保存" CausesValidation="true" Icon="Disk">
                    <DirectEvents>
                        <Click OnEvent="btnSave_Click" Single="true">
                            <EventMask ShowMask="true" Msg="正在处理..." />
                        </Click>
                    </DirectEvents>
                </ext:Button>
                <ext:Button ID="btnSumbit1" runat="server" Text="提交" CausesValidation="true" Icon="PageAdd">
                    <DirectEvents>
                        <Click OnEvent="btnSubmit_Click" Single="true">
                            <EventMask ShowMask="true" Msg="正在处理..." />
                        </Click>
                    </DirectEvents>
                </ext:Button>
            </Buttons>
            <BottomBar>
                <ext:StatusBar ID="StatusBar1" runat="server" />
            </BottomBar>
            <TopBar>
                <ext:Toolbar ID="Toolbar1" runat="server">
                    <Items>
                        <ext:ToolbarFill ID="ToolbarFill1" runat="server"/>
                        <ext:Button ID="tbSave" runat="server" Icon="Disk" CausesValidation="true" Text="保存">
                            <DirectEvents>
                                <Click OnEvent="btnSave_Click" Single="true">
                                    <EventMask ShowMask="true" Msg="正在处理数据..." />
                                </Click>
                            </DirectEvents>
                        </ext:Button>
                        <ext:Button ID="btnSumbit2" runat="server" Icon="PageAdd" CausesValidation="true" 
                            Text="提交">
                            <DirectEvents>
                                <Click OnEvent="btnSubmit_Click" Single="true">
                                    <EventMask ShowMask="true" Msg="正在处理..." />
                                </Click>
                            </DirectEvents>
                        </ext:Button>
                    </Items>
                </ext:Toolbar>
            </TopBar>
            <Listeners>
                <ClientValidation Handler="#{btnSave}.setDisabled(!valid);#{tbSave}.setDisabled(!valid);#{btnSumbit1}.setDisabled(!valid);#{btnSumbit2}.setDisabled(!valid);var valCs=valid ? 'valaccept' : 'valexclamation';var msg=valid ? '<span style=\'color:green;\'>验证通过,可以提交数据</span>' : '<span style=\'color:red;\'>输入有误,请检查标红的输入项。</span>';this.getBottomToolbar().setStatus({text :msg, iconCls: valCs});showMsg('温馨提示',msg,valCs);" />
            </Listeners>
        </ext:FormPanel>
	</div>
</center>
<script type="text/javascript">
    Ext.onReady(function () {
        $(function(){
            setTimeout("setLabelClass()",300);            
        });
        //当前窗体最大化
        top.Ext.getCmp('frmStatesRequestList').maximize();
    });     
    function setLabelClass() {
        //表单控件设置Label样式
        $("label.x-form-item-label").addClass("labelStyle");
        //设置表格宽度
        $("table.x-table-layout").attr("width", "100%");
    } 
</script>

模板如下:

<%-- 
Name: 根据XML生成用户控件表单
Author: LWQ
--%>
<%@ CodeTemplate Language="C#" TargetLanguage="Html" Debug="True"
CompilerVersion="v3.5" Description="根据XML生成Ext.NET用户控件" ResponseEncoding="UTF-8"%>

<%@ Assembly Name="CodeSmith.CustomProperties" %>
<%@ Property Name="ClassName" Type="System.String" Default="" Optional="True" Category="Optional" Description="用户控件名称。" %>
<%--加载使用访问数据库的组件SchemaExplorer,并声明其使用的命名空间。--%>
<%@ Assembly Name="SchemaExplorer" %>
<%@ Import Namespace="SchemaExplorer" %>
<%@ Property Name="SourceTable" Type="SchemaExplorer.TableSchema" Category="Context"  Description="对应的数据主表" %>
<%@ Import Namespace="System.Text" %>
<%@ Import Namespace="System.Text.RegularExpressions" %>
<%--加载Linq to xml组件,并声明其使用的命名空间。--%>
<%@ Import Namespace="System.Xml.Linq" %>
<%@ Assembly Name="System.Xml.Linq" %>
<%@ Import Namespace="System.IO" %>
<%@ Import Namespace="System.Xml" %>
<%@ Import Namespace="System.Windows.Forms.Design"%>
<%@ Assembly Name="System.Design" %>
<%@ Import Namespace="System.Collections.Generic" %>
<%%@ Control Language="C#" AutoEventWireup="true" CodeBehind="<%=ClassName%>.ascx.cs"
    Inherits="NBShop.UserControls.Form.<%=ClassName%>" EnableViewState="true" %>
<%%@ Register Assembly="Ext.Net" Namespace="Ext.Net" TagPrefix="ext" %>
<ext:ResourceManager ID="ResourceManager1" runat="server" />
<script type="text/javascript">
    var valCss = '';
    function showMsg(title, content, cs) {
        if (valCss != cs) {
            valCss = cs;
            Ext.net.Notification.show({
                hideFx: {
                    fxName: 'switchOff',
                    args: [{}]
                },
                showFx: {
                    args: [
                              'C3DAF9',
                              1,
                              {
                                  duration: 2.0
                              }
                          ],
                    fxName: 'frame'
                },
                iconCls: cs,
                closeVisible: true,
                html: content,
                title: title + '   ' + new Date().format('g:i:s A')
            });
        }
    }
</script>
<center>
    <div style="width: 830px; text-align: left;">
        <ext:FormPanel ID="FormPanel1" Collapsible="true" Header="false" Icon="PageAdd" runat="server"
            MonitorValid="true" Padding="5" ButtonAlign="Right"
            Width="830px" Layout="Form">
			<Items>
				<%=GetFormItem()%>
                    <ext:Panel ID="pnlExamineList" runat="server" Collapsible="true" Header="true" Icon="UserFemale" Border="true"
                    Title="审批历史" Height="200">
                    <AutoLoad Url="/FormServerTemplates/ExamineList.aspx" NoCache="true" Mode="IFrame"
                        ShowMask="true" />
                    <Listeners>
                        <Expand Handler="this.reload();" />
                        <Collapse Handler="this.clearContent();" />
                    </Listeners>
                </ext:Panel>
			</Items>
			<Buttons>
                <ext:Button ID="btnSave" runat="server" Text="保存" CausesValidation="true" Icon="Disk">
                    <DirectEvents>
                        <Click OnEvent="btnSave_Click" Single="true">
                            <EventMask ShowMask="true" Msg="正在处理..." />
                        </Click>
                    </DirectEvents>
                </ext:Button>
                <ext:Button ID="btnSumbit1" runat="server" Text="提交" CausesValidation="true" Icon="PageAdd">
                    <DirectEvents>
                        <Click OnEvent="btnSubmit_Click" Single="true">
                            <EventMask ShowMask="true" Msg="正在处理..." />
                        </Click>
                    </DirectEvents>
                </ext:Button>
            </Buttons>
            <BottomBar>
                <ext:StatusBar ID="StatusBar1" runat="server" />
            </BottomBar>
            <TopBar>
                <ext:Toolbar ID="Toolbar1" runat="server">
                    <Items>
                        <ext:ToolbarFill ID="ToolbarFill1" runat="server"/>
                        <ext:Button ID="tbSave" runat="server" Icon="Disk" CausesValidation="true" Text="保存">
                            <DirectEvents>
                                <Click OnEvent="btnSave_Click" Single="true">
                                    <EventMask ShowMask="true" Msg="正在处理数据..." />
                                </Click>
                            </DirectEvents>
                        </ext:Button>
                        <ext:Button ID="btnSumbit2" runat="server" Icon="PageAdd" CausesValidation="true" 
                            Text="提交">
                            <DirectEvents>
                                <Click OnEvent="btnSubmit_Click" Single="true">
                                    <EventMask ShowMask="true" Msg="正在处理..." />
                                </Click>
                            </DirectEvents>
                        </ext:Button>
                    </Items>
                </ext:Toolbar>
            </TopBar>
            <Listeners>
                <ClientValidation Handler="#{btnSave}.setDisabled(!valid);#{tbSave}.setDisabled(!valid);#{btnSumbit1}.setDisabled(!valid);#{btnSumbit2}.setDisabled(!valid);var valCs=valid ? 'valaccept' : 'valexclamation';var msg=valid ? '<span style=\'color:green;\'>验证通过,可以提交数据</span>' : '<span style=\'color:red;\'>输入有误,请检查标红的输入项。</span>';this.getBottomToolbar().setStatus({text :msg, iconCls: valCs});showMsg('温馨提示',msg,valCs);" />
            </Listeners>
        </ext:FormPanel>
	</div>
</center>
<script type="text/javascript">
    Ext.onReady(function () {
        $(function(){
            setTimeout("setLabelClass()",300);            
        });
        //当前窗体最大化
        top.Ext.getCmp('frmStatesRequestList').maximize();
    });     
    function setLabelClass() {
        //表单控件设置Label样式
        $("label.x-form-item-label").addClass("labelStyle");
        //设置表格宽度
        $("table.x-table-layout").attr("width", "100%");
    } 
</script>
<script runat="template">
     ///配置文件路径
     private string _userFileName = string.Empty;
     [Editor(typeof(FileNameEditor), typeof(System.Drawing.Design.UITypeEditor)),Category("Custom"), Description("请选择配置XML文件。")]
     public string UserFileName
     {
          get {return _userFileName;}
          set {_userFileName= value;}
     }
     //返回生成的项的HTML
      public string GetFormItem()
     {
          Debugger.Break();
          if (File.Exists(_userFileName))
          {
               StringBuilder _sbText = new StringBuilder();
               XElement elements = XElement.Load(_userFileName);
               var _group = elements.Descendants("Group");
               if (_group == null || _group.Count() == 0)
               {
                   var _fields = elements.Descendants("Field");
                   CreateFields(_sbText, _fields);
               }
               else
               {
                    int _groupIndex=0;
                   foreach (var item in _group)
                   {
                       var _GroupID = item.Attribute("GroupID") == null ? "fpGroup"+_groupIndex : item.Attribute("GroupID").Value;
                       var _title = item.Attribute("Title") == null ? string.Empty : item.Attribute("Title").Value;
                       var _Columns = item.Attribute("Columns") == null ? string.Empty : item.Attribute("Columns").Value;
                       _sbText.Append("<ext:FormPanel ID=\"").Append(_GroupID).Append("\" Icon=\"PhoneAdd\" Border=\"true\" Collapsible=\"true\" runat=\"server\" Title=\"").Append(_title).Append("\" AutoHeight=\"true\" LabelWidth=\"120\">\r\n\t<Items>\r\n\t");
                       _sbText.Append("<ext:TableLayout runat=\"server\" ColumnWidth=\"");
                       switch (_Columns)
                       {
                           case "2":
                               _sbText.Append("0.5");
                               break;
                           case "3":
                               _sbText.Append("0.33");
                               break;
                           case "4":
                               _sbText.Append("0.25");
                               break;
                           case "1":
                               _sbText.Append("1");
                               break;
                           default:
                               break;
                       }
                       _sbText.Append("\" Columns=\"").Append(_Columns).Append("\"><Cells>");
                       var _fields = item.Descendants("Field");
                       CreateFields(_sbText, _fields);
                       _sbText.Append("</Cells>   </ext:TableLayout>");
                       _sbText.Append("</Items>\r\n\t</ext:FormPanel>\r\n\t");
                      _groupIndex++;
                   }
               }
               return _sbText.ToString();
            }
          return string.Empty;
     }
      private void CreateFields(StringBuilder _sbText, IEnumerable<XElement> _fields)
    {
        foreach (var item in _fields)
        {
          
            //文本控件ID
            string _textControlID = item.Attributes("TextControlID").First().Value;
            string _attr = _textControlID.Substring(0, 3);
            string _fieldName=_textControlID.Substring(3);

            if (_attr == "tbl")
                _sbText.Append("<ext:Cell ColSpan=\"2\">");
            else
                _sbText.Append("<ext:Cell>");

            //判断是否为数字
            if (item.Attributes("MaximumValue").FirstOrDefault() != null || item.Attributes("MinimumValue").FirstOrDefault() != null)
            {
                _sbText.Append("<ext:NumberField ID=\"").Append(_textControlID).Append("\" runat=\"server\" />");
            }
            else
            {
                switch (_attr)
                {
                    case "txt":
                        if ( _textControlID.ToLower().Contains("date") 
                              || _textControlID.ToLower().Contains("time") 
                              || _textControlID.ToLower().Contains("DeadLine")
                              || _textControlID.ToLower().Contains("birthday")
                              )
                            _sbText.Append("<ext:DateField ID=\"").Append(_textControlID).Append("\" runat=\"server\" />");
                        else
                            _sbText.Append("<ext:TextField ID=\"").Append(_textControlID).Append("\" runat=\"server\" />");
                        break;
                    case "ddl":
                        _sbText.Append("<ext:ComboBox Editable=\"false\" ID=\"").Append(_textControlID).Append("\" runat=\"server\" />");
                        break;
                    case "cbl":
                        _sbText.Append("<ext:CheckboxGroup ID=\"").Append(_textControlID).Append("\" runat=\"server\" ><Items><ext:Checkbox runat=\"server\" BoxLabel=\"测试\" /> </Items></ext:CheckboxGroup>");
                        break;
                    case "rbl":
                        _sbText.Append("<ext:RadioGroup ID=\"").Append(_textControlID).Append("\" runat=\"server\" ><Items><ext:Radio runat=\"server\" BoxLabel=\"测试\" /> </Items></ext:RadioGroup>");
                        break;
                    case "tbl":
                        _sbText.Append("<ext:FormPanel Border=\"false\" IsFormField=\"true\" ID=\"").Append(_textControlID).Append("\" runat=\"server\" ><Items><ext:DisplayField runat=\"server\" Text=\"---动态生成--\" /></Items></ext:FormPanel>");
                        break;
                    case "chk":
                        _sbText.Append("<ext:Checkbox ID=\"").Append(_textControlID).Append("\" runat=\"server\" />");
                        break;
                     case "rdo":
                        _sbText.Append("<ext:Radio ID=\"").Append(_textControlID).Append("\" runat=\"server\" />");
                        break;
                    default:
                        Response.WriteLine("警告:代码生成错误。未知的控件前缀:"+_attr);
                        return;
                }
            }
            _sbText.Append("</ext:Cell>\r\n\t");
        }
    }
</script>

网友评论

登录后评论
0/500
评论
codelove
+ 关注