代码改变世界

codesmith

2009-05-08 15:25  宝宝合凤凰  阅读(584)  评论(0)    收藏  举报

来自CodeSmith的震撼

前面我有一篇随笔重复,为什么我们要不断重复讲述的是我在项目开发中的苦恼,引发了很多人讨论,大家各出高招,有人提到ORM,按我的愚见,ORM是在应用程序的类和数据库中表及视图建立一对一关系,例如,数据库中有表tblarticle,那么与之对应,我们可以建立一个articleItem对象来表示单条的记录,表的每个字段做为articleItem的成员变量,对应表的insert,update,delete以及select item及select all等存储过程,我们可以为articleitem建立对应的方法,然后在方法中用ADO.NET及对应的存储过程来完成数据的抽取,修改等.并且,我们可以在articleitem的基础上建立articleitemcollection以表示多条记录,这样,就将单条记录的更新变成了建立一个articleitem对象,给article对象的各种属性赋值,最后调用像articleitem,update()这样的方法来完成数据操纵的目的.这种实现方式其实很容易令人接受,并且,如果A负责写数据存取层的话,B用的时候,几乎不用关心是在操纵哪个表,而只关心操纵的是何种对象.非常类似我们使用.NET类库中对象一样.

可是,听起来不错,但如果真的要你去用ORM做一个项目的时候,你会发现代码量远远大于使用"传统"的直接用ADO.NET调用存储过程的方法.虽然使用ORM可以让我们项目在以后的维护中更加容易,可是,在项目的初期,真的会拖慢开发速度,所以,很多博客堂的朋友觉得,与其ORM,不如就用ADO.NET来

可是,ADO.NET直接操作首先带来的问题是,你的项目只能模向分隔(比如,你可以把为一个数据库中某几个表写数据存取层的任务交给A,另外的交给B),无法进行纵向层次的分割,如果用ORM,你可以让A负责写数据存取层,让B写对象层,让C写业务逻辑层,协作上容易的多.

既然传统方法和ORM都不是那么完美.那有没有更好的方法呢?虽然我也听说过"银弹"故事.我也相信世界上没有银弹.但是我仍然孜孜不倦的追求完美,仍然想找到合适的解决方案.

CodeSmith这个软件在博客堂和CSDN不知道有多少人提过了.大多数的解释是CODeSmith是一个快速代码生成工具.试用后,CodeSmith给我了强烈的震撼,假如它只是一个基于模板的代码生成工具.那么我不认为有什么了不起.可是它竟然克服了模板生成工具的灵活性不足缺陷.它在高效率和高定制性间取得了完美的平衡.如果你没有用过他,我可以告诉你他有以下特点:

1.他可以用于生成C#,VB.NET,TSQL以及其他任何语言代码
2.他本身是可以编程的(这是他的灵活性之源)
3.他提供了强大的SchemaExplorer对象,使数据库储过程的生成非常容易
4.有了他,你不会再向我一样埋怨从一个项目到另一个项目时,需要重新写许多代码.因为你只需要一套模板而已
5.他使用的语法是典型的ASP.NET语法,并且,可以像我们写ASP那样将代码和静态内容混和撰写(好像在写ASP的时代一样)

举一个简单的例子,你就可以明白他的强大
下面是我根据Quick Start Guide写的一个模板,作用是生成一个简单的类框架,不要小看他呀

<%@ CodeTemplate Language="C#" TargetLanguage="C#"  Debug="False" Description="Simple CodeSmith Project" %>
<%@ Property Name="Developer" Type="System.String" Category="Context" Description="开发者名称" %>
<%@ Property Name="NameSpace" Type="System.String" Category="Context" Description="名字空间" %>
<%@ Property Name="ClassName" Type="System.String" Category="Context" Description="类名" %>
///////////////////////////////////////////////////////////////////////////////////////
//文件名:<%=ClassName%>.cs
//说明:一个简单的类架构生成器
//版权所有 @ <%=DateTime.Now.Year%>  客户名称
//历史更新
//        <%=DateTime.Now%>        <%=Developer%>    零版本
///////////////////////////////////////////////////////////////////////////////////////
using System;
namespace <%=NameSpace%>
{

    
///<summary>    
    
///测试类
    
///</summary>

