design patterns best practices for net data components n.
Download
Skip this Video
Loading SlideShow in 5 Seconds..
資料元件設計模式與最佳實務 Design Patterns & Best Practices For .NET Data Components PowerPoint Presentation
Download Presentation
資料元件設計模式與最佳實務 Design Patterns & Best Practices For .NET Data Components

Loading in 2 Seconds...

play fullscreen
1 / 65

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


  • 135 Views
  • Uploaded on

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

loader
I am the owner, or an agent authorized to act on behalf of the owner, of the copyrighted work described.
capcha
Download Presentation

PowerPoint Slideshow about '資料元件設計模式與最佳實務 Design Patterns & Best Practices For .NET Data Components' - eugenia-garrett


An Image/Link below is provided (as is) to download presentation

Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author.While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server.


- - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - -
Presentation Transcript
design patterns best practices for net data components

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

Microsoft .NET 技術代言人

林耀珍 Michael

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

slide2
林耀珍
  • 現職
    • IT 顧問
  • 經歷

第三波資訊 技術總監

育碁數位科技 總經理

第三波資訊 ERP專案經理

  • 專業認證與專長

微軟 .NET 技術 、 軟體開發流程、資訊系統規劃、J2EE

Microsoft MCSD/MCSE/MCDBA

物件導向技術,Rational OOAD 認證講師

Lotus Notes principle CLP/CLI

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

slide3
目標與對象

對象

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

目標

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

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

slide4
大綱

Overview

Process of designing Data Components

Design Data Access Logic Components

Design Business Entity Components

Design Data Transformation Components

Best Practices

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

distributed applications

Business

Entities

Business

Entities

Data

Access Logic

Components

Data

Access Logic

Components

Distributed Applications

Presentation Tier

Presentation Tier

Business Process

Components

Business Process

Components

Doc

Schema

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

net enterprise application architecture

Schema

Users

UI Components

UI Process Components

Service Interfaces

Business Workflows

Business Components

Business Entities

Data Access Components

Service Agents

Data

Sources

Services

.NET Enterprise Application Architecture

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

slide7
大綱

Overview

Process of designing Data Components

Design Data Access Logic Components

Design Business Entity Components

Design Data Transformation Components

Best Practices

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

process of designing data components
Process of designing Data Components
  • Requirements analysis
  • Identifying Business Entities
  • Identifying Business Services
  • Identifying Business Components
  • Identifying Data Components
  • Design Tables & Relationships
  • Recommendations

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

use cases
使用Use cases進行需求分析
  • 以一個網路購物系統為例,Use case diagram描述整體功能
  • actor表示角色-role
  • 根據actor/use cases排出優先順序, 與最小的系統, 例如iteration-1: browse & search, iteration-2: else
  • 使用use case report.doc詳細描述使用者與系統的互動關係
  • 使用architcture.doc描述系統的非功能性需求:平台, 網路, 安全, 效能…

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

business entity
Business Entity

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

