資料元件設計模式與最佳實務 design patterns & best practices for .net data...

65
111/06/14 .NET技技技技技 技技技 2004/06/29 1 資資資資資資資資資資資資資 資資資資資資資資資資資資資 Design Patterns & Best Design Patterns & Best Practices For .NET Data Practices For .NET Data Components Components Microsoft .NET 技技技技 技技技 Michael

Upload: eugenia-garrett

Post on 31-Dec-2015

49 views

Category:

Documents


0 download

DESCRIPTION

資料元件設計模式與最佳實務 Design Patterns & Best Practices For .NET Data Components. Microsoft .NET 技術代言人 林耀珍 Michael. 林耀珍. 現職 IT 顧問 經歷 第三波資訊 技術總監 育碁數位科技 總經理 第三波資訊 ERP 專案經理 專業認證與專長 微軟 .NET 技術 、 軟體開發流程、資訊系統規劃、 J2EE Microsoft MCSD/MCSE/MCDBA 物件導向技術, Rational OOAD 認證講師 - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: 資料元件設計模式與最佳實務 Design Patterns & Best Practices For .NET Data Components

112/04/19 .NET技術代言人 林耀珍 2004/06/29 1

資料元件設計模式與最佳實務資料元件設計模式與最佳實務Design Patterns & Best Design Patterns & Best Practices For .NET Data Practices For .NET Data

ComponentsComponents

Microsoft .NET 技術代言人林耀珍 Michael

Page 2: 資料元件設計模式與最佳實務 Design Patterns & Best Practices For .NET Data Components

112/04/19 .NET技術代言人 林耀珍 2004/06/29 2

林耀珍林耀珍現職

IT 顧問經歷第三波資訊 技術總監育碁數位科技 總經理第三波資訊 ERP 專案經理

專業認證與專長微軟 .NET 技術 、 軟體開發流程、資訊系統規劃、 J2EE

Microsoft MCSD/MCSE/MCDBA

物件導向技術, Rational OOAD 認證講師Lotus Notes principle CLP/CLI

Page 3: 資料元件設計模式與最佳實務 Design Patterns & Best Practices For .NET Data Components

112/04/19 .NET技術代言人 林耀珍 2004/06/29 3

目標與對象目標與對象

對象技術平台的決策人員軟體建構師系統分析師專案經理應用程式開發人員

目標介紹資料元件設計模式與最佳實務

Page 4: 資料元件設計模式與最佳實務 Design Patterns & Best Practices For .NET Data Components

112/04/19 .NET技術代言人 林耀珍 2004/06/29 4

大綱大綱

Overview

Process of designing Data Components

Design Data Access Logic Components

Design Business Entity ComponentsDesign Data Transformation Components

Best Practices

Page 5: 資料元件設計模式與最佳實務 Design Patterns & Best Practices For .NET Data Components

112/04/19 .NET技術代言人 林耀珍 2004/06/29 5

Distributed ApplicationsDistributed Applications

Presentation Tier

Business Process Components

BusinessEntities

Data Access LogicComponents

Presentation Tier

Business Process Components

BusinessEntities

Data Access LogicComponents

Doc

Schema

Page 6: 資料元件設計模式與最佳實務 Design Patterns & Best Practices For .NET Data Components

112/04/19 .NET技術代言人 林耀珍 2004/06/29 6

.NET Enterprise Application .NET Enterprise Application ArchitectureArchitecture

UI Components

UI Process Components

Data Access Components

Business Workflows

Business Components

Users

Business Entities

Service Agents

Service Interfaces

Data Sources

Services

Sch

ema

Page 7: 資料元件設計模式與最佳實務 Design Patterns & Best Practices For .NET Data Components

112/04/19 .NET技術代言人 林耀珍 2004/06/29 7

大綱大綱

Overview

Process of designing Data Components

Design Data Access Logic Components

Design Business Entity ComponentsDesign Data Transformation Components

Best Practices

Page 8: 資料元件設計模式與最佳實務 Design Patterns & Best Practices For .NET Data Components

112/04/19 .NET技術代言人 林耀珍 2004/06/29 8

Process of designing Process of designing Data ComponentsData Components

Requirements analysis

Identifying Business Entities

Identifying Business Services

Identifying Business Components

Identifying Data Components

Design Tables & Relationships