    public class <%=ClassName%>
    
{
    
        
///<summary>
        
///构造器
        
///</summary>

        public <%=ClassName%>()
        
{
        }

        
        
~<%=ClassName%>
        
{
        
        }

        
    }

    
}
=====================
Code Smith环境安装和配置
作者:佚名    厚朴教育来源:佚名    点击数:151    更新时间:2009-4-9

    Visual Code Smith是一款与Visual C/C++配套使用,免费的软件开发平台。

    在某种程度上,VcSmith是Source Insight、Visual Assist、CppUnit,以及VC 调试器的综合体,把诸多工具的优势集成到一个开发平台。但这种集成不是简单的拼凑,而是基于一种语言映射技术与在线调测技术,把C/C++软件开发的3 项主体活动(编码、调试、测试)有机的揉合在一起,使各项活动效率更高,更有质量保障。

    VcSmith适合给那些成天与VC代码打交道,不满足现有编程工具提供的开发效率,或不满足现有工具的易用性、直观性,或者有几款好用工具但无法整合起来用,东拼西凑用得不舒服,改用VcSmith或许是个明智选择。

    VcSmith特明适合给那些已经(或者将要)采用持续集成开发模式的人员使用,其编辑、调测一体的应用环境,简洁明快的用户界面,充分的外部工具集成能力,常让那些坚守IID理念而苦于缺少适用工具的人们欣喜不已。

    恰当使用VcSmith可望将开发效率与编码质量同时提升30% !


Code Smith环境安装和配置

主讲&文档撰写:Jacob.Huang
文档最后统筹:Jimmy.Ke
时间:2007-11-07
参与人员:Diapers Team & Enterprise Product Team

技术背景
    在Suryani.China的项目中,GenClaimsWarehouse等项目以Microsoft Enterprise Library作为基础的技术架构,包括其中的DataAccess BlockLoggerExceptionEncryptionCache等等,搭配使用Open SourceMyGeneration作为代码生成器。整体技术架构遵循三层模型,包括Entity包(实体包,与Database一一映射)、Data包(Access to Database,与数据库交互)、Core包(业务逻辑包,对Data包的简单代理以及扩展、事务实现)、Web表现层,其中EntityData包、Core包的大部分代码由MyGeneration自动生成,并通过partial class的方式支持自定义扩展。

    与这种存储过程和数据驱动的架构类似的解决方案是:CodeSmith + NetTiers组合。CodeSmith作为一个著名的代码生成工具,同样提供了基于模板生成C#VB.NETTSQL等语言代码的功能,并且支持ASP.NET语法的自定义模板;NetTiers则提供了一套成熟的基于CodeSmith的模板,在Microsoft Enterprise Library的基础上对其进行了封装和再组织,帮助开发者快速开发遵循三层架构的代码,以期在一定基础上统一并简化对EL的操作,避免重复的工作,减轻开发者的负担。本文是对本次茶话会的总结和扩展,对CodeSmithNetTiers做一个简单的介绍。Jacol.Huang也在茶话会上分享了他的开发经验。

环境安装和配置
    首先从www.codesmithtools.com 下载最新版本的Code Smith安装文件(Professional版本,有30天的试用期)。Code Smith有两个版本,Standard Profession版,我们使用Profession 版本,可以编辑模板。


    其次从www.nettiers.com 下载最新的Net Tiers包,NetTiers是免费的。

Code Smith Step by Step
    下载netTiers2.2后,解压到目录,右击选择Excute,打开CodeSmith配置窗口。


    在
CodeSmith配置窗口中编辑配置属性,比如数据源、代码输出目录、数据源表和视图等等。

    配置完毕后点击Generate生成工程包和代码,如下图所示,包括一份生成报告report.html

     CodeSmith的自定义模板支持ASP.NET语法,包括命名空间的引入和属性的读取。可以在模板中定义需要引入的命名空间和CodeSmith配置界面将呈现的属性,如下图所示。




