在15分鐘內構造一個數據訪問層。

本文源於對官方教程的翻譯,原文請查看官方網站。

Build a Data Access Layer in less than 15 minutes
15分鐘內構造一個數據訪問層。

DOWN LINKS
下載鏈接

·  Download a free 30 day trial of CodeSmith Professional (下載一個免費的30天的試用版CodeSmith)

·  Download latest .netTiers templates (下載最新的.net(Tiers不知道該如何翻譯)模版)

·  Watch a video presentation of this article(觀看本教程的視頻版)

Introduction
簡介

In this article you will learn how to build a Data Access Layer using Microsoft’s Enterprise Library in less than 15 minutes using CodeSmith and the .netTiers Template Library.
在這篇文章中,你將會學習到如何使用微軟的企業庫在15分鐘之內藉助CodeSmith.netTiers模版庫構造一個數據訪問層。

The Data Access Layer, from here on out referred to as the DAL, is the layer of application functionality that encapsulates all interactions with the database. Typically this type of code is hand written and requires specialized knowledge, not only of .NET, but of the specific data access routines too. Writing the DAL code for an application is one of the most monotonous, time consuming, repetitive, and likely bug-ridden aspects of building software.
數據訪問層,這裏我們簡寫爲DAL,是應用程序中與數據庫交互的封裝。這些代碼手寫的時候需要一些專業的知識,僅僅.net是不夠的,還需要一些數據訪問的知識。對應用程序寫DAL代碼是枯燥,耗時,重複性高,而且也是BUG的高發地段。

For this article we’ll use the sample Northwind database in SQL Server, but these examples will work with any database. And of course, after this article you’ll no longer view writing the DAL for your application as monotonous and time consuming, but quick, easy, and simple!
在這個文檔中,我們將會使用SQL Server 中的實力數據庫Northwind,但是這個例子可以工作與所有的數據庫。當然,在學習了這個教程後你也不必再爲你的應用程序機械,重複,枯燥的編寫DAL,它將會變得輕鬆簡單。

If you follow this article at the end you will be able to create a complete best practices Data Access Layer in just under 1 minute (the other 14 minutes are for downloading the software the first time).
在這個文章結束時你將能夠在一分鐘之內構造一個不錯的DAL(其餘的14分鐘時用於第一次使用時下載軟件)

 

Code Generation, a brief overview
簡單介紹一下代碼生成

Code generation, or the use of software tools to generate code, is not a new concept. In fact, code generation has been around for quite some time. In this article I’m going to use CodeSmith as the tool for generating both the code and T-SQL scripts for the DAL.
代碼生成,或者使用軟件工具來生成代碼並不是一個新的玩意兒。事實上這個東西很久之前就有了。在這個文章中,我將使用CodeSmith作爲代碼和T-SQL腳本的代碼生成工具。

CodeSmith is a developer productivity tool that enables developers to use templates to control the formatting and desired code output. Therein is the beauty of CodeSmith - software developers still retain full control over the code created through templates. Templates provide the opportunity for people to create new and interesting code reuse and generation libraries, such as the .netTiers templates used in this article.
CodeSmith
是一個允許開發者使用模版來控制生成代碼的格式和生成的代碼的輸出的開發工具。開發者通過模版仍然保持對生成的代碼的完全掌控----在這一點上CodeSmith做的很漂亮。模版提供人們一種對創建新代碼和重用代碼生成庫的機會。例如本文中使用的.netTier模版。

Step 1 – Setup
第一步----安裝

The first step is to get the necessary tools (CodeSmith) and templates (.netTiers). CodeSmith is a commercial developer tool, but there is a 30-day free trial we can use for the purpose of this article:
首先我們需要得到必須的工具(CodeSmith)和模版(.netTiers)CodeSmith是一個商業開發工具,但是我們也可以得到一個30天的免費試用版本(對於我們的教程這就足夠了)。

Download and Install CodeSmith
下載和安裝CodeSmith

http://www.codesmithtools.com/

CodeSmith comes with a lot of built-in templates and the next service pack will include the .netTiers templates shown in this article.
CodeSmith
有一大堆的內建模版和next服務包,包括我們在本文中要使用的.netTiers