Recommendations

Page 9: 資料元件設計模式與最佳實務 Design Patterns & Best Practices For .NET Data Components

112/04/19 .NET技術代言人 林耀珍 2004/06/29 9

使用使用 Use casesUse cases 進行需求分析進行需求分析

以一個網路購物系統為例,Use case diagram 描述整體功能actor 表示角色 -role

根據 actor/use cases排出優先順序 , 與最小的系統 , 例如 iteration-1: browse & search, iteration-2: else

使用 use case report.doc 詳細描述使用者與系統的互動關係使用 architcture.doc 描述系統的非功能性需求:平台 , 網路 , 安全 , 效能…

Page 10: 資料元件設計模式與最佳實務 Design Patterns & Best Practices For .NET Data Components

112/04/19 .NET技術代言人 林耀珍 2004/06/29 10

Business EntityBusiness Entity

Page 11: 資料元件設計模式與最佳實務 Design Patterns & Best Practices For .NET Data Components

112/04/19 .NET技術代言人 林耀珍 2004/06/29 11

Identifying Business Identifying Business ServicesServices

Identify the required operationsGet (or update) information about a customer, including his or her addresses

Get a list of orders for a customer

Get a list of order items for a particular order

Place a new order

Get (or update) information about a product or a collection of products

Each business entity should have a matching DALC

Page 12: 資料元件設計模式與最佳實務 Design Patterns & Best Practices For .NET Data Components

112/04/19 .NET技術代言人 林耀珍 2004/06/29 12

Business ServicesBusiness Services

Customer System Order System Product Catalog System

Page 13: 資料元件設計模式與最佳實務 Design Patterns & Best Practices For .NET Data Components

112/04/19 .NET技術代言人 林耀珍 2004/06/29 13

Business ComponentsBusiness Components

CustomerBusiness Service

OrderBusiness Service

ProductBusiness Service

CustomerBusiness Component

OrderBusiness Component

ProductBusiness Component

Page 14: 資料元件設計模式與最佳實務 Design Patterns & Best Practices For .NET Data Components

112/04/19 .NET技術代言人 林耀珍 2004/06/29 14

Data Component TypesData Component Types

Data Access Logic Components (DALCs)

Retrieve/Save data from/to the database

Business Rules For processing Data

Business entity components Data is used to represent real world business entities

Format: XML, DataSets, O-O Entity classes

Data Schema

Data Transformation Components

Page 15: 資料元件設計模式與最佳實務 Design Patterns & Best Practices For .NET Data Components

112/04/19 .NET技術代言人 林耀珍 2004/06/29 15

Business Entity Business Entity Implementation OptionsImplementation Options

XML

DataSet

Typed DataSet

Business Entity Component

Business Entity Component

With CRUD Behaviors

Page 16: 資料元件設計模式與最佳實務 Design Patterns & Best Practices For .NET Data Components

112/04/19 .NET技術代言人 林耀珍 2004/06/29 16

Data ComponentsData Components

CustomerData Access Logic

Component

OrderData Access Logic

Component

ProductData Access Logic

Component

CustomerBusiness Component

OrderBusiness Component

ProductBusiness Component

CustomerEntity

OrderEntity

ProductEntity

CustomerSchema

OrderSchema

ProductSchema

Transformer

CustomerBusiness Service

OrderBusiness Service

ProductBusiness Service

Presentation Layer

Page 17: 資料元件設計模式與最佳實務 Design Patterns & Best Practices For .NET Data Components

112/04/19 .NET技術代言人 林耀珍 2004/06/29 17

RDB TablesRDB Tables

CustomerBusiness entity

OrderBusiness entity

ProductBusiness entity

CustomerData Access Logic

Component

OrderData Access Logic

Component

ProductData Access Logic

Component

Customers Addresses Orders OrderDetails Products

Page 18: 資料元件設計模式與最佳實務 Design Patterns & Best Practices For .NET Data Components

112/04/19 .NET技術代言人 林耀珍 2004/06/29 18

RDB DesignRDB Design

Customers CustomerIDCompanyName

Orders OrderIDCustomerIDOrderDateShippedDate

OrderDetails OrderIDProductIDUnitPriceQuantity

Products ProductIDProductNameQuantityPerUnitUnitPriceUnitsInStockUnitsOnOrderReorderLevel