NetTiers Step by Step
    下图是一个利用NetTiersCodeSmith生成的解决方案的截图,其中包括Web视图(自动生成的针对单表的维护界面)、Entities实体包、Services业务逻辑包等等。

    利用NetTiers,还可以生成自定义的存储过程、视图,可以在CodeSmith配置界面中配置生成的存储过程的前缀等属性。如下图所示。

     如果要扩展NetTiers框架生成的代码,则可以修改Processor,添加相应的扩展代码。如下图所示。


与现有技术架构的比较
    与现有的MyGeneration自定义模板相比,利用CodeSmith + NetTiers,架构基本上遵循NetTiers所定制的结构,每次修改数据库表结构后都需要重新生成代码,并将其拷贝到解决方案的相应位置。利用CodeSmith生成的自定义存储过程也是一样。

     另外,NetTiers是一个相对完善的框架,其生成的文件较多,对硬件的要求也相对较高,特别是大型系统。


技术参考
参考网站:http://www.cnblogs.com/iCaca/category/80950.html
博客园网友的Net Tiers系列学习笔记
关于EL的可以查看MSDN的相关WebCast
http://www.microsoft.com/china/msdn/events/webcasts/shared/webcast/consyscourse/EntLib.aspx
CodeSmith官网:http://www.codesmithtools.com
NetTiers官网:http://www.nettiers.com选择了自动上传Ôùþ|¸NŠ:íØbbs.51aspx.com6"+yºŸ&dec


SUMMARY: Many time while programming you will be coming across codes which you are doing again and again only with little changes. Example writing database codes, let get properties of business classes, making gui etc.How many times have you coded add,update,delete for customer master, supplier master, accounts master, journal master etc.In my experience these master and recurring coding templates consume almost 30% of your coding project time.These recurring codes with little changes to do again is not only tiresome but at long run you tend also loosing your standards of coding.This tutorial aims at getting some practical first hand experience on the tool called "Code Smith" which will do all the tedious task for you. Welcome to new world of template programming.
Scope : This tutorial is only till how you will use code smith and will not cover details of c# programming.there are many tutorials for learning c# so this article will deal only with code smith.
Introduction :- In my late project some 2 years back when using vb5,vb6 and asp i had always felt a need for template programming.As many a times i was coding the database update , add ,delete , writing the same store procedures and always felt no this has to be automised.We had written some semi automated program in house for stored procedures where we used to give table names and it used to code for us create, update stored procedures.Now that i have migrated to .NET platform i have decided to not code the recurring codes again.and landed to this cool thing called code smith.This tutorial will mainly will show how to code recurring codes for c#.

Download and Installation :- http://www.ericjsmith.net/. Theres no such deal you can download the freeware from the link said.I will not deal with details of how to install as its fairly simpler.Note after installation code smith will seen in the vc# IDE in Tools section.

Version :- This is tutorial is meant for version 2.5.So what features i am saying here is completed related to that so if you are reading this tutorial for some other version there can be changes.

How to start :-

Fixing your code smith editor:
1) The first thing to start with code smith is to decide which editor to use.After installing code smith goto code smith explorer.See image Select editor in the same directory of tutorial which says where to click for editor.well my personal opinion is to use notepad which you can get in winnt/notepad.exe.but you can select any other like ultraedit also thats a personal choice.Now that you are ready with you favourite editor we can move ahead.

2) Coding Hello world : You will see lot of folders in samples folder in the code smith explorer and all categorised properly.These samples provide very good base for learning as they all have premade codes in it.right click on the code smith explorer and click on add new folder called as "Learn Code Smith" we will put all out code smith code inside this folder.As like all good new learner in the world lets start with "Hello World".now right click on the folder "learn code smith" created by you and say add new c# template.All code smith files have extension .cst.

The first line you will see in the Template Cst file is

<%@ CodeTemplate Language="C#" TargetLanguage="Text" Description="Hello Word" %>

This line says that which language to use and short description to say what the template name.This statement is like a directive and does not affect any where the output of the code

and the next line is as simple as it looks "Hello word"

That completes our coding part of code smith for the hello world.Now we have to compile the project.Right click on HelloWorld.cst and click execute you will get the following output if everything is ok