Now that CodeSmith is installed, download the .netTiers template library:
現在CodeSmith已經被安裝上,下載.netTiers模版庫。

Download .netTiers Template Library for CodeSmith
下載CodeSmith.netTiers模版庫

http://www.nettiers.com/

On the .netTiers site click on the "Latest Download" link in the left-column; next, click on "available for download" at the top of the page. This will take you to another page where you can download the latest Windows MSI installer.
.netTiers頁面上單擊左邊一列的“Latest Download”鏈接,單擊頁面頂端的“available for download.這將會鏈接到下載頁面。

The last step is to ensure you have a SQL Server database setup and have a connection string you can use to connect to the database.
下一步是確信你的機子上安裝了SQL Server數據庫,並且你能夠擁有一個鏈接到數據庫的鏈接字符串。

Step 2 – CodeSmith
第二步—CodeSmith

After downloading and installing CodeSmith you should be able to open it from All Programs | CodeSmith 3.1 | CodeSmith Studio. Before we use the .netTiers templates you need to familiarize yourself with CodeSmith.
在下載和安裝了CodeSmith後,你將能夠在開始菜單的 所有程序|CodeSmith|CodeSmith Studio下面打開它。在我們使用.netTiers模版的時候你需要先熟悉一下CodeSmith的開發環境。

As mentioned in the introduction, CodeSmith is a template driven code generation tool. There is a window on the right of CodeSmith called the Template Explorer. The Template Explorer provides you with a quick and easy way of accessing the templates you’ve installed or written:
正如上面所提到的,CodeSmith是一個模版驅動的代碼生成工具。在CodeSmith右邊有一個稱作模版管理器的窗口。模版管理器提供了一個方便簡捷的方法來訪問你安裝的或者曾經寫過的模版。

To explain the rest of CodeSmith we need a template. Open the Hashtable.cst template from Template Explorer by double-clicking on it.
要了解CodeSmith的剩餘部分,我們需要一個模版。從模版管理器中雙擊打開Hashtable.cst模版。

Hashtable.cst is one of the great sample templates included with CodeSmith and is used to generate strongly typed collections that use the .NET Hashtable type as the base data type. Before we explain the template, let’s quickly look at another window in CodeSmith, the Properties window:
Hashtable.cst
CodeSmith中一個很不錯的模版。它能夠藉助.NET Hashtable類作爲父類產生強類型的結合。在解釋模板之前,讓我們瀏覽一下CodeSmith中的另一個窗口----屬性窗口。

The Properties window allows you to set properties for the template. When using the Hashtable.cst template we need to set some common elements such as the generated ClassName, ItemType, and KeyType. For example, if you wanted to create a strongly typed collection of Person objects accessed by an integer with a class name of PersonCollection, you would set the ClassName to PersonCollection, the ItemType to Person, and the KeyType to int. You could generate the source for this strongly typed collection now by simply clicking the Run button in CodeSmith (found on the toolbar).
屬性窗口允許你設置模板的屬性。當使用Hashtable.cst模版之前,我們需要設置一些元素,例如生成的類名。值名和鍵名。例如,如果你想創建通過一個整數訪問的Persong類的強類型集合PersonCollection,你需要設置ClassName屬性的值爲PersonCollectionItemType屬性的值爲PersonKeyType屬性的值爲int。你現在可以通過單擊CodeSmith中工具欄上的Run按鈕來產生這個強類型集合的源碼。

If you took a moment to examine the Hashtable.cst template file you might say to yourself, "This looks a lot like ASP.NET". You’d be correct. CodeSmith templates are modeled after ASP.NET Pages and share many similar ideas. However, whereas ASP.NET Pages are used to generate HTML, CodeSmith Templates are used to generate source files or other text files.
如果你花費時間來查看一下Hashtable.cst模版文件,你或許會驚歎:“哇,這跟ASP.NET的代碼太像了!”,是的,CodeSmith模板的語法的確根ASP.NET有異曲同工之妙。然而,ASP.NET是被用來生成HTML的,CodeSmith模版是用來生成原代碼文件或者其他的文本文件的。

The most important thing to remember about CodeSmith is that CodeSmith does not limit your creativity by forcing you into what code is generated. Since it is template driven the code output is completely controlled by you.
你需要了解關於CodeSmith的重要的一點是它並不限制您的創造力來強迫你使用某種格式的生成的代碼(沒有任何的副作用)。一次它是模版驅動的代碼並且輸出是可以被你完全控制的。