Addresses AddressIDCustomerIDStreetCityPostalCodeCountryPhone

1 1 1 1

*

*

**

Page 19: 資料元件設計模式與最佳實務 Design Patterns & Best Practices For .NET Data Components

112/04/19 .NET技術代言人 林耀珍 2004/06/29 19

Design Design ConsiderationsConsiderationsUser interface controls binding

Collections

Sorting, Searching

Batch update

Access data Locally or remotely

Paging

Transaction

Security

Used by XML Web services or other Apps

Nonfunctional requirementsPerformance / Scalability

Productivity / Maintainability

Page 20: 資料元件設計模式與最佳實務 Design Patterns & Best Practices For .NET Data Components

112/04/19 .NET技術代言人 林耀珍 2004/06/29 20

大綱大綱

Overview

Process of designing Data Components

Design Business Entity Components

Design Data Access Logic ComponentsDesign Data Transformation Components

Best Practices

Page 21: 資料元件設計模式與最佳實務 Design Patterns & Best Practices For .NET Data Components

112/04/19 .NET技術代言人 林耀珍 2004/06/29 21

Designing Designing Business Business EntitiesEntities

Business Entity Characteristics

Options of Business EntitiesXML Business Entities

DataSet Business Entities

Typed DataSet Business Entities

Custom Business Entity

Custom Business Entities with CRUD - omitted

Page 22: 資料元件設計模式與最佳實務 Design Patterns & Best Practices For .NET Data Components

112/04/19 .NET技術代言人 林耀珍 2004/06/29 22

Business EntityBusiness Entity CCharacteristicsharacteristics

Store Data

Can be built from data with schemasData typically originates from multiple related tables in a database

Data can be passed as part of the I/O parameters of business processes

Can be serializable, to persist the current state of the entities

Do not access the database directly

Do not initiate any kind of transaction

Page 23: 資料元件設計模式與最佳實務 Design Patterns & Best Practices For .NET Data Components

112/04/19 .NET技術代言人 林耀珍 2004/06/29 23

XML Business EntitiesXML Business Entities

<?xml version="1.0"?><Product xmlns="urn:aUniqueNamespace"> <ProductID>1</ProductID> <ProductName>Chai</ProductName> <QuantityPerUnit>10 boxes x 20 bags</QuantityPerUnit> <UnitPrice>18.00</UnitPrice> <UnitsInStock>39</UnitsInStock> <UnitsOnOrder>0</UnitsOnOrder> <ReorderLevel>10</ReorderLevel></Product>

<?xml version="1.0"?><Product xmlns="urn:aUniqueNamespace"> <ProductID>1</ProductID> <ProductName>Chai</ProductName> <QuantityPerUnit>10 boxes x 20 bags</QuantityPerUnit> <UnitPrice>18.00</UnitPrice> <UnitsInStock>39</UnitsInStock> <UnitsOnOrder>0</UnitsOnOrder> <ReorderLevel>10</ReorderLevel></Product>

Page 24: 資料元件設計模式與最佳實務 Design Patterns & Best Practices For .NET Data Components

112/04/19 .NET技術代言人 林耀珍 2004/06/29 24

XML Business EntitiesXML Business EntitiesConsiderationsConsiderations

ForStandards support

Interoperability

Flexibility

AgainstPreserving type fidelity

Validation

Displaying

Parsing

Sorting

Private fields

Page 25: 資料元件設計模式與最佳實務 Design Patterns & Best Practices For .NET Data Components

112/04/19 .NET技術代言人 林耀珍 2004/06/29 25

XML Business EntitiesXML Business EntitiesRecommendationsRecommendations

Decide whether the XML document should contain a single business entity or a collection of business entities

Use a namespace to uniquely identify the XML document

Choose appropriate names for elements and attributes

Use one of the following approaches to retrieve your business entities in XML format:

If using SQL Server 2000, use the FOR XML clause in queries or stored procedures

Retrieve a DataSet and transform it or write it out as an XML stream

Build an XML document from output parameters or by using a DataReader

Page 26: 資料元件設計模式與最佳實務 Design Patterns & Best Practices For .NET Data Components

112/04/19 .NET技術代言人 林耀珍 2004/06/29 26

DataSet Business EntitiesDataSet Business Entities