---------------- Compile started -----------------


Build complete -- 0 errors, 0 warnings

---------------------- Done ----------------------

Build succeeded

lol to see the out put click on generate ..... drink a coffee now.....

3) Input parameters to Template :After hello world like any other good tutorial lets write code for accepting some string and displaying it 10 times.So right click and add new c# file called as display.cst.So the first declaration is by default the declaration
<%@ CodeTemplate Language="C#" TargetLanguage="Text" Description="This accepts input and displays the output 10 times" %>

then next we say the variable through which the input has to be made
<%@ Property Name="AcceptMessage" Type="System.String" Description="The message to display 10 times" %>
then follows the code normal c# syntax to display the message

<% int pintcount;
for (pintcount=0;pintcount<10;pintcount++)
{%>
<%=AcceptMessage%>
<%}%>

there goes the whole code at once


<%@ CodeTemplate Language="C#" TargetLanguage="Text" Description="This accepts
input and displays the output 10 times" %>
<%@ Property Name="AcceptMessage" Type="System.String" Description="The message
to display 10 times" %>
<% int pintcount;
for (pintcount=0;pintcount<10;pintcount++)
{%>
<%=AcceptMessage%>
<%}%>
note the AcceptMessage way its displayed is like a classic asp syntax. now right click and execute. Put some value in acceptmessage and say generate thats 10 times displayed the message.
4) Writing a simple component let get properties :- now we know how the display is done , how the parameters can be fed in to code smith template.lets go for some practical implementation.The most boring task in object oreinted programming is creating classes with let get properties with proper data type and naming conventions.Specially in database projects to make template buisness object with let get for every table becomes boring.So this section will cover the details of creating a let get from database table.We are going to use sql server, database will be the favourite northwind and employeetable.so lets add letgettemplate.cst to the learn code smith folder.

so heres the declarative statement of letgettemplate.cst

<%@ Assembly Name="SchemaExplorer" %>
<%@ Import Namespace="SchemaExplorer" %>
<%@ CodeTemplate Language="C#" Src="CSLAHelper.cs" Inherits="CSLAHelper" TargetLanguage="C#" Description="Generates
a Basic Class of let and get properties" %>
<%@ Property Name="DevelopersName" Type="String" Description="This is needed to
tell Who has developed" %>
<%@ Property Name="CodedOnWhichdate" Type="String" Description="Says when the
developer has coded" %>
The syntaxes are very much the same meaning as we have in dot net.But the main declarative is the codetemplate."CSAHelper.cs" which already has many prefunctions which we will be using.I think code smith has almost all basic function we need in the "CSAHelper.cs".you will find this file in "D:\Program Files\CodeSmith\v2.5\Samples\CSLA.NET\C#\".for this tutorial please copy that file in "Learn Code Smith" directory which we have created for learning as we will be using most of the exisiting functions from this.So the code template attribute says that which is the file  we will be using in this template.We can also write our own exisiting function and module in a files and give it in CodeTemplate property.The next two property are just for saying that who has developed this module and what date.
ok now the next statement
<% ColumnSchemaCollection NPKs = RootTable.NonPrimaryKeyColumns; %>
here we define a NPKs variable of ColumnSchemaCollection type.the rootable variable will have all the column collection.Note roottable variable is defined in CSLAHelper.cs and all implementation is also provided in the that file.if more keen just open in notepad and you will know every thing.
now we have all non primary key inside the npk variable we can just browse and display and the let and get

