Code Smith应用
Code Smith应用
在我们的project中,对于一个web service要进行3个地方的处理
1.asmx file,比如GCRecommendWebSiteManagementService.asmx.vb, 提供web methods
<System.Web.Services.WebService(Namespace:=”http://tempuri.org/“)> _
Public Class GCRecommendWebSiteManagementService
Inherits BaseService
…
<WebMethod(), System.Web.Services.Protocols.SoapHeader(”TokenValue”)> _
Public Function GetAllRecommendWebSite() As DataSet
end Function
end Class
2.内部逻辑class, 比如GCRecommendWebSiteManagementControl.vb
Public Class GCRecommendWebSiteManagementControl
Inherits BaseControl
Public Function GetAllRecommendWebSite() As DataSet
…
End Function
end class
3.在Client 端提供proxy 比如GCRecommendWebSiteManagementServiceProxy.vb
<System.Diagnostics.DebuggerStepThroughAttribute(), _
System.ComponentModel.DesignerCategoryAttribute(”code”), _
System.Web.Services.WebServiceBindingAttribute(Name:=”GCRecommendWebSiteManagementServiceSoap”, [Namespace]:=”http://tempuri.org/“)> _
Public Class GCRecommendWebSiteManagementServiceProxy
Inherits BaseProxy
<System.Web.Services.Protocols.SoapHeaderAttribute(”TokenValue”), _
System.Web.Services.Protocols.SoapDocumentMethodAttribute(”http://tempuri.org/GetAllRecommendWebSite“, RequestNamespace:=”http://tempuri.org/“, ResponseNamespace:=”http://tempuri.org/“, Use:=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle:=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)> _
Public Function GetAllRecommendWebSite() As System.Data.DataSet
Dim results() As Object = Me.Invoke(”GetAllRecommendWebSite”, New Object(-1) {})
Return CType(results(0), System.Data.DataSet)
End Function
Public Function BeginGetAllRecommendWebSite(ByVal callback As System.AsyncCallback, ByVal asyncState As Object) As System.IAsyncResult
Return Me.BeginInvoke(”GetAllRecommendWebSite”, New Object(-1) {}, callback, asyncState)
End Function
Public Function EndGetAllRecommendWebSite(ByVal asyncResult As System.IAsyncResult) As System.Data.DataSet
Dim results() As Object = Me.EndInvoke(asyncResult)
Return CType(results(0), System.Data.DataSet)
End Function
end Class
三部分代码大同小异,目前的做法是copy-post-modify,不好.
我想可以通过下面的方法来自动生成代码:
1. 在GCRecommendWebSiteManagementControl.vb中定义出一个web service所有方法的原型.
2. 在CodeSmith 模板文件执行时利用CodeDomProvider.CompileAssemblyFromSource动态build这个文件,
生成一个assembly,再遍历这个assemlby中的type,type中的method, 利用code dom 就可以生成对应的代码.
注意由于vb会在build一个assembly时加入诸如My.MyApplication,My.MyComputer的class,同时一个
class也会从object继承一些method,所以又需要定义一个attribut来标识需要生成代码的type和
method.
收获
1.使用了自定义的assembly(包含标识type和method的attribute)
2.使用子模板,根据不同的语言生成代码.
3.使用code behind文件,把大量的逻辑放在.cs文件中
4.复习了codedom,
VBCodeProvider.CreateGenerator 已被废弃,现在的用法是:
CodeDomProvider codeProvider = CodeDomProvider.CreateProvider(”VisualBasic”);
codeProvider.GenerateCodeFromMember(cmm, sw, new CodeGeneratorOptions());
5.CodeDom动态编译