UniqueConstraint (OrderID)UniqueConstraint (OrderID)

UniqueConstraint (OrderID, ProductID)UniqueConstraint (OrderID, ProductID)

Orders DataTable

OrderDetails DataTable

RelationRelation

Order DataSet

Page 27: 資料元件設計模式與最佳實務 Design Patterns & Best Practices For .NET Data Components

112/04/19 .NET技術代言人 林耀珍 2004/06/29 27

DataSet Business EntitiesDataSet Business EntitiesConsiderationsConsiderations

ForFlexibility

Serialization

Data binding

Sorting and filtering

Interchangeability with XML

Availability of metadata

Optimistic concurrency

Extensibility

AgainstClient code must access data through collections in the DataSet

High instantiation and marshalling costs

No option to hide information

Page 28: 資料元件設計模式與最佳實務 Design Patterns & Best Practices For .NET Data Components

112/04/19 .NET技術代言人 林耀珍 2004/06/29 28

Typed DataSet Business Typed DataSet Business EntitiesEntities

Three ways to create a typed DataSet:

From a DataAdapter within Visual Studio .NET

From an XSD schema file within Visual Studio .NET

From the .NET Framework command prompt window by using the XSD Schema Definition Tool (xsd.exe)

Use strong types in your codeString str = dsProducts.Products[0].ProductName;v.s.String str = dsProducts.Tables[“Products”].Rows[0][“ProductName”];

Page 29: 資料元件設計模式與最佳實務 Design Patterns & Best Practices For .NET Data Components

112/04/19 .NET技術代言人 林耀珍 2004/06/29 29

Typed DataSet Business Typed DataSet Business EntitiesEntities ConsiderationsConsiderations

ForCode readability

Easier to use than generic DataSets

Compile type checking

AgainstDeployment

Support of Enterprise Services (COM+) callers

Extensibility issues

You cannot instantiate the type by using the new operator

Inheritance

Page 30: 資料元件設計模式與最佳實務 Design Patterns & Best Practices For .NET Data Components

112/04/19 .NET技術代言人 林耀珍 2004/06/29 30

Custom Business Entity Custom Business Entity ComponentsComponentsCustom business entities have:

Private fields to cache the business entity's data locally

Public properties to access the state of the entity, and to access subcollections and hierarchies of data inside the entity

Methods and properties to perform localized processing by using the data in the entity component

Events to signal changes to the internal state of the entity component

Page 31: 資料元件設計模式與最佳實務 Design Patterns & Best Practices For .NET Data Components

112/04/19 .NET技術代言人 林耀珍 2004/06/29 31

Custom Business Entity Custom Business Entity ComponentsComponents

Data AccessLogic

Component

Business entity’s state

Business Process Components

Business Entity ComponentExposes state accessor functionsPublic String Name{ set {myData.Name = value}}

OrderDALC.CreateOrder(OrderEntity)

Business entity’s state

OrderBusiness.PlaceOrder(OrderEntity.OrderData)

Caller

Business entity data passed to

business process components or

DALC

Page 32: 資料元件設計模式與最佳實務 Design Patterns & Best Practices For .NET Data Components

112/04/19 .NET技術代言人 林耀珍 2004/06/29 32

Custom Business Entity Custom Business Entity ComponentsComponents ConsiderationsConsiderations

ForCode readability

Encapsulation

Modeling of complex systems

Localized validation

Private fields

AgainstCustom entities represent a single business entity, not a collection of business entitiesRequires a custom serialization mechanismRequires custom mechanisms for representing data relationships and hierarchiesRequires custom mechanisms for searching and sorting of entities Requires deployment of the assembly containing the custom entity on all physical tiersSupport for Enterprise Services (COM+) clients Extensibility issues

Page 33: 資料元件設計模式與最佳實務 Design Patterns & Best Practices For .NET Data Components

112/04/19 .NET技術代言人 林耀珍 2004/06/29 33

Custom Business Entity Custom Business Entity ComponentsComponents RecommendationsRecommendations

Define a struct for simple business entities that don’t contain hierarchical data or collections

Define a class for complex business entities (or business entities that require inheritance)

Define fields using .NET data types for simple values such as numbers and strings

Represent subcollections and hierarchies of data as a .NET collection (e.g. ArrayList) or a DataSet