Step 3 – Generate the DAL
第三步----產生DAL代碼

Now that you have a basic understanding of CodeSmith I want to show you the .netTiers templates.
你已經對CodeSmith有一個基本的瞭解了,現在我想介紹一下.netTiers模版。

Remember, the idea behind CodeSmith is that it allows you to write code faster, with fewer defects. The .netTiers templates take that one step further and create a DAL for you that follows all the recommended Patterns & Practices from the team at Microsoft by the same name.
記住,CodeSmith的意圖是讓你更快更少錯誤的編寫代碼。.netTiers模版提供了使用常用的方法創建DAL的代碼。(這些翻譯的不好,請查看原文)

First we need to add the .netTiers templates to the CodeSmith Template Explorer:
首先,我們需要添加.netTiers模版到CodeSmith模版管理器:

  1. In Template Explorer click on the Open Folder icon to browse for a folder containing templates.
    在模版管理器中單擊打開文件夾圖標,來瀏覽一個文件加內所包含的模板。

  2. Go to the folder where .netTiers was installed. On my computer this is:
    C:/Program Files/SerialCoder/NetTiers 0.9.2 - Caribert/Templates/
    打開.netTiers被安裝的文件夾的位置,在我的電腦上是:
    C:/Program Files/SerialCoder/NetTiers 0.9.2 - Caribert/Templates/

  3. Once this folder is created as a shortcut in Template Explorer, expand it and select NetTiers.cst
    一旦這個文件夾被創建作爲模版管理器中的快捷方式,展開並選擇NetTiers.cst

  4. Now that the .netTiers templates are installed you need to configure a data source. With the NetTiers.cst template open, open the Properties window and configure a Source Database by clicking on the ellipses:

    現在已經安裝了.netTiers模版,你需要配置一下數據源。打開NetTiers.cst模版,打開屬性窗口通過點擊下面的按鈕來配置數據源。

  5. This opens the Database Picker, we’re going to create a new data source so click on the ellipses in the Database Picker to open the Data Source Manager. In the screen shot below is an example of how this should look (choose a name that let’s you quickly know what database you’re working with):

    這將會打開數據庫選擇器,我們將創建一個新的數據源,因此點擊數據庫選擇器來打開數據源管理器。如下面的窗口所示。(選擇一個你能夠容易記住的名字)

  6. Test the connection to ensure it works and then back out of these dialog windows by clicking OK. Make sure the new data source is selected.
    測試一下鏈接。確信它能夠連接到數據庫,然後確定返回。

  7. Finally, set the EntireDatabase property to True, set the NameSpace property to Demo, and set the OutputDirectory property to the directory where you would like the generated files to be located. You will need to create the output directory if it doesn’t exist.
    最後,設置EntireDatavase屬性爲True,設置命名空間爲Demo,設置OutputDirectory屬性作爲你想生成的代碼文件的目錄。如果目錄不存在,你需要創建一個。

Once you’ve completed these steps your property window for the NetTiers.cst template should look similar to the screenshot below (changes highlighted):
一旦尼完成了這些操作,你的NetTiers.cst的屬性窗口將會如下圖所示。

We are not going to show anywhere near the full capabilities of .netTiers in this article or CodeSmith, but we’ve now done enough to generate a DAL. Click the Run button in the CodeSmith toolbar to generate the code.
我們不會講解.netTier的內容。但是我們現在掌握的東西已經足夠來生成DAL了,點擊工具欄中的Run按鈕來生成代碼。

Step 4 – Review the Generated Code
第四部----預覽一下生成的代碼

Open Visual Studio .NET and if you followed the directions above you should find a Demo.sln file in the c:/NetTiers/Northwind_Demo/ directory.
打開Visual Studion .NET 如果你按照我們的嚮導執行,那麼你可以在c:/NetTiers/Northwind_Demo/ directory下發現一個Demo.sln文件

Take a moment and browse the solution and project files in Visual Studio:
用一點時間來瀏覽一下顯示在Visual Studio 中的解方案和工程

You should find 3 projects within the solution:
你將會發現在解決方案下有3個項目