using System;
// Coded by <%=DevelopersName %> on <%=CodedOnWhichdate%>
namespace <%=ClassNamespace%>
{
public class Cls<%=ObjectName%>
{
private const string ClassName="Cls<%=ObjectName%>";
<% foreach(ColumnSchema col in NPKs) { %>
<%= GetMemberVariableDeclarationStatement(col, "",true) %>
<%}%>
private Cls<%=ObjectName%>Db mobjCls<%=ObjectName%>Db;
<% foreach(ColumnSchema col in NPKs) {string propertyName = GetPropertyName(col);%>
public <%=GetCSVariableType(col)%> <%=GetCamelCaseName(propertyName)%>
{
get
{
return <%=GetMemberVariableName(col,"")%>;
}
set
{<%=GetMemberVariableName(col,"")%> = value;
}
}
<%}%>
public Cls<%=ObjectName%>()
{
}
}
}
I know the above code is little heavy to digest but what output we are looking
for is some thing like this shown below and the upper coding in code smith
matches with the template below. see the <%=CodedOnWhichdate%> been replaced by
1/1/2004.see the <%=DevelopersName %> replaced by Shivprasad Koirala (well thats my name) and so on.The GetCSVariableType function gives us the data type mapping
in c# i mean nvarchar become a string in c# GetMemberVariableName gives the
column name.
using System;
// Coded by Shivprasad Koirala on 1/1/2004
namespace NameSpaceEmployee
{
public class ClsEmployee
{
private const string ClassName="ClsEmployee";

private string _lastName;
private string _firstName;

 

private ClsEmployeeDb mobjClsEmployeeDb;
public string lastName
{
get
{
return _lastName;
}
set
{
_lastName = value;
}
}
public string firstName
{
get
{
return _firstName;
}
set
{
_firstName = value;
}
}


}
}

so heres the full code now
<%@ Assembly Name="SchemaExplorer" %>
<%@ Import Namespace="SchemaExplorer" %>
<%@ CodeTemplate Language="C#" Src="CSLAHelper.cs" Inherits="CSLAHelper" TargetLanguage="C#" Description="Generates
a Basic Class of let and get
properties" %>
<%@ Property Name="DevelopersName" Type="String" Description="This is needed to
tell Who has developed" %>
<%@ Property Name="CodedOnWhichdate" Type="String" Description="Says when the
developer has coded" %>
<% ColumnSchemaCollection NPKs = RootTable.NonPrimaryKeyColumns; %>
using System;
// Coded by <%=DevelopersName %> on <%=CodedOnWhichdate%>
namespace <%=ClassNamespace%>
{
public class Cls<%=ObjectName%>
{
private const string ClassName="Cls<%=ObjectName%>";
<% foreach(ColumnSchema col in NPKs) { %>
<%= GetMemberVariableDeclarationStatement(col, "",true) %>
<%}%>
private Cls<%=ObjectName%>Db mobjCls<%=ObjectName%>Db;

<% foreach(ColumnSchema col in NPKs) {string propertyName = GetPropertyName(col);%>

public <%=GetCSVariableType(col)%> <%=GetCamelCaseName(propertyName)%>
{
get
{
return <%=GetMemberVariableName(col,"")%>;
}
set
{
<%=GetMemberVariableName(col,"")%> = value;
}

}

<%}%>
public Cls<%=ObjectName%>()
{
}
}
}
when you run the code in code smith you have to provide namespace,choose table,object name,date created,name of programmer and just say generate.thats 20 % of your work.
I have give all the folder zipped with it which will just work if you paste in the code smith installed directory

Last words :- if you go through the other templates give in code smith you have idea of how you can really make it useful.I have been using code smith right from making GUI(where all my txtboxes etc etc are taken care off),buisness object(let get) and till the end to write database stored procedures.It really speeds up your development process by atleast 30%.... and also maintaining tight naming conventions.I am also giving so called a fulltemplate.cst attached with the tutorial till what extent i have gone.but yes my coding standards will be different from yours.by fulltemplate.cst needs some fixing manually but thats ok for me as i have already made a template on which i should code.

by shivprasad koirala(Ag technologies)
Special thanks to Ganesh g(Ag technologies) for his help.


这段模板生成的C#代码如下
///////////////////////////////////////////////////////////////////////////////////////
//文件名:MyClass.cs
//说明:一个简单的类架构生成器
//版权所有 @ 2005  客户名称
//历史更新
//        2005-5-19 17:39:13 上午        Heroman    零版本
///////////////////////////////////////////////////////////////////////////////////////
using System;
namespace FunSoft
{

    
///<summary>    
    
///测试类
    
///</summary>

    public class MyClass
    
{
    
        
///<summary>
        
///构造器
        
///</summary>

        public MyClass()