Consider implementing data binding in your custom entity:Windows Forms

Web Forms (may have to implement IBindingList)

Expose events

Make business entities serializable

Page 34: 資料元件設計模式與最佳實務 Design Patterns & Best Practices For .NET Data Components

112/04/19 .NET技術代言人 林耀珍 2004/06/29 34

大綱大綱

Overview

Process of designing Data Components

Design Business Entity Components

Design Data Access Logic ComponentsDesign Data Transformation Components

Best Practices

Page 35: 資料元件設計模式與最佳實務 Design Patterns & Best Practices For .NET Data Components

112/04/19 .NET技術代言人 林耀珍 2004/06/29 35

DesigningDesigning DALCs DALCs

Communicate with Business Services Components

Passing Scalar Values

Passing XML

Passing DataSets

Passing Business Entity Components

Returning Data Readers

Communicate with RDBMSUsing Stored Procedures

Page 36: 資料元件設計模式與最佳實務 Design Patterns & Best Practices For .NET Data Components

112/04/19 .NET技術代言人 林耀珍 2004/06/29 36

DALC ClassesDALC Classes

Design consistent interfacesPass business entity data into methods in the DALC

Return business entity data from methods in the DALC

Consider using a data access helper component Data Access Logic

ComponentData Access Logic

Component

Data Access HelperComponent

Page 37: 資料元件設計模式與最佳實務 Design Patterns & Best Practices For .NET Data Components

112/04/19 .NET技術代言人 林耀珍 2004/06/29 37

Data Access Application Data Access Application BlockBlock

Data Access Application BlockData Access Component

SQL Server

SqlHelper

ExecuteNonQuery

SqlHelperParameterCache

ExecuteDataset

ExecuteReader

ExecuteScalar

ExecuteXmlReader

CacheParameterSet

GetCachedParameterSet

GetSpParameterSet

int

DataSet

SqlDataReader

object

XmlReader

SqlParameter[ ]

Transact-SQLor

Stored Procedure

Page 38: 資料元件設計模式與最佳實務 Design Patterns & Best Practices For .NET Data Components

112/04/19 .NET技術代言人 林耀珍 2004/06/29 38

Apply Factory Design patternsApply Factory Design patterns

YourApplication

YourApplication

Application XML Configuration

- XML File- XML File- SQL Server- SQL Server- Registry- Registry- Custom- Custom

Configuration ManagerConfiguration Manager

Configuration Storage ProviderConfiguration Storage Provider

Data ProtectionProviderData ProtectionProvider - DPAPI

- BCL- Custom

Caching ServiceCaching Service

Configuration Section Handlers

Configuration Section HandlersConfiguration

Section Handlers

Configuration Section

Handlers

Data ProtectionProvider

Data ProtectionProvider

Data ProtectionProvider

Data ProtectionProvider

Storage Service ProviderStorage Service Provider

Storage Service ProviderStorage Service Provider

Pluggable Handler, Storage/protection provider

Page 39: 資料元件設計模式與最佳實務 Design Patterns & Best Practices For .NET Data Components

112/04/19 .NET技術代言人 林耀珍 2004/06/29 39

Using Stored ProceduresUsing Stored Procedures

Improved performance

Improved security

Easier maintenance

Reduce network traffic

Page 40: 資料元件設計模式與最佳實務 Design Patterns & Best Practices For .NET Data Components

112/04/19 .NET技術代言人 林耀珍 2004/06/29 40

Stored Procedures Stored Procedures ConsiderationsConsiderations

Pay Attention to:

Applications with extensive business logic or processing could place excessive loads on the server if implemented entirely in stored procedures

Maintenance becomes an issue when you must modify business logic in stored procedures

Writing and maintaining stored procedures is a specialized skill

Page 41: 資料元件設計模式與最佳實務 Design Patterns & Best Practices For .NET Data Components

112/04/19 .NET技術代言人 林耀珍 2004/06/29 41

Stored Procedure Stored Procedure RecommendationsRecommendations

Only DALCs should be exposed to database schema information, such as stored procedure names, parameters, tables, and fields

Each stored procedure should be called by only one DALC

Stored procedures for DALC use should be named to emphasize the DALC to which they pertain

If you accept user input to perform queries dynamically, do not create a string by concatenating values without using parameters