identifying business services
Identifying Business Services
  • Identify the required operations
    • Get (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

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

business services
Business Services

Customer System

Order System

Product Catalog System

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

business components
Business Components

Customer

Business Service

Order

Business Service

Product

Business Service

Customer

Business Component

Order

Business Component

Product

Business Component

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

data component types
Data 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

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

business entity implementation options

XML

Business Entity

Component

With

CRUD Behaviors

DataSet

Business Entity

Component

Typed DataSet

Business Entity Implementation Options

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

data components

Customer

Entity

Order

Entity

Product

Entity

Customer

Schema

Order

Schema

Product

Schema

Transformer

Data Components

Presentation Layer

Customer

Business Service

Order

Business Service

Product

Business Service

Customer

Business Component

Order

Business Component

Product

Business Component

Order

Data Access Logic

Component

Product

Data Access Logic

Component

Customer

Data Access Logic

Component

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

rdb tables
RDB Tables

Customer

Data Access Logic

Component

Order

Data Access Logic

Component

Product

Data Access Logic

Component

Customer

Business entity

Order

Business entity

Product

Business entity

Products

Orders

OrderDetails

Customers

Addresses

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

rdb design
RDB Design

1

1

1

*

1

*

*

*

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

design considerations
Design Considerations
  • User 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 requirements
    • Performance / Scalability
    • Productivity / Maintainability

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

slide20
大綱

Overview

Process of designing Data Components

Design Business Entity Components

Design Data Access Logic Components

Design Data Transformation Components

Best Practices

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

designing business entities
Designing Business Entities
  • Business Entity Characteristics
  • Options of Business Entities
    • XML Business Entities
    • DataSet Business Entities
    • Typed DataSet Business Entities
    • Custom Business Entity
    • Custom Business Entities with CRUD - omitted

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

business entity c haracteristics
Business Entity Characteristics
  • Store Data
  • Can be built from data with schemas
    • Data 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

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

xml business entities
XML 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>

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

xml business entities considerations
For

Standards support

Interoperability

Flexibility

Against

Preserving type fidelity

Validation

Displaying

Parsing

Sorting

Private fields

XML Business EntitiesConsiderations

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

xml business entities recommendations
XML Business EntitiesRecommendations
  • 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

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

dataset business entities
DataSet Business Entities

Order DataSet

UniqueConstraint (OrderID)

Orders DataTable

Relation

UniqueConstraint (OrderID, ProductID)

OrderDetails DataTable

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

dataset business entities considerations
For

Flexibility

Serialization

Data binding

Sorting and filtering

Interchangeability with XML

Availability of metadata

Optimistic concurrency

Extensibility

Against

Client code must access data through collections in the DataSet

High instantiation and marshalling costs

No option to hide information

DataSet Business EntitiesConsiderations

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

typed dataset business entities
Typed DataSet Business Entities
  • 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 code

String str = dsProducts.Products[0].ProductName;

v.s.

String str =

dsProducts.Tables[“Products”].Rows[0][“ProductName”];

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

typed dataset business entities considerations
For

Code readability

Easier to use than generic DataSets

Compile type checking

Against

Deployment

Support of Enterprise Services (COM+) callers

Extensibility issues

You cannot instantiate the type by using the new operator

Inheritance

Typed DataSet Business EntitiesConsiderations

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

custom business entity components
Custom Business Entity Components

Custom 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

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

custom business entity components1

Business entity’s state

Custom Business Entity Components

Business Entity Component

Exposes state accessor functions

Public String Name

{

set {myData.Name = value}

}

Caller

Business entity data passed to business process components or DALC

Business Process

Components

Data Access

Logic

Component

Business entity’s state

OrderDALC.CreateOrder(OrderEntity)

OrderBusiness.PlaceOrder(OrderEntity.OrderData)

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

custom business entity components considerations
For

Code readability

Encapsulation

Modeling of complex systems

Localized validation

Private fields

Against

Custom entities represent a single business entity, not a collection of business entities

Requires a custom serialization mechanism

Requires custom mechanisms for representing data relationships and hierarchies

Requires custom mechanisms for searching and sorting of entities

Requires deployment of the assembly containing the custom entity on all physical tiers

Support for Enterprise Services (COM+) clients

Extensibility issues

Custom Business Entity ComponentsConsiderations

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

custom business entity components recommendations
Custom Business Entity ComponentsRecommendations
  • 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

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

slide34
大綱

Overview

Process of designing Data Components

Design Business Entity Components

Design Data Access Logic Components

Design Data Transformation Components

Best Practices

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

designing dalcs
Designing DALCs
  • Communicate with Business Services Components
    • Passing Scalar Values
    • Passing XML
    • Passing DataSets
    • Passing Business Entity Components
    • Returning Data Readers
  • Communicate with RDBMS
    • Using Stored Procedures

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

dalc classes

Data Access Logic

Component

Data Access Logic

Component

Data Access Helper

Component

DALC Classes
  • Design consistent interfaces
    • Pass business entity data into methods in the DALC
    • Return business entity data from methods in the DALC
  • Consider using a data access helper component

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

data access application block
Data Access Application Block

Data Access Application Block

Data Access Component

SqlHelper

Transact-SQL

or

Stored Procedure

ExecuteNonQuery

ExecuteDataset

ExecuteReader

ExecuteScalar

int

ExecuteXmlReader

DataSet

SqlDataReader

SQL Server

SqlHelperParameterCache

object

XmlReader

CacheParameterSet

GetCachedParameterSet

SqlParameter[ ]

GetSpParameterSet

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

apply factory design patterns

Configuration Storage Provider

Storage Service Provider

Storage Service Provider

Data Protection

Provider

Data Protection

Provider

Apply Factory Design patterns
  • Pluggable Handler, Storage/protection provider

Configuration Manager

Caching Service

Your

Application

Application XML Configuration

- XML File

- SQL Server

- Registry

- Custom

- DPAPI

- BCL

- Custom

Configuration Section Handlers

Configuration Section Handlers

Data Protection

Provider

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

using stored procedures
Using Stored Procedures
  • Improved performance
  • Improved security
  • Easier maintenance
  • Reduce network traffic

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

stored procedures considerations
Stored Procedures Considerations

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

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

stored procedure recommendations
Stored Procedure Recommendations
  • 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

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

locking and concurrency
Locking and Concurrency
  • Pessimistic concurrency
  • Optimistic concurrency

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

testing for optimistic concurrency violations
Testing for Optimistic Concurrency 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

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

best practices for designing dalc
Best Practices For Designing 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

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

slide45
大綱

Overview

Process of designing Data Components

Design Data Access Logic Components

Design Business Entity Components

Design Data Transformation Components

Best Practices

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

data transformation components implementation options
Data Transformation ComponentsImplementation Options
  • Custom Data Transformation Utility
  • DataSet and XML
  • XML Schema & XSLT
  • BizTalk Schema Transformation

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

common message bus
Common Message Bus

XML,XSD,XSLT

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

xml serialization

Serialization

Public class Invoice {

// property and

// field definitions

...

}

<>

<>

<>

XML Serialization
  • .NET Framework classes are blueprints for objects
  • XML schemas are blueprints for XML documents

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

xslt in the net framework

<XSLT>

XSLT in the .NET Framework

Transform XML

Data storage

Persist or save

transformed

XML

XslTransform.Transform()

XmlDocument

XmlDataDocument

XPathDocument

XmlReader

XmlWriter

TextWriter

Stream

URL

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

data transformation
Data Transformation
  • Transform data in BizTalk
  • Message based

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

biztalk schema mapper
Using XSLT

Functoids

String

Math

Logical

Database Access

Custom functions by .NET Languages

n-n items mapping

BizTalk Schema Mapper

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

slide52
大綱
  • Overview
  • Process of designing Data Components
  • Design Data Access Logic Components
  • Design Business Entity Components
  • Design Data Transformation Components
  • Best Practices
    • Transaction, Validation, Exception, Security, Connection

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

manual transactions in dalcs
Manual Transactions in DALCs
  • 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

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

automatic transactions in dalcs
Automatic Transactions in DALCs
  • 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

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

general kinds of validation
General Kinds of Validation
  • Point-in-time validation
    • Performed at a specific point in time
    • Example: a business process validates an XML document when the document is received
  • Continuous validation
    • Performed on an ongoing basis at many different levels in your application
    • At UI
    • At Dataset/Business Entity
    • At Business Services Layer
    • At DALC

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

validating xml with schema
Validating XML with Schema

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);

}

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

validating data in property accessors
Validating Data in Property 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...

}

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

data paging
Data Paging
  • Use SqlDataAdapter, not efficient

public int Fill( DataSet ds, int start, int maxRecords, … );

  • Use a server-side cursor
    • Another programming paradigm
  • Manual Implementation with a Unique Key

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

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

security in dalcs
Security 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

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

data connection
Data 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

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

secure communication
Secure 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

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

managing exceptions in dalcs
Managing Exceptions in DALCs
  • Use Exception Management Application Block

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

}

}

}

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

managing exceptions in business entity components
Managing Exceptions in Business 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");

}

...

}

}

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

conclusions

Knowledge

Practice

Ability

Conclusions
  • Data Components acts key roles in
    • Ensuring Performance
    • Facilitate Integration
  • Designing good data components is the most fundamental task in software development.

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

questions

Questions…

Microsoft .NET 技術代言人

林耀珍

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