CodeSmith系列(二)——使用CodeSmith生成ASP.NET后台代码
因为表单的后台代码都差不多,所以采用了CodeSmith生成。由于表单的控制是基于XML的,所以可以根据XML自定义生成。由于没时间,就不多写了,具体模板代码见最后。
在这里,先选择变量。如下:
XMl文件内容如下:
<?xml version="1.0" encoding="utf-8" ?> <FieldConfig> <GlobalDefaultConfig> <Description>付款确认单</Description> <Width>360</Width> </GlobalDefaultConfig> <Fields> <Group Title="表单信息" Columns="2"> <Field TextControlID="txtAreaName" Disabled="true">所属大区</Field> <Field TextControlID="txtBranchCompany" Disabled="true">所属分公司</Field> <Field TextControlID="txtProvince" Disabled="true">所属省份</Field> <Field TextControlID="txtCitys" Disabled="true">所属城市</Field> <Field TextControlID="txtShopName" Disabled="true" MaxLength="20">门店名称</Field> <Field TextControlID="txtName" Disabled="true">主持老师</Field> <Field TextControlID="txtOracleNO" Disabled="true">Oralce号</Field> <Field TextControlID="txtMarginNumber" Disabled="true">保证金号码号</Field> <Field TextControlID="txtPayTime" AllowBlank="false">付款时间</Field> <Field TextControlID="txtPayer" AllowBlank="false">付款人</Field> <Field TextControlID="tblPaymentAmount" AllowBlank="false">付款金额(元)</Field> <Field TextControlID="ddlCollectingCompany" AllowBlank="false">收款公司名称</Field> <Field TextControlID="ddlDueBank" AllowBlank="false">收款银行名称</Field> <Field TextControlID="ddlCollectingBankAccount" AllowBlank="false">收款银行帐号</Field> <Field TextControlID="txtBranchContacts">分公司联系人</Field> <Field TextControlID="txtContactPhoneNumber">联系电话</Field> <Field TextControlID="tblFinancialConfirm" Disabled="true">财务确认</Field> <!--<Field TextControlID="cblFinancialConfirm">财务确认</Field>--> </Group> </Fields> <Controls> <Control> <QueryStrings> <!--培训阶段--> <Query Name="DriverPhasesid">1E355FC6D4A744F4AF11BB0811E2A066</Query> </QueryStrings> <Disabled FieldsName="AttributeValue"> <ControlField>加盟套餐费(元)</ControlField> <ControlField>改型套餐费(元)</ControlField> <ControlField>保证金(元)</ControlField> <ControlField>虹膜套餐款(元)</ControlField> <ControlField>虹膜续约款(元)</ControlField> </Disabled> <!--<ControlField Disabled="true">Cost1</ControlField> <ControlField Disabled="true">Cost2</ControlField> <ControlField Disabled="true">Cost3</ControlField> <ControlField Disabled="true">Cost4</ControlField> <ControlField Disabled="true">Cost5</ControlField> <ControlField Disabled="true">ddfBank1</ControlField> <ControlField Disabled="true">ddfBank2</ControlField> <ControlField Disabled="true">ddfBank3</ControlField> <ControlField Disabled="true">ddfBank4</ControlField> <ControlField Disabled="true">ddfBank5</ControlField>--> </Control> <Control> <QueryStrings> <!--签约阶段--> <Query Name="DriverPhasesid">72512CBA542E43029B91F9FB3155D4DD</Query> </QueryStrings> <!--<ControlField Disabled="true">Cost0</ControlField> <ControlField Disabled="true">Cost2</ControlField> <ControlField Disabled="true">Cost4</ControlField> <ControlField Disabled="true">Cost5</ControlField>--> <Disabled FieldsName="AttributeValue"> <ControlField>培训费(元)</ControlField> <!--<ControlField>加盟套餐费</ControlField>--> <ControlField>改型套餐费(元)</ControlField> <!--<ControlField>保证金</ControlField>--> <ControlField>虹膜套餐款(元)</ControlField> <ControlField>虹膜续约款(元)</ControlField> </Disabled> </Control> <Control> <QueryStrings> <!--续约--> <Query Name="DriverPhasesid">BDA31689C7B54F4EAE925A5390F56C99</Query> </QueryStrings> <!--<ControlField Disabled="true">Cost0</ControlField> <ControlField Disabled="true">Cost1</ControlField> <ControlField Disabled="true">Cost2</ControlField> <ControlField Disabled="true">Cost4</ControlField> <ControlField Disabled="true">Cost5</ControlField>--> <Disabled FieldsName="AttributeValue"> <ControlField>培训费(元)</ControlField> <ControlField>加盟套餐费(元)</ControlField> <ControlField>改型套餐费(元)</ControlField> <!--<ControlField>保证金</ControlField>--> <ControlField>虹膜套餐款(元)</ControlField> <ControlField>虹膜续约款(元)</ControlField> </Disabled> </Control> <Control> <QueryStrings> <!--改型--> <Query Name="DriverPhasesid">DEB4897EBD28440AB0C60F5D27ED677E</Query> </QueryStrings> <!--<ControlField Disabled="true">Cost0</ControlField> <ControlField Disabled="true">Cost1</ControlField> <ControlField Disabled="true">Cost4</ControlField> <ControlField Disabled="true">Cost5</ControlField>--> <Disabled FieldsName="AttributeValue"> <ControlField>培训费(元)</ControlField> <ControlField>加盟套餐费(元)</ControlField> <!--<ControlField>改型套餐费</ControlField>--> <!--<ControlField>保证金</ControlField>--> <ControlField>虹膜套餐款(元)</ControlField> <ControlField>虹膜续约款(元)</ControlField> </Disabled> </Control> <Control> <QueryStrings> <!--转约--> <Query Name="DriverPhasesid">464BEE8157B943B1AC9C3930FD6D774C</Query> </QueryStrings> <!--<ControlField Disabled="true">Cost0</ControlField> <ControlField Disabled="true">Cost1</ControlField> <ControlField Disabled="true">Cost2</ControlField> <ControlField Disabled="true">Cost5</ControlField>--> <Disabled FieldsName="AttributeValue"> <ControlField>培训费(元)</ControlField> <ControlField>加盟套餐费(元)</ControlField> <ControlField>改型套餐费(元)</ControlField> <!--<ControlField>保证金</ControlField>--> <!--<ControlField>虹膜套餐款</ControlField>--> <ControlField>虹膜续约款(元)</ControlField> </Disabled> </Control> <Control> <QueryStrings> <!--虹膜续约--> <Query Name="DriverPhasesid">6E022231D0AC41EFAD8E685D0B5FB768</Query> <Query Name="DriverPhasesid">60846B34E4F8482297192A2A0AE5D068</Query> <Query Name="DriverPhasesid">CFCFB79EA19F4B529819641E02EE8EE5</Query> </QueryStrings> <!--<ControlField Disabled="true">Cost0</ControlField> <ControlField Disabled="true">Cost1</ControlField> <ControlField Disabled="true">Cost2</ControlField> <ControlField Disabled="true">Cost3</ControlField> <ControlField Disabled="true">Cost4</ControlField>--> <Disabled FieldsName="AttributeValue"> <ControlField>培训费(元)</ControlField> <ControlField>加盟套餐费(元)</ControlField> <ControlField>改型套餐费(元)</ControlField> <ControlField>保证金(元)</ControlField> <ControlField>虹膜套餐款(元)</ControlField> <!--<ControlField>虹膜续约款</ControlField>--> </Disabled> </Control> </Controls> </FieldConfig>
生成的代码如下:
using System; using System.Collections; using System.Configuration; using System.Data; using System.Linq; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.HtmlControls; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Xml.Linq; using Ext.Net; using NBShopService; using NBShopCommon; //辅助类库 using NBShopCommon.Ext; //Ext函数库以及扩展方法 using System.Collections.Generic; namespace NBShop.UserControls.Form { /// <summary> /// 付款确认单 /// </summary> public partial class ConfirmationForPayment : System.Web.UI.UserControl { #region 公共属性 /// <summary> /// 店铺ID /// </summary> public string ShopID { get { return Request.QueryString["ObjectID"]??Request.QueryString["ShopID"]; } } /// <summary> /// 表单类型 /// </summary> public string FormType { get { return Request.QueryString["FormType"]; } } /// <summary> /// 当前表单ID /// </summary> public string CurrentFormID { get { return (ViewState["CurrentFormID"] ?? string.Empty).ToString(); } set { ViewState["CurrentFormID"] = value; } } #endregion protected void Page_Load(object sender, EventArgs e) { //在SharePoint中赋予权限加载Ext资源文件 ResourceManager1.BuildAllPrivilegesForExtNET(); //注册jquery脚本文件 this.Page.ClientScript.RegisterClientScriptInclude("JQuery4.4", "/js/jquery-1.4.4.min.js"); try { //绑定数据,设置界面逻辑 Loading(); } catch (Exception ex) { //记录错误日志 LogManager.WriteErrorLog(ex); } } /// <summary> /// 绑定数据,设置界面逻辑 /// </summary> private void Loading() { using (NBShopDataContext _db = new NBShopDataContext()) { #region 设置参数 if (!IsPostBack) { //设置审批列表的加载路径和参数 pnlExamineList.AutoLoad.Url = "/FormServerTemplates/ExamineList.aspx?PTCode=" + Request.QueryString["PTCode"] + "&TaskId=" + Request.QueryString["TaskId"]; ///加载配置(使用的是扩展方法,用于配置Ext控件) this.LoadConfigs("ConfirmationForPayment", Context); //TODO:设置参数 #region 绑定下拉列表 #region 绑定收款公司名称 //TODO:请绑定下拉列表收款公司名称 //ExtControlHelper.BindComobox(this, _db.SelectGeneralFromTableINFO(ShopID, CurrentFormID, //"CollectingCompany").ToList() //, "ddlCollectingCompany", "AttributeValue", "AttributeID", "所选值"); #endregion #region 绑定收款银行名称 //TODO:请绑定下拉列表收款银行名称 //ExtControlHelper.BindComobox(this, _db.SelectGeneralFromTableINFO(ShopID, CurrentFormID, //"DueBank").ToList() //, "ddlDueBank", "AttributeValue", "AttributeID", "所选值"); #endregion #region 绑定收款银行帐号 //TODO:请绑定下拉列表收款银行帐号 //ExtControlHelper.BindComobox(this, _db.SelectGeneralFromTableINFO(ShopID, CurrentFormID, //"CollectingBankAccount").ToList() //, "ddlCollectingBankAccount", "AttributeValue", "AttributeID", "所选值"); #endregion #endregion var _context = _db.SelectConfirmationForPaymentINFO(ShopID).FirstOrDefault(); if (_context!=null) { //设置控件的值 this.SetControlValues(_context); if (!string.IsNullOrEmpty(_context.ConfirmationForPaymentID)) { CurrentFormID = _context.ConfirmationForPaymentID; } else { CurrentFormID = _db.GetNewGuid(); } } } #endregion } GC.Collect(); } //保存 protected void btnSave_Click(object sender, DirectEventArgs e) { try { //显示保存进度条 X.Msg.Show(new MessageBoxConfig { Message = "正在保存数据, 请稍后...", ProgressText = "正在保存数据...", Width = 300, Wait = true, WaitConfig = new WaitConfig { Interval = 200 }, IconCls = "ext-mb-download", AnimEl = this.btnSave.ClientID }); if (Save()) { //执行流程驱动 ResourceManager1.SetSubmitScript(ShopID, false); } } catch (Exception ex) { NBShopCommon.LogManager.WriteErrorLog(ex); ResourceManager1.AddScript(" setTimeout(function () { Ext.MessageBox.hide(); Ext.Msg.notify('完成', '保存失败!'); }, 1000);"); } } //保存数据 private bool Save() { //实例化LINQ To SQl类上下文对象 NBShopDataContext _db = new NBShopDataContext(); try { if (_db.Connection.State == ConnectionState.Closed) _db.Connection.Open(); //事务开始 _db.Transaction = _db.Connection.BeginTransaction(System.Data.IsolationLevel.Serializable); //TODO:保存数据 //提交事务 _db.Transaction.Commit(); //ObjectService _os = new ObjectService(); //bool _bobjprc = _os.SaveObjectProcessInfo(Request.QueryString["ObjectID"] ?? string.Empty, Request.QueryString["PTCode"] ?? string.Empty); //bool _bobjnp = _os.SaveObjectPN(Request.QueryString["ObjectID"] ?? string.Empty, Request.QueryString["PhasesId"] ?? string.Empty); return true; } catch (Exception ex) { //回滚事务 _db.Transaction.Rollback(); LogManager.WriteErrorLog(ex); ResourceManager1.AddScript(" setTimeout(function () { Ext.MessageBox.hide(); Ext.Msg.notify('完成', '保存数据失败!');}, 3000);"); return false; } } //提交 protected void btnSubmit_Click(object sender, DirectEventArgs e) { try { //显示提交进度条 X.Msg.Show(new MessageBoxConfig { Message = "正在提交数据, 请稍后...", ProgressText = "正在提交数据...", Width = 300, Wait = true, WaitConfig = new WaitConfig { Interval = 200 }, IconCls = "ext-mb-download", AnimEl = this.btnSumbit2.ClientID }); if (Save()) { //流程操作并执行脚本 ResourceManager1.SetSubmitScript(ShopID, true); } } catch (Exception ex) { LogManager.WriteErrorLog(ex); ResourceManager1.AddScript(" setTimeout(function () { Ext.MessageBox.hide();Ext.Msg.notify('完成', '提交失败!'); }, 2000);"); } } } }
模板代码如下:
<%-- Name: 根据XML生成用户控件表单 Author: LWQ --%> <%@ CodeTemplate Language="C#" TargetLanguage="C#" ResponseEncoding="UTF-8" Description="生成Ext.NET用户控件处理代码" CompilerVersion="v3.5" %> <%@ 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" %> <%@ Import Namespace="System.Windows.Forms.Design"%> <%@ Assembly Name="System.Design" %> <%@ Import Namespace="System.Xml.Linq" %> <%@ Assembly Name="System.Xml.Linq" %> <%@ Import Namespace="System.Xml" %> <%@ Import Namespace="System.IO" %> <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;} } XElement elements =null; //返回XML的Key。 public string GetFormKey() { return ClassName; } </script> <% if(File.Exists(_userFileName)) { elements = XElement.Load(_userFileName); } %> using System; using System.Collections; using System.Configuration; using System.Data; using System.Linq; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.HtmlControls; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Xml.Linq; using Ext.Net; using NBShopService; using NBShopCommon; //辅助类库 using NBShopCommon.Ext; //Ext函数库以及扩展方法 using System.Collections.Generic; namespace NBShop.UserControls.Form { <% if(elements.Element("GlobalDefaultConfig").Element("Description")!=null) {%> /// <summary> /// <%=elements.Element("GlobalDefaultConfig").Element("Description").Value %> /// </summary> <% } %> public partial class <%=ClassName%> : System.Web.UI.UserControl { #region 公共属性 /// <summary> /// 店铺ID /// </summary> public string ShopID { get { return Request.QueryString["ObjectID"]??Request.QueryString["ShopID"]; } } /// <summary> /// 表单类型 /// </summary> public string FormType { get { return Request.QueryString["FormType"]; } } /// <summary> /// 当前表单ID /// </summary> public string CurrentFormID { get { return (ViewState["CurrentFormID"] ?? string.Empty).ToString(); } set { ViewState["CurrentFormID"] = value; } } #endregion protected void Page_Load(object sender, EventArgs e) { //在SharePoint中赋予权限加载Ext资源文件 ResourceManager1.BuildAllPrivilegesForExtNET(); //注册jquery脚本文件 this.Page.ClientScript.RegisterClientScriptInclude("JQuery4.4", "/js/jquery-1.4.4.min.js"); try { //绑定数据,设置界面逻辑 Loading(); } catch (Exception ex) { //记录错误日志 LogManager.WriteErrorLog(ex); } } /// <summary> /// 绑定数据,设置界面逻辑 /// </summary> private void Loading() { using (NBShopDataContext _db = new NBShopDataContext()) { #region 设置参数 if (!IsPostBack) { //设置审批列表的加载路径和参数 pnlExamineList.AutoLoad.Url = "/FormServerTemplates/ExamineList.aspx?PTCode=" + Request.QueryString["PTCode"] + "&TaskId=" + Request.QueryString["TaskId"]; ///加载配置(使用的是扩展方法,用于配置Ext控件) this.LoadConfigs("<%=ClassName%>", Context); //TODO:设置参数 <% if(elements.Descendants("Field").Where(p=>p.Attribute("TextControlID").Value.Substring(0,3)=="ddl").Count()>0){ %> #region 绑定下拉列表 <% var ddls = elements.Descendants("Field").Where(p => p.Attribute("TextControlID").Value.Substring(0, 3) == "ddl"); foreach (var item in ddls){ %> #region 绑定<%=item.Value%> //TODO:请绑定下拉列表<%=item.Value%> //ExtControlHelper.BindComobox(this, _db.SelectGeneralFromTableINFO(ShopID, CurrentFormID, //"<%=item.Attribute("AttributeTypeCode")==null?item.Attribute("TextControlID").Value.Substring(3):item.Attribute("AttributeTypeCode").Value %>").ToList() //, "<%=item.Attribute("TextControlID").Value %>", "AttributeValue", "AttributeID", "所选值"); #endregion <% }%> #endregion <%} %> var _context = _db.Select<%=ClassName%>INFO(ShopID).FirstOrDefault(); if (_context!=null) { //设置控件的值 this.SetControlValues(_context); if (!string.IsNullOrEmpty(_context.<%=ClassName%>ID)) { CurrentFormID = _context.<%=ClassName%>ID; } else { CurrentFormID = _db.GetNewGuid(); } } } #endregion <% if(elements.Descendants("Field").Where(p=>p.Attribute("TextControlID").Value.Substring(0,3)=="cbl").Count()>0){ %> #region 绑定复选框组 <% var cbos = elements.Descendants("Field").Where(p => p.Attribute("TextControlID").Value.Substring(0, 3) == "cbl"); foreach (var item in cbos){ %> #region 绑定<%=item.Value%> //TODO:请绑定复选框组<%=item.Value%> //ExtControlHelper.BindCheckGroup(this, _db.SelectGeneralFromTableINFO(ShopID, CurrentFormID, //"<%=item.Attribute("AttributeTypeCode")==null?item.Attribute("TextControlID").Value.Substring(3):item.Attribute("AttributeTypeCode").Value %>").ToList() //, "<%=item.Attribute("TextControlID").Value %>", "AttributeValue", "AttributeID", "CheckValue",4); #endregion <% }%> #endregion <%} %> <% if(elements.Descendants("Field").Where(p=>p.Attribute("TextControlID").Value.Substring(0,3)=="rbl").Count()>0){ %> #region 绑定单选框组 <% var rdos = elements.Descendants("Field").Where(p => p.Attribute("TextControlID").Value.Substring(0, 3) == "rbl"); foreach (var item in rdos){ %> #region 绑定<%=item.Value%> //TODO:请绑定单选框组<%=item.Value%> //ExtControlHelper.BindRadioGroup(this, _db.SelectGeneralFromTableINFO(ShopID, CurrentFormID, //"<%=item.Attribute("AttributeTypeCode")==null?item.Attribute("TextControlID").Value.Substring(3):item.Attribute("AttributeTypeCode").Value %>").ToList() //, "<%=item.Attribute("TextControlID").Value %>", "AttributeValue", "AttributeID", "CheckValue",true,4); #endregion <% }%> #endregion <%} %> } GC.Collect(); } //保存 protected void btnSave_Click(object sender, DirectEventArgs e) { try { //显示保存进度条 X.Msg.Show(new MessageBoxConfig { Message = "正在保存数据, 请稍后...", ProgressText = "正在保存数据...", Width = 300, Wait = true, WaitConfig = new WaitConfig { Interval = 200 }, IconCls = "ext-mb-download", AnimEl = this.btnSave.ClientID }); if (Save()) { //执行流程驱动 ResourceManager1.SetSubmitScript(ShopID, false); } } catch (Exception ex) { NBShopCommon.LogManager.WriteErrorLog(ex); ResourceManager1.AddScript(" setTimeout(function () { Ext.MessageBox.hide(); Ext.Msg.notify('完成', '保存失败!'); }, 1000);"); } } //保存数据 private bool Save() { //实例化LINQ To SQl类上下文对象 NBShopDataContext _db = new NBShopDataContext(); try { if (_db.Connection.State == ConnectionState.Closed) _db.Connection.Open(); //事务开始 _db.Transaction = _db.Connection.BeginTransaction(System.Data.IsolationLevel.Serializable); //TODO:保存数据 //提交事务 _db.Transaction.Commit(); //ObjectService _os = new ObjectService(); //bool _bobjprc = _os.SaveObjectProcessInfo(Request.QueryString["ObjectID"] ?? string.Empty, Request.QueryString["PTCode"] ?? string.Empty); //bool _bobjnp = _os.SaveObjectPN(Request.QueryString["ObjectID"] ?? string.Empty, Request.QueryString["PhasesId"] ?? string.Empty); return true; } catch (Exception ex) { //回滚事务 _db.Transaction.Rollback(); LogManager.WriteErrorLog(ex); ResourceManager1.AddScript(" setTimeout(function () { Ext.MessageBox.hide(); Ext.Msg.notify('完成', '保存数据失败!');}, 3000);"); return false; } } //提交 protected void btnSubmit_Click(object sender, DirectEventArgs e) { try { //显示提交进度条 X.Msg.Show(new MessageBoxConfig { Message = "正在提交数据, 请稍后...", ProgressText = "正在提交数据...", Width = 300, Wait = true, WaitConfig = new WaitConfig { Interval = 200 }, IconCls = "ext-mb-download", AnimEl = this.btnSumbit2.ClientID }); if (Save()) { //流程操作并执行脚本 ResourceManager1.SetSubmitScript(ShopID, true); } } catch (Exception ex) { LogManager.WriteErrorLog(ex); ResourceManager1.AddScript(" setTimeout(function () { Ext.MessageBox.hide();Ext.Msg.notify('完成', '提交失败!'); }, 2000);"); } } } }
作者:雪雁
出处:http://www.cnblogs.com/codelove/
沟通渠道:编程交流群<85318032> 产品交流群<897857351>
如果喜欢作者的文章,请关注【麦扣聊技术】订阅号以便第一时间获得最新内容。本文版权归作者和湖南心莱信息科技有限公司共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
静听鸟语花香,漫赏云卷云舒。
出处:http://www.cnblogs.com/codelove/
沟通渠道:编程交流群<85318032> 产品交流群<897857351>
如果喜欢作者的文章,请关注【麦扣聊技术】订阅号以便第一时间获得最新内容。本文版权归作者和湖南心莱信息科技有限公司共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
静听鸟语花香,漫赏云卷云舒。