Avoid string concatenation in stored procedures when using sp_execute, or when not using the sp_executesql parameter support

Page 42: 資料元件設計模式與最佳實務 Design Patterns & Best Practices For .NET Data Components

112/04/19 .NET技術代言人 林耀珍 2004/06/29 42

Locking and ConcurrencyLocking and Concurrency

Pessimistic concurrency

Optimistic concurrency

Page 43: 資料元件設計模式與最佳實務 Design Patterns & Best Practices For .NET Data Components

112/04/19 .NET技術代言人 林耀珍 2004/06/29 43

Testing for Optimistic Testing for Optimistic Concurrency ViolationsConcurrency Violations

Use distributed time stamps/version column

Maintain a copy of original data values in the client

DataSets supports

Use centralized time stamps Define a centralized time stamp table to log all updates to any row in any table

Is appropriate in checkout scenarios and in some disconnected client scenarios

Facilitate auditing

Page 44: 資料元件設計模式與最佳實務 Design Patterns & Best Practices For .NET Data Components

112/04/19 .NET技術代言人 林耀珍 2004/06/29 44

Best Practices For Best Practices For Designing DALCDesigning DALC

Return only the data you need

Use (but don’t overuse) stored procedures

Rely on the RDBMS for data-intensive work(Batch Processing)

Implement a standard set of stored procedures for CRUD operations

Expose common DALC functionality in a separate interface or base class

Design consistent interfaces for different clients

Expose metadata

Don’t build one component per table

DALCs should not decrypt encrypted data

When using Enterprise Services, place DALCs in a library application

Enable transactions only when you need them

Consider tuning isolation levels

Use data access helper components for conversion

Page 45: 資料元件設計模式與最佳實務 Design Patterns & Best Practices For .NET Data Components

112/04/19 .NET技術代言人 林耀珍 2004/06/29 45

大綱大綱

Overview

Process of designing Data Components

Design Data Access Logic Components

Design Business Entity Components

Design Data Transformation Components

Best Practices

Page 46: 資料元件設計模式與最佳實務 Design Patterns & Best Practices For .NET Data Components

112/04/19 .NET技術代言人 林耀珍 2004/06/29 46

Data Transformation Data Transformation ComponentsComponents Implementation OptionsImplementation Options

Custom Data Transformation Utility

DataSet and XML

XML Schema & XSLT

BizTalk Schema Transformation

Page 47: 資料元件設計模式與最佳實務 Design Patterns & Best Practices For .NET Data Components

112/04/19 .NET技術代言人 林耀珍 2004/06/29 47

Common Message BusCommon Message Bus

XML , XSD , XSLT

Page 48: 資料元件設計模式與最佳實務 Design Patterns & Best Practices For .NET Data Components

112/04/19 .NET技術代言人 林耀珍 2004/06/29 48

.NET Framework classes are blueprints for objects

XML schemas are blueprints for XML documents

XML SerializationXML Serialization

<>

<>

<>

