Three-layer Schema code generator (Nettiergenerator)

Source: Internet
Author: User
Tags generator sessions
net Layered Schema builder

· Download Source-157 KB

· Download sample-456 KB

Brief Introduction

There are many Object relational mapping (ORM) and Code generation programs (generator), such as (nhibernate,nettiers,entity framework, etc.), some of which are based on a template-driven engine, Others are based on the solution framework. The program that this article will show is based on my own solution framework, so it's not just an object relational mapping tool, it focuses on how to present a superior development environment for any project or project.

Solution Framework

In short, my solution framework can still be described in a classic three-tier architecture. This framework includes the data Access Layer (DAL), the Business Logic layer (BLL), and some presentation layer rules (GUI). This framework follows Microsoft's publication of the right. NET application Architecture (application architecture for. NET) is recognized as best practice. This architecture can be represented by the following graphic:

But in my own opinion, the great advantage of this program is that there is an intermediate transition layer between the code generator and the underlying data store (I call it metalayer), which is a set of XML files that describe the underlying data storage structure, This gives developers an easy way to extend basic functionality (declaring new business entity classes, new data-reading methods, and so on).

layers in the solution framework

One of the most important terms in this solution is "services", where the solution operates at various levels like a vertical brick to the concrete to glue the functions of each system. For example, for a dictionary that is stored in each country, we will have a countryinfodto object, a countryservicedal, a icountryservicedal, and Countryservice in the business Logic layer , the key point is that each service is implemented as stateless (stateless Class). Each layer is constructed in one of the following ways: The method of the Dal service should be invoked by the service of the corresponding business logic. Data access has been implemented as a data provider accessed through a data factory. This allows us to derive a perfect abstraction from the specific DAL implementation. Each layer is implemented as a stand-alone project (or assembly), so a typical solution will include the following projects: Common,configuration Management, metalayer,business entities Model, Data access Layer interfaces,data access Layer implementation, DAL Factory, and Business logic, as shown in the following illustration:

The functions of each project are described below, and some examples will be given.

Common

The project is where public code is placed (including global lookups in programs, public programs, and so on), with two important features that are tightly integrated into the solution and the Code generator program:

1, the global lookup in the program can be used for business entity mapping;

2. The business entity validation engine and the Modify history tracking engine are also located in this assembly.

Configuration Management

This is a project of configuration management through the "*.config" file, and I have described in detail the implementation of configuration management in my article. One of the main benefits of this project is to implement a feature that uses simple code to obtain configuration information.

string applicationname = CustomSettings.Current.ApplicationName;

Business Entity Model

It is a set of independent projects to achieve a group of data transmission objects, in addition to a simple data on the background of a container, the data transfer object also has the following functions:

Application-level data validation, iclonable, iequatable<>.

Data validation features from Nettiers This project, its core is to implement a set of independent static methods, each data transformation object class in the following ways to use these static methods:

Privatestaticvoid Adddatabasechemarules ()

{

Goodinfomodel.validation_rules. Addrule (Commonrules.notnull, "Name");

Goodinfomodel.validation_rules. Addrule (Commonrules.stringmaxlength,

New Commonrules.maxlengthruleargs ("Name", 50));

Goodinfomodel.validation_rules. Addrule (Commonrules.notnull, "cost");

Goodinfomodel.validation_rules. Addrule (Commonrules.notnull, "Quantity");

}

Data Access Layer

There are a number of ways to present data to the needs of your application. One is Microsoft's Ado.net, which uses DataTables and dataadapters for data maps based on data tables, and the other is the way in which many ORM (such as nhibernate,nettiers) are used, which is based on the row-level mapping of the datasheet. This means that the solution framework is a data map at the row level of the datasheet like any other ORM, and the implementation of this DAL can be divided into three points:

1, a group of DAL services to achieve a specific function;

2, a group of interfaces covering a group of Dal objects;

3. The Dal factory creates an instance of a specific Dal service class at run time.

The implementation of the DAL function will depend on the specifics, and I use the example code in the attachment as a way of approaching the data Access Application Block v1, which the reader can see in the source code.

underlying database rules

I follow a few rules for database development:

1. Naming conventions for database objects:

A Data Table---tblnamespace.essence (example: Tbladministration.user, Tbladministration.role, tbldictionary.country);

b The View---vwnamespace.essence (example: vwdictionary.country), TBL/VW is the prefix representing Table/view, administration/dictionary represents some kind of namespace, The User/role/country suffix represents the object.

2, only the underlying database as a data storage container, do not do other business operations here, in other words, is to avoid the use of triggers to business goals, stored procedures. Consider a database as a container for storing only data, indexes, and data integrity;

3. Use GUIDs as primary keys (do not use integers as identities).

Business Layer

The following issues need to be addressed at this level:

1, the most important thing is the implementation of Session management (Management), especially the implementation of the History of affairs Management (Transaction Management);

2, the actual problem is to the underlying database (or other places) read data to cache the ability;

3, if a regular developer can avoid making common sense errors, then this will be a very useful result.

The problem of Session management and transaction management has been solved in other ORM. The interface classes for a session and transaction are maintained at the business logic level in a static thread, so there is no need to maintain the session between function invocations, and there are strict rules in the business logic layer to handle sessions and transactions. Caching is implemented as an independent service based on the MS Enterprise Library caching. The implementation of the cache is heavily used. The new features in NET2.0----anonymous methods, so it's very easy to implement data caching.