Demo – the main library that contains the classes you will use within your application to interact with the database.
Demo ---
你需要在你的應用程序中使用的與數據庫交互得主類庫項目

Demo.DataAccessLayer – the library containing the data access implementation code.
Demo.DataAccessLayer ----
包括數據訪問擴展代碼的類庫。

Demo.DataAccessLayer.SqlClient – the library containing the Microsoft Patterns & Practices classes for working with the database.
Demo.DataAccessLayer.SqlClient –
包括Microsoft Pattern & Practices 的數據類。

Step 5 – Compile …and we’re done!
第五步 編譯我們已經完成了

Next, with Visual Studio still open, compile the project.
然後,保持Visual Studion 處於打開狀態,編譯項目。

Congratulations! You now have a Data Access Layer that implements the recommended best practices from the Microsoft Patterns & Practices group for working with a database.
祝賀!你現在已經有了一個微軟推薦的格式的數據訪問層。

You can now begin using your new Data Access Layer in other Visual Studio .NET projects. For example, below is code to retrieve, update and then delete an employee record.
你可以開始在其他的Visual Studio .net項目中使用這個新的數據訪問層。例如,下面的代碼是獲取,更新和刪除一個員工記錄的示例。

using Demo.DataAccessLayer.SqlClient;

 

// Select by primary key

Employee employee = SqlDataRepository.EmployeeProvider.GetByEmployeeID(13);

employee.FirstName = "John";

employee.LastName = "Doe";

 

// Save changes

SqlDataRepository.EmployeeProvider.Save(employee);

 

// Delete record

SqlDataRepository.EmployeeProvider.Delete(employee);

   

For more information on how to use the generated DAL, take a look at the .netTiers manual here:
想知道更多的關於如何使用生成的DAL代碼的信息,請查看.netTiers手冊:

http://www.nettiers.com/nettiers-manual-v1.aspx

Remember all of the Data Access Layer code was generated by templates, so later when you change your database structure you can simply rebuild the DAL again from the templates. Furthermore, you can even extend the templates with your own ideas, comments, naming conventions, patterns, and so on.
記住所有的數據訪問層的代碼都是通過模版聲稱的,因此,隨後當你改變你的數據庫的結構的時候,你可以通過剛纔的模版簡單的重新構造DAL。更牛的是,你甚至可以用你的意圖來擴展這些模版,註釋,轉換,樣式等等。

Conclusion
結論

The possibilities for CodeSmith templates are limited only by your own creativity. As I’ve demonstrated in this article, CodeSmith is an exceptionally powerful developer productivity tool. Coupled with the .netTiers templates you can write a best practices Data Access Layer for your application in a matter of minutes.
CodeSmith
模版的能力只受你的創造力的約束。就像我在本文中解釋的,CodeDmith是一個超級強大的開發生產工具。在模版的幫助下你可以在短短的幾分鐘之內構造一個優秀的數據訪問層。

You can also watch a video of this presentation here:
本教程視頻版到下面的網址觀看:

http://community.codesmithtools.com/r.ashx?id=1

One of the fun features added into version 3.1 was a simple "value calculator". The value calculator provides a conservative estimate of the time saved by using CodeSmith:
3.1
版中的一個新特性是簡單的“值計算”。值計算提供了一個保守的通過使用CodeSmith 節省的時間的評估。

As shown in the screenshot above, using the .netTiers templates with CodeSmith generated 91,559 lines of code. Assuming a developer can write approximately 50 lines of code per-hour (had we written this manually) writing the code we generated would have taken 1,800 hours. Taking this a step further and assuming that a developer’s time is approximately $60/hour, CodeSmith and .netTiers together saved you 1,800 hours of your life and $109,000 for your company!

So get CodeSmith… and then go ask for a raise.
就像上面的在抓屏圖片中顯示的那樣,.netTiers模版生成了91559行代碼,假設一個開發者每小時能夠寫50行代碼(手工狀態下)。那麼我們寫這些代碼將會花費1800小時。進一步推算,如果開發人員的薪水是每小時60美元,那麼CodeSmith使用.netTiers將會節省你1800小時的生命併爲您的公司節省109000美元。(哎,咱怎麼連份工作都找不到呢?,老外雜就這麼強呢?)

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章