Public class Invoice { // property and // field definitions ...}

SerializationSerialization

Page 49: 資料元件設計模式與最佳實務 Design Patterns & Best Practices For .NET Data Components

112/04/19 .NET技術代言人 林耀珍 2004/06/29 49

XSLT in the .NET XSLT in the .NET FrameworkFramework

XmlDocumentXmlDataDocument

XPathDocument

XmlReaderXmlWriterTextWriter

StreamURL

Data storageData storage Transform XML Transform XML Persist or save transformed

XML

Persist or save transformed

XML

XslTransform.Transform()

<XSLT>

Page 50: 資料元件設計模式與最佳實務 Design Patterns & Best Practices For .NET Data Components

112/04/19 .NET技術代言人 林耀珍 2004/06/29 50

Data TransformationData TransformationTransform data in BizTalk

Message based

Page 51: 資料元件設計模式與最佳實務 Design Patterns & Best Practices For .NET Data Components

112/04/19 .NET技術代言人 林耀珍 2004/06/29 51

BizTalk Schema MapperBizTalk Schema Mapper

Using XSLT

FunctoidsString

Math

Logical

Database Access

Custom functions by .NET Languages

n-n items mapping

Page 52: 資料元件設計模式與最佳實務 Design Patterns & Best Practices For .NET Data Components

112/04/19 .NET技術代言人 林耀珍 2004/06/29 52

大綱大綱

Overview

Process of designing Data Components

Design Data Access Logic Components

Design Business Entity Components

Design Data Transformation Components

Best PracticesTransaction, Validation, Exception, Security, Connection

Page 53: 資料元件設計模式與最佳實務 Design Patterns & Best Practices For .NET Data Components

112/04/19 .NET技術代言人 林耀珍 2004/06/29 53

Manual Manual Transactions in Transactions in DALCsDALCs

Where possible, perform processing in stored procedures

Control transactions programmatically by using ADO.NET if you are not using stored procedures, and DALCs are not called from a business process

Page 54: 資料元件設計模式與最佳實務 Design Patterns & Best Practices For .NET Data Components

112/04/19 .NET技術代言人 林耀珍 2004/06/29 54

Automatic Automatic Transactions in Transactions in DALCsDALCs

DALCs must inherit from the ServicedComponent class in the System.EnterpriseServices namespace

Annotate DALCs with the Transaction(TransactionOption.Supported) attribute so you can perform read and write operations in the same component

Page 55: 資料元件設計模式與最佳實務 Design Patterns & Best Practices For .NET Data Components

112/04/19 .NET技術代言人 林耀珍 2004/06/29 55

General Kinds of General Kinds of ValidationValidation

Point-in-time validationPerformed at a specific point in time

Example: a business process validates an XML document when the document is received

Continuous validationPerformed on an ongoing basis at many different levels in your application

At UI

At Dataset/Business Entity

At Business Services Layer

At DALC

Page 56: 資料元件設計模式與最佳實務 Design Patterns & Best Practices For .NET Data Components

112/04/19 .NET技術代言人 林耀珍 2004/06/29 56

Validating XML with Validating XML with SchemaSchemapublic void ReadData() { XmlTextReader tr = new XmlTextReader("Product.xml"); XmlValidatingReader vr = new XmlValidatingReader(tr); vr.ValidationType = ValidationType.Schema; vr.ValidationEventHandler += new ValidationEventHandler(MyHandlerMethod); try { while (vr.Read()) // Process the XML data, as appropriate ... } catch (XmlException ex) { Console.WriteLine("XmlException: " + ex.Message); } vr.Close();}

public void MyHandlerMethod(object sender, ValidationEventArgs e) { Console.WriteLine("Validation Error: " + e.Message);}

public void ReadData() { XmlTextReader tr = new XmlTextReader("Product.xml"); XmlValidatingReader vr = new XmlValidatingReader(tr); vr.ValidationType = ValidationType.Schema; vr.ValidationEventHandler += new ValidationEventHandler(MyHandlerMethod); try { while (vr.Read()) // Process the XML data, as appropriate ... } catch (XmlException ex) { Console.WriteLine("XmlException: " + ex.Message); } vr.Close();}

public void MyHandlerMethod(object sender, ValidationEventArgs e) { Console.WriteLine("Validation Error: " + e.Message);}

Page 57: 資料元件設計模式與最佳實務 Design Patterns & Best Practices For .NET Data Components

112/04/19 .NET技術代言人 林耀珍 2004/06/29 57

Validating Data in Validating Data in Property AccessorsProperty Accessors

public class ProductDALC{ … public short ReorderLevel { get { return reorderLevel; } } set { if (value < 0) { throw new ArgumentOutOfRangeException("invalid ReorderLevel"); } reorderLevel = value; }

// Plus other members in the ProductDALC class...}

public class ProductDALC{ … public short ReorderLevel { get { return reorderLevel; } } set { if (value < 0) { throw new ArgumentOutOfRangeException("invalid ReorderLevel"); } reorderLevel = value; }

// Plus other members in the ProductDALC class...}

Page 58: 資料元件設計模式與最佳實務 Design Patterns & Best Practices For .NET Data Components

112/04/19 .NET技術代言人 林耀珍 2004/06/29 58

Data PagingData Paging

Use SqlDataAdapter, not efficientpublic int Fill( DataSet ds, int start, int

maxRecords, … );

Use a server-side cursorAnother programming paradigm

Manual Implementation with a Unique KeyCREATE PROCEDURE GetProductsPaged @lastProductID int, @pageSize int

AS SET ROWCOUNT @pageSize SELECT * FROM Products WHERE [standard search criteria] AND ProductID > @lastProductID ORDER BY [Criteria that leaves ProductID monotonically increasing] GO

CREATE PROCEDURE GetProductsPaged @lastProductID int, @pageSize int AS SET ROWCOUNT @pageSize SELECT * FROM Products WHERE [standard search criteria] AND ProductID > @lastProductID ORDER BY [Criteria that leaves ProductID monotonically increasing] GO

Page 59: 資料元件設計模式與最佳實務 Design Patterns & Best Practices For .NET Data Components

112/04/19 .NET技術代言人 林耀珍 2004/06/29 59

Security in DALCsSecurity in DALCs

Perform authorization checks at DALC level if you need to:

Share DALCs with developers of business processes you do not fully trust

Protect access to powerful functions exposed by the data stores

perform role-based security checks in one of three ways using identity and principal :

Imperatively using a PrincipalPermission object

Declaratively using the PrincipalPermissionAttribute attribute

Explicitly using the IsInRole method in the Principal object

Page 60: 資料元件設計模式與最佳實務 Design Patterns & Best Practices For .NET Data Components

112/04/19 .NET技術代言人 林耀珍 2004/06/29 60

Data ConnectionData Connection

Use Connection pool"Server=(local); Integrated Security=SSPI; Database=Northwind; Max Pool Size=75; Min Pool Size=5"

Use Windows Authentication to connect to SQL Server

Do not use SQL Server logins

Avoid impersonation in the middle tier

Store connection strings securely

Open database connections late, close them early

Page 61: 資料元件設計模式與最佳實務 Design Patterns & Best Practices For .NET Data Components

112/04/19 .NET技術代言人 林耀珍 2004/06/29 61

Secure CommunicationSecure Communication

Use the following secure communication technologies:

Distributed Component Object Model (DCOM)

Secure Sockets Layer (SSL)

Secure Internet Protocol (IPSec)

Encrypted data stored within a database is usually decrypted and encrypted using a DALC

Business entity components should not deal with communication security or data encryption

If the risk of exposing the information is high, consider securing the communication channel to and from the DALCs

Page 62: 資料元件設計模式與最佳實務 Design Patterns & Best Practices For .NET Data Components

112/04/19 .NET技術代言人 林耀珍 2004/06/29 62

Managing Exceptions in Managing Exceptions in DALCsDALCs

public class CustomerDALC{ public void UpdateCustomer(Dataset aCustomer) { try { // Update the customer in the database... } catch (SqlException se) { // Catch the exception and wrap, and rethrow throw new DataAccessException("Database is unavailable", se); } finally { // Cleanup code } }}

public class CustomerDALC{ public void UpdateCustomer(Dataset aCustomer) { try { // Update the customer in the database... } catch (SqlException se) { // Catch the exception and wrap, and rethrow throw new DataAccessException("Database is unavailable", se); } finally { // Cleanup code } }}

Use Exception Management Application Block

Page 63: 資料元件設計模式與最佳實務 Design Patterns & Best Practices For .NET Data Components

112/04/19 .NET技術代言人 林耀珍 2004/06/29 63

Managing Exceptions in Managing Exceptions in Business Entity ComponentsBusiness Entity Components

public class CustomerEntity{ public void Update() { // Check that the user has provided the required data. In this // case a first name for the customer if (FirstName == "") { // Throw a new application exception that you have defined throw new MyArgumentException ("Missing First Name"); } ... }}

public class CustomerEntity{ public void Update() { // Check that the user has provided the required data. In this // case a first name for the customer if (FirstName == "") { // Throw a new application exception that you have defined throw new MyArgumentException ("Missing First Name"); } ... }}

Page 64: 資料元件設計模式與最佳實務 Design Patterns & Best Practices For .NET Data Components

112/04/19 .NET技術代言人 林耀珍 2004/06/29 64

ConclusionsConclusions

Data Components acts key roles inEnsuring Performance

Facilitate Integration

Designing good data components is the most fundamental task in software development.

Knowledge

PracticeAbility

Page 65: 資料元件設計模式與最佳實務 Design Patterns & Best Practices For .NET Data Components

112/04/19 .NET技術代言人 林耀珍 2004/06/29 65

Questions…Questions…

Microsoft .NET 技術代言人林耀珍