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.

浙公网安备 33010602011771号