650 likes | 805 Views
資料元件設計模式與最佳實務 Design Patterns & Best Practices For .NET Data Components. Microsoft .NET 技術代言人 林耀珍 Michael. 林耀珍. 現職 IT 顧問 經歷 第三波資訊 技術總監 育碁數位科技 總經理 第三波資訊 ERP 專案經理 專業認證與專長 微軟 .NET 技術 、 軟體開發流程、資訊系統規劃、 J2EE Microsoft MCSD/MCSE/MCDBA 物件導向技術, Rational OOAD 認證講師
E N D
資料元件設計模式與最佳實務Design Patterns & Best Practices For .NET Data Components Microsoft .NET 技術代言人 林耀珍 Michael .NET技術代言人 林耀珍 2004/06/29
林耀珍 • 現職 • IT 顧問 • 經歷 第三波資訊 技術總監 育碁數位科技 總經理 第三波資訊 ERP專案經理 • 專業認證與專長 微軟 .NET 技術 、 軟體開發流程、資訊系統規劃、J2EE Microsoft MCSD/MCSE/MCDBA 物件導向技術,Rational OOAD 認證講師 Lotus Notes principle CLP/CLI .NET技術代言人 林耀珍 2004/06/29
目標與對象 對象 • 技術平台的決策人員 • 軟體建構師 • 系統分析師 • 專案經理 • 應用程式開發人員 目標 • 介紹資料元件設計模式與最佳實務 .NET技術代言人 林耀珍 2004/06/29
大綱 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
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
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
大綱 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 • 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 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 .NET技術代言人 林耀珍 2004/06/29
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 Customer System Order System Product Catalog System .NET技術代言人 林耀珍 2004/06/29
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 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
XML Business Entity Component With CRUD Behaviors DataSet Business Entity Component Typed DataSet Business Entity Implementation Options .NET技術代言人 林耀珍 2004/06/29
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 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 1 1 1 * 1 * * * .NET技術代言人 林耀珍 2004/06/29
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
大綱 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 • 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 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 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
For Standards support Interoperability Flexibility Against Preserving type fidelity Validation Displaying Parsing Sorting Private fields XML Business EntitiesConsiderations .NET技術代言人 林耀珍 2004/06/29
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 Order DataSet UniqueConstraint (OrderID) Orders DataTable Relation UniqueConstraint (OrderID, ProductID) OrderDetails DataTable .NET技術代言人 林耀珍 2004/06/29
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 • 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
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 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
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
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 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
大綱 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 • 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
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 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
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 • Improved performance • Improved security • Easier maintenance • Reduce network traffic .NET技術代言人 林耀珍 2004/06/29
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 • 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 • Pessimistic concurrency • Optimistic concurrency .NET技術代言人 林耀珍 2004/06/29
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 • 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
大綱 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 ComponentsImplementation Options • Custom Data Transformation Utility • DataSet and XML • XML Schema & XSLT • BizTalk Schema Transformation .NET技術代言人 林耀珍 2004/06/29
Common Message Bus XML,XSD,XSLT .NET技術代言人 林耀珍 2004/06/29
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> 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 • Transform data in BizTalk • Message based .NET技術代言人 林耀珍 2004/06/29