Visual Studio Hacks [Electronic resources] نسخه متنی

اینجــــا یک کتابخانه دیجیتالی است

با بیش از 100000 منبع الکترونیکی رایگان به زبان فارسی ، عربی و انگلیسی

Visual Studio Hacks [Electronic resources] - نسخه متنی

Andrew Lockhart

| نمايش فراداده ، افزودن یک نقد و بررسی
افزودن به کتابخانه شخصی
ارسال به دوستان
جستجو در متن کتاب
بیشتر
تنظیمات قلم

فونت

اندازه قلم

+ - پیش فرض

حالت نمایش

روز نیمروز شب
جستجو در لغت نامه
بیشتر
لیست موضوعات
توضیحات
افزودن یادداشت جدید







Hack 50. Define Templates for Generating Code

Whenever possible, take a shortcut. You can use
the CodeSmith custom tool to generate code from templates that you
create.

CodeSmith is a popular .NET code generation
tool. The normal CodeSmith application is a Windows Forms application
that allows you to create templates in an ASP.NET-like syntax, and
then generate code using those templates. The templates can be based
on simple variables specified at the time of the template execution,
or they can be based on database tables or other objects.

CodeSmith is an excellent time-saver because you can generate any
part of your application using the completely customizable templates.
And while the normal CodeSmith application is valuable, another part
of CodeSmith is built directly into Visual Studio.

The normal CodeSmith application performs what is called
passive code
generation
. Passive code generation is when you
generate code and then add it to your application as separate steps.
The code in your application could even be edited after generation,
meaning that you could not generate the code again without losing
your changes to the code. The CodeSmith custom tool performs what is
called active code
generation
. Active code generation is when code
is generated on the fly, usually during the build process of your
solution. Using active code generation, you almost never modify the
code generated, since it would simply be overwritten the next time
you build your solution. The CodeSmith custom tool is a little bit
different in that it generates the code when you save the file, as
opposed to during the build process, but the result is the same. (You
could also create a custom build step to execute the templates
[Hack #34] .)

The first step in using CodeSmith is downloading and
installing it. CodeSmith can be downloaded from http://www.ericjsmith.NET/codesmith. During
the installation process, you will be asked if you want to add
support for Visual Studiobe sure to answer yes.


6.8.1. Creating a Template


To
make use of this tool, you first need
to add a new CodeSmith template to your Visual Studio Project by
right-clicking on your project and choosing Add New Item. From the
Add New Item dialog, choose Text File and save the file with a
.cst extension. (You could also create a new
template from the CodeSmith Explorer window.)

Here is a simple CodeSmith template to generate a dictionary-based
collectionyou can put this in your .cst
file to try it out:

<%@ CodeTemplate Language="C#" TargetLanguage="Text" 
Description="Sample Template" %>
<%@ Property Name="className" Type="System.String"
Description="This name of the class" %>
public class <%=className%>Dictionary :
System.Collections.DictionaryBase
{
public <%=className%> this[int <%=className.ToLower( )%>ID]
{
get { return ((<%=className%>)(
Dictionary[<%=className.ToLower( )%>ID])); }
set { Dictionary[<%=className.ToLower( )%>ID] = value; }
}
public ICollection Keys
{
get {return( Dictionary.Keys );}
}
public ICollection Values
{
get {return( Dictionary.Values );}
}
public bool Contains(int <%=className.ToLower( )%>ID)
{
return Dictionary.Contains(<%=className.ToLower( )%>ID);
}
public void Add(int <%=className.ToLower( )%>ID,
<%=className%> <%=className.ToLower( )%>)
{
Dictionary.Add(<%=className.ToLower( )%>ID,
<%=className.ToLower( )%>);
}
public void Remove(int <%=className.ToLower( )%>ID)
{
Dictionary.Remove(<%=className.ToLower( )%>ID);
}
}

This template will generate a strongly typed dictionary class based
on a single property. At the top of the template, you can see that it
expects the name of the type, its sole parameter. Using this
property, CodeSmith will fill in this template and create the output.
If you look at the syntax of the template, it is very similar to
ASP.NET and you can see where the value of the property will be
inserted between the <% and
%> symbols.

This template could be executed as-is from the normal CodeSmith
application, but to use the custom tool, you need to do a little more
work.


6.8.2. Creating the XML


The

next step is to create an XML file
that will be used by the custom tool. First, add a new XML file
(right-click on your project and click Add Add New Item,
then select XML File from the list) to your project and then enter
the following XML:

<?xml version="1.0" encoding="utf-8" ?>
<codeSmith>
<!-- template that will be used to generate code -->
<template path="SimpleClass.cst" />
<!-- namespace for the generated code -->
<namespace>Vehicles</namespace>
<!-- namespaces that should be imported -->
<imports>
<import namespace="System" />
<import namespace="System.Collections" />
</imports>
<!-- list of property sets which each get
loaded into the template and executed -->
<propertySets>
<propertySet>
<property name="className">Car</property>
</propertySet>
<propertySet>
<property name="className">Truck</property>
</propertySet>
</propertySets>
</codeSmith>

The template element specifies the name of the
template you want to execute. The namespace
element specifies what namespace your generated class should be
included in. The imports element lists all of the
namespaces that should be included in your generated class. With this
template, you will need to include System and
System.Collections as the
Dictionary class is in the
System.Collections namespace. Finally, the
propertySets element contains any number of
property sets that will be passed to the template. In this sample XML
file, I have specified two property sets, one
with the class name of Car and the other with the class name of
Truck. Property sets are the automated method of specifying
parameters when running the template. The property set contains
exactly what you would specify if you were running the template
through the normal GUI.


6.8.3. Execute in Visual Studio


The
next step is to set up and execute the
CodeSmith custom tool. Just as with other custom tools, you need to
specify the name of the custom tool in the properties page of the XML
file. The name of the CodeSmith custom tool is
CodeSmithGenerator. A configured XML Properties
page is shown in Figure 6-10.


Figure 6-10. CodeSmith custom tool

Once you have specified the custom tool, you will see the generated
code in the Vehicles.cs file. (Remember, to see
files created by a custom
tool [Hack #47] , you will need
to click the Show all Files button on the Solution Explorer.)

Here is the code that CodeSmith generated:

//-------------------------------------------------
// <autogenerated>
// This code was generated by CodeSmith.
// Version: 2.6.0.117
//
// Changes to this file may cause incorrect behavior
// and will be lost if the code is regenerated.
// </autogenerated>
//-------------------------------------------------
using System;
using System.Collections;
namespace Vehicles
{
public class CarDictionary : System.Collections.DictionaryBase
{
public Car this[int carID]
{
get { return ((Car)(Dictionary[carID])); }
set { Dictionary[carID] = value; }
}
public ICollection Keys
{
get {return( Dictionary.Keys );}
}
public ICollection Values
{
get {return( Dictionary.Values );}
}
public bool Contains(int carID)
{
return Dictionary.Contains(carID);
}
public void Add(int carID, Car car)
{
Dictionary.Add(carID, car);
}
public void Remove(int carID)
{
Dictionary.Remove(carID);
}
}
}

I am showing only the first class generated for
brevity's sake. As you might imagine, the second
class is exactly the same except for a different class name. You can
modify the XML file and add additional property sets, or you can
modify the template and the custom tool will always keep your code
up-to-date.

CodeSmith is an extremely valuable tool, and I encourage you to
explore it further. More information can be found at the
home page for CodeSmith, which is at


http://www.ericjsmith.NET/codesmith.


/ 172