I have achieved the use of DAL at BLL level, a method that Microsoft has implemented in his open project, PetShop 4. The BLL class uses the Idal as an internal static member, using the Dal factory to instantiate the concrete implementation.

privatestaticreadonly iagreementservicedal dal =

Dalmanager.createinstance ("Economy.agreementservicedal") as Iagreementservicedal;

Later, a formal BLL method is implemented to obtain data as in the following example.

Public Agreementinfomodel Getagreementinfobyid (Guid ID)

{

String key = String.Concat (agreementservice.agreement_by_id, ID. ToString ());

Return cacheservice.getdata<agreementinfomodel> (

Key

Agreementservice.agreement_by_id_sinc_key,

Timespan.fromseconds (Agreementservice.agreement_by_id_cache_interval),

Delegate

{

Agreementinfomodel agreement = null;

using (Session sessions = base. Opensession ())

{

agreement = dal. Getagreementinfobyid (session. Current, id);

if (agreement!= NULL)

{

Agreement. Currentamount =

Dal. Getagreementtransferamountbyagreementid (

Session. Current, agreement. Id, Datetime.today);

}

}

return agreement;

}

);

}

A formal BLL method implements an operational activity like the following example:

Publicvoid Deleteagreementinfobyid (Agreementtoinfomodel agreementto)

{

using (Session sessions = base. Opensession ())

using (Transaction tx = Session. BeginTransaction ())

{

if (agreement. imageID!= Guid.Empty)

{

ServiceFacade.ImageService.DeleteImageInfoById (agreement. imageID);

}

Dal. Deleteagreementinfobyid (session. Current, agreement. ID);

Tx.commit ();

}

}

The use of the GUI in the following layers

This is a service that gathers all the BLL to serve a point, and this service makes it very easy to invoke methods from the GUI below.

Protectedvoid Btnsave_click (object sender, EventArgs e)

{

if (Page.IsValid)

{

Branchinfomodel item = This.pc.GetObject () as Branchinfomodel;

ServiceFacade.BranchService.SaveBranch (item);

This. Showlistpage ();

}

}

Publicoverrideobject GetObject ()

{

Branchinfomodel item = ServiceFacade.BranchService.GetBranchInfoById (this. ITEMID);

if (item = NULL)

{

item = new Branchinfomodel ();

}

Item. Name = This.tbName.Text;

Item. Email = This.etbEmail.Text;

return item;

}

nettiergenerator code Generation program

The above solution framework gives us a perfect code generation environment, a recommended code generator for handling data transfer Objects (DTO) models, DAL (+idal), and BLL layers. And there is a level of middle-level between the underlying database structure and the output code, which allows us to create additional database invocation methods from the middle tier implementation.

This is another important feature of this program, which generates two physical files for each class (one is the generated content, the other is the developer's requirements, and each of these files contains a declaration of the C # partial class entry at each level):

The recommended code generation program addresses the following tasks:

1, it allows to put the generated content into a target namespace;

2, it maps the database table or view into its own intermediate declaration structure;

3, it maps each intermediate layer of XML declaration file into its own application services;

4. Each of the intermediate layers of the XML file contains multiple database tables or view mappings (which allows them to be constrained to a single service);

5. It allows you to easily map rows of database tables to enumerators of C #;

6. It allows the declaration of additional methods to interact with the underlying database;

7, it allows code generation operations at each layer, so that we can easily use to define the code to rewrite the generated content;

8, for each of the underlying database created by the XML declaration has a corresponding GUI code;

9, it has a function to obtain the paging data (here I will use one of the methods described in this article): http://www.codeproject.com/KB/aspnet/PagingLarge.aspx

A simple XML declaration will look like the following example:

<tiermodelnamespace= "Economy" servicename= "City" >

<declaretype= "Solution.Common.Economy.BranchConditionEnum"/>

<declaretype= "Solution.Common.Economy.PaymentTypeEnum"/>

<includepath= "Economy\image.xml" type= "Imageinfo"/>

<itemmodeldbtable= "Tbleconomy_city"

Classname= "Cityinfo"

caching= "True" parent= "" >

<Comment/>

<keypropertyneedtogenerate= "true" readonly= "False" >

<Comment/>

<csharpcsharpname= "id" csharptype= "Guid"/>

<dbdbname= "rowguid" dbtype= "uniqueidentifier"

Isnullable= "False" length= "/>"

</KeyProperty>

<propertyreadonly= "False" >

<Comment/>

<csharpcsharpname= "Branchid" csharptype= "Guid"/>

<dbdbname= "Branchid" dbtype= "uniqueidentifier"

Isnullable= "False" length= "/>"

</Property>

<propertyreadonly= "False" >

<Comment/>

<csharpcsharpname= "Name" csharptype= "string" length= "MB"/>

<dbdbname= "Name" dbtype= "nvarchar"

Isnullable= "False" length= "/>"

</Property>

<selectmethodneedtocreate= "true" dalaccess= "true" bllaccess= "true"/>

<insertmethodneedtocreate= "true" dalaccess= "true" bllaccess= "true"/>

<updatemethodneedtocreate= "true" dalaccess= "true" bllaccess= "true"/>

<deletemethodneedtocreate= "true" dalaccess= "true" bllaccess= "False"/>

</ItemModel>

<listitemmodeldbview= "vweconomy_city" classname= "Citylistitem" "parent=" ">

<Comment/>

<KeyProperty>

<Comment/>

<csharpcsharpname= "id"

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.