Designing Data Tier Components and Passing Data THROUGH TIERS
Related Links
Patterns and Practices INDEX
.NET Architecture Center
Application Architecture for .NET: Designing Applications and Services
Angela Crocker, Andy Olsen, And Edward JezierskiMicrosoft Corporation
August 2002
Applies TO: Microsoft® .NET Applications
Summary: Learn How To Best Expose Your Data To Microsoft .NET Applications and How To Implement An Effective Strategy for Passing Data Between The Tiers in a Distributed Application. (65 Printed Pages)
Download
Download Designing Data Tier Components and Passing Data THROUGH TIERS IN .PDF FORMAT.
Contents
Introduction Mapping Relational Data to Business Entities Implementing Data Access Logic Components Implementing Business Entities Transactions Validations Exception Management Authorization and Security Deployment Appendix Collaborators
Introduction
When designing a distributed application, you need to decide how to access and represent the business data associated with your application. This document provides guidance to help you choose the most appropriate way of exposing, persisting and passing that data through the tiers of an application.
. Figure 1 depicts the common tiers of a distributed application This document distinguishes between business data and the business processes that use the data;. The business process tier is discussed only where needed for clarification Likewise, the presentation tier is discussed only where there are direct implications for the way data is represented, such as the way Microsoft® ASP.NET Web pages expose business data Figure 1 introduces two new terms:. data access logic components and business entity components These terms are described later in this document.Figure 1. Accessing and representing data in a distributed application
Most applications store data in relational databases. While there are other options for storing data, this document focuses on how .NET applications interact with relational databases, and does not specifically discuss how to interact with data held in other data stores such as flat files or Non-rate databases.
THIS Document Makes a Clear Distinction Between Persistence Logic and The Data Itself. The Reasons for Separating Persistence Logic from The Data INCLUDE The FOLLOWING:
· Separate Data Persistence Components Can Isolate The Application from Database Dependencies, Such as The Name of The Data Source, Connection Information and Field Names.
· Many of today's applications use loosely coupled, message-based technologies, such as XML Web services and Microsoft Message Queuing (also known as MSMQ). These applications typically communicate by passing business documents, rather than by passing objects.
Note For an introduction to XML Web services, see the article titled .NET Web Services:. Web Methods Make it Easy to Publish Your App's Interface over the Internet in the March 2002 issue of MSDN® Magazine For more information about Message Queuing, see Message Queuing overview.to attain the distinction between Persistence Logic and The Data Itself, this document proposes two.
· Data access logic components. Data access logic components retrieve data from the database and save entity data back to the database. Data access logic components also contain any business logic needed to achieve data-related operations.
· Business entity components. Data is used to represent real world business entities, such as products or orders. There are numerous ways to represent these business entities in your application-for example, XML or DataSets or custom object-oriented classes-depending on the .................................. ...CRIPLILE, Hotel.
Data Access Logic Components
A Data Access Logic Component Provides Methods To Perform The Following Tasks Upon A Database, on Behalf of The Caller:
Create Records in the database
Read Records in The Database, And Return Business Entity Data To The Caller
· Update Records in The Database, by using revised business entity data sales by the caller
· Delete Records in The Database
The Methods That Perform The Preceding Tasks Are Off "CRUD" Methods, Where Crud Is An Acronym Based on The First Letter of Each Task.
The Data Access Logic Component also has methods to implement business logic against the database. For example, a Data Access Logic Component might have a method to find the highest-selling product in a catalog for this month.Typically, a Data Access Logic Component accesses a single database and encapsulates the data-related operations for a single table or a group of related tables in the database. for example, you might define one Data Access Logic Component to deal with the Customer and Address tables in a database, and another Data Access Logic Component to DEAL with TABLES. The Design Decisions for Mapping Data Access Logic Components To Database Tables Are Discussed Later in this document.
Representing business enttive
.. Each Data Access Logic Component deals with a specific type of business entity For example, the Customer Data Access Logic Component deals with Customer business entities There are many different ways to represent business entities, depending on factors such as the following:
· Do You NEED TO BIND Business Entity Data TO Controls IN A Microsoft Windows® Form OR on an ASP.NET PAGE?
· Do you need to perform in the business entity data?
· Does your application deal with business entities One at a time, or does it Typically DEAL with sets of business entities?
· WILL you deploy your application locally or remotely?
· WILL THE Business Entity Be buy by XML Web Services?
· How Important Are Nonfunctional Requirements, Such As Performance, Scalability, Maintainability, and Programming Convenience?
This document outlines the advantages and disadvantages of the following implementation options:. · XML You use an XML string or an XML Document Object Model (DOM) object to represent business entity data XML is an open and flexible data representation format that can be used. To Integrate Diverse Types of Applications.
· DataSet. A DataSet is an in-memory cache of tables, obtained from a relational database or an XML document. A Data Access Logic Component can use a DataSet to represent business entity data retrieved from the database, and you can use the DataSet in Your application. for an introduction to datasets, see "Introducing ADO.NET" in The .NET Data Access Architecture Guide.
· Typed DataSet. A type inherits from the ado.net DataSet Class from the ADO.NET DATASET Class and Properties To Access The Tables and Column in a DataSet.
· Business Entity Component. This is a custom class to represent each type of business entity. You define fields to hold the business entity data, and you define properties to expose this data to the client application. You define methods to encapsulate simple business logic, making use of the fields defined in the class This option does not implement CRUD methods as pass-through methods to the underlying Data Access Logic Component;. the client application communicates directly with the Data Access Logic Component to perform CRUD operations.
· Business Entity Component with CRUD behaviors. You define a custom entity class as described previously, and you implement the CRUD methods that call the underlying Data Access Logic Component associated with this business entity.Note If you prefer to work with your data in a more object-oriented fashion, you can use the alternate approach of defining an object persistence layer based on the reflection capabilities of the common language runtime. you can create a framework that uses reflection to read the properties of the objects and use a mapping file to describe the mapping between objects and tables. However, to implement this effectively would constitute a major investment in infrastructure code. This outlay might be viable for ISVs and solution providers, but not for the majority of organizations, and it is beyond the scope of this document .
Technical considitys
Figure 2 shows some of the technical considerations that influence the implementation strategy for data access logic components and business entities. This document addresses each of these technical considerations and provides recommendations.
Figure 2. Technical Considerations That Influnce The Design of Data Access Logic Components and Business Entities
Mapping Relational Data to Business Entities
Databases typically contain many tables, with relationships implemented by primary keys and foreign keys in these tables. When you define business entities to represent this data in your .NET application, you must decide how to map these tables to business entities.
Consider The Hypothetical Retailer's Database Shown in Figure 3.
Figure 3. Hypothetical Table Relationships IN A RELATIONAL DATABASE
The Following Table Summarizes The Types of Relationships in The Example Database.type of RelationShip
EXAMPLE
Description
One-to-Many
Customer: AddressCustomer: Order
.
MANY-TO-MANY
ORDER: PRODUCT
An ORDER CAN COMPRESE MANY PRODUCTS; Each Product Is Represented by a Separate Row in The OrderDetails Table. LikeWise, a Product Can Be Featured In Many ORDERS.
When you define business entities to model the information in the database, consider how you will use the information in your application. Identify the core business entities that encapsulate your application's functionality, rather than defining a separate business entity for each table.
Typical Operations in The Hypothetical Retailer's Application Area Follows:
· Get (or Update) Information 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 INFORMATION ABOUT A Product OR A Collection of Products
To fulfill these application requirements, there are three logical business entities that the application will handle:. A Customer, an Order and a Product For each business entity, a separate Data Access Logic Component will be defined as follows:
· Customer Data Access Logic Component. This Class Will Provide Services To Retrieve and Modify Data IN The Customer and Address Tables.
· Order Data Access Logic Component. This class will provide services to retrieve and modify data in the Order and OrderDetails tables. · Product Data Access Logic Component. This class will provide services to retrieve and modify data in the Product table.
Figure........................
Figure 4. Defining Data Access Logic Components To Expose RELATIONAL DATA TO .NET Applications
.
Recommendations for Mapping Relational Data To Business Entities
To Map Relational Data To Business Entities, Consider The Following Recommendations:
· Take the time to analyze and model the logical business entities of your application, rather than defining a separate business entity for every table. One of the ways to model how your application works is to use Unified Modeling Language (UML). UML is a formal design notation for modeling objects in an object-oriented application, and for capturing information about how objects represent automated processes, human interactions, and associations. for more information, see Modeling Your Application and Data.
· Do not define separate business entities to represent many-to-many tables in the database; these relationships can be exposed through methods implemented in your Data Access Logic Component For example, the OrderDetails table in the preceding example is not mapped to a separate. business entity;. instead, the Orders data access logic component encapsulates the OrderDetails table to achieve the many-to-many relationship between the Order and Product tables · If you have methods that return a particular type of business entity, place these methods in the Data Access Logic Component for that type. for example, if you are retrieving all orders for a customer, implement that function in the Order Data Access Logic Component because your return value is of the type Order. Conversely, if you are retrieving all customers that Have Ordered A Specific Product, Implement That Function In The Customer Data Access Logic Component.
· Data access logic components typically access data from a single data source. If aggregation from multiple data sources is required, it is recommended to define a separate Data Access Logic Component to access each data source that can be called from a higher-level business process Component That Can Perform The AGGREGATION. There Are Two Reasons for this Recommendation:
· Transaction management is centralized to the business process component and does not need to be controlled explicitly by the Data Access Logic Component. If you access multiple data sources from one Data Access Logic Component, you will need the Data Access Logic Component to be the root of transactions, which will introduce additional overhead on functions where you are only reading data. · Aggregation is usually not a requirement in all areas of the application, and by separating the access to the data, you can let the type stand alone as well as BE Part of an AGGREGATION WHEN NEEDED.
Implementing Data Access Logic Components
A Data Access Logic Component is a stateless class, meaning that all messages exchanged can be interpreted independently. No state is held between calls. The Data Access Logic Component provides methods for accessing one or more related tables in a single database, or in some instances .
One of the key goals of data access logic components is to hide the invocation and format idiosyncrasies of the database from the calling application. Data access logic components provide an encapsulated data-access service to these applications. Specifically, data access logic components handle the following Implementation Details:
· Manage and encapsulate Locking Schemes
· Handle Security and Authorization Issues Appropriately
· Handle Transaction Issues ApproPriaTely
Perform Data Paging · Perform Data-Dependent Routing If Required
· Implement a Caching Strategy IF Appropriate, for Queries of Nontransactional Data
Perform Data streaming and data serialization
Some of these Issues Are Explored in More Detail Later in this section.
Application Scenarios for Data Access Logic Components
Figure 5 shows how a Data Access Logic Component can be called from a variety of application types, including Windows Forms applications, ASP.NET applications, XML Web services and business processes. These calls might be local or remote, depending on how you deploy your Applications.
Figure 5. Application Scenarios for Data Access Logic Components (Click thumbnail for larger image)
Implementing Data Access Logic Component Classes
Data access logic components use ADO.NET to execute SQL statements or call stored procedures. For an example of a Data Access Logic Component class, see How to Define a Data Access Logic Component Class in the appendix.
If your application contains multiple data access logic components, you can simplify the implementation of Data Access Logic Component classes by using a data access helper component. This component can help manage database connections, execute SQL commands and cache parameters. The data access logic components still encapsulate the logic required to access the specific business data, whereas the data access helper component centralizes data access API development and data connection configuration, thereby helping to reduce code duplication. Microsoft provides the Data Access Application Block for .NET, which can be used as a generic data access helper component in your applications when you use Microsoft SQL Server ™ databases. Figure 6 shows how to use the data access helper component to help implement data access logic components.Figure 6. Implementing data access logic components by using the data access Helper Component
IF The are Utility Functions That Are Common To All of Your Data Access Logic Components, You Can Define A Base Class for Data Access Logic Components To inherit from And Extend.
Design your Data Access Logic Component classes to provide a consistent interface for different types of clients. If you design the Data Access Logic Component to be compatible with the requirements of your current and potential business process tier implementation, you can reduce the number of additional interfaces , Facades or mapping layers that you must us.
To Support A DiversE Range of Business Processes and Applications, Consider The Following Techniques To Pass Data To and from Data Access Logic Component Methods:
. · Passing business entity data into methods in the Data Access Logic Component You can pass the data in several different formats: as a series of scalar values, as an XML string, as a DataSet or as a custom Business Entity Component · Returning business. . entity data from methods in the Data Access Logic Component You can return the data in several different formats: as output-parameter scalar values, as an XML string, as a DataSet, as a custom Business Entity Component or as a data reader.
The following sections present the options for passing business entity data to and from your data access logic components, in addition to the advantages and disadvantages of each approach. This information will help you to make an informed choice based on your specific application scenario.
Passing Scalar Values As Inputs and Outputs
The Advantages of this Option Are as Follows:
Abstract. Callers Must Know About Only The Data That Defines The Business Entity, But Not a Specific Type or The Specific Structure of The Business Entity.
· Serialization. Scalar Values Native Support Serialization.
.
.................... ..
The Disadvantages of this Option Are as Follows:
· Tight Coupling and Maintenance. Schema Changes COULD Require Method Signatures To Be Modified, Which Will Affect The Calling Code.
· Collections of entities. To save or update multiple entities to a Data Access Logic Component, you must make separate method calls. This can be a significant performance hit in distributed environments. · Support of optimistic concurrency. To support optimistic concurrency, time stamp columns Must be defluded as part of the data.
Passing XML strings as inputs and outputs
The Advantages of this Option Are as Follows:
Loose Coupling. Callers Must Know About Only The Data That Defines The Business Entity and The Schema That Provides Metadata for the Business Entity.
INTEGRATION. Accepting XML Will Support Callers IMPLEMENTED IN VARIOS WAYS-for Example, .NET Applications, BizTalk Orchestration Rules, And Third-Party Business Rules Engines.
.
· Serialization. Strings Natively Support Serialization.
The Disadvantages of this Option Are as Follows:
· The XML String Must Be repared at the receiving end. Very Large XML Strings IncUR a Performance Overhead.
.
• Supporting Optimistic Concurrency, Time Stamp Columns Must Be Defined in The Database and Included As Part of The XML Data.
Passing DataSets as INPUTS AND OUTPUTS
The Advantages of this Option Are as Follows:
· Native functionality. DataSets provide built-in functionality to handle optimistic concurrency (along with data adapters) and support for complex data structures. Furthermore, typed DataSets provide support for data validation. · Collections of business entities. DataSets are designed to handle sets and Complex RELATIONSHIPS, SO You do Not Need To Write Custom Code To Implement this functionality.
· Maintenance. Schema changes do not affect the method signatures. However, if you are using typed DataSets and the assembly has a strong name, the Data Access Logic Component class must be recompiled against the new version, must use a publisher policy inside the global Assembly Cache, Or Must Define A
· Serialization. A Dataset Supports XML Serialization Native and Can Be Serialized Across Tiers.
The Disadvantages of this Option Are as Follows:
...................
· Representation of a single business entity. DataSets are designed to handle sets of data. If your application works mainly with instance data, scalar values or custom entities are a better approach as you will not incur the performance overhead.
Passing Custom Business Entity Components As Inputs and Outputs
The Advantages of this Option Are as Follows:
· Maintenance. Schema changes may not affect the Data Access Logic Component method signatures. However, the same issues arise as with typed DataSets if the Business Entity Component is held in a strong-named assembly. · Collections of business entities. An array or a COLLECTION OF Custom Business Entity Components Can Be Passed to and from The Methods.
The Disadvantages of this Option Are as Follows:
· Supporting Optimistic Concurrency. To Support Optimistic Concurrency Easily, Time Stamp Columns Must Be defined in The Database and Included As Part of The Instance Data.
. · Limited integration When using custom business entity components as inputs to the Data Access Logic Component, the caller must know the type of business entity; this can limit integration for callers that are not using .NET However, this issue does not necessarily limit. integration if the caller uses custom business entity components as output from the Data Access Logic Component. For example, a Web method can return the custom Business Entity Component that was returned from a Data Access Logic Component, and the Business Entity Component will be serialized to XML Automatically Using XML Serialization.
Returning Data Readers as outputs
The Advantage Of this option is as follows:
................ ..
The disadvantage of this option is as enough
· Remoting. It is inadvisable to use data readers in remoting scenarios, because of the potential for client applications to hold the database connection open for lengthy periods.Using Stored Procedures in Conjunction with Data Access Logic Components
You can use stored procedures to Perform Many of The Data Access Tasks Supported by Data Access Logic Components.
Advantages
· Stored Procedures Generally Result In Improved Performance, Because The Database CAN Optimize The Data Access Plan Used by The Procedure and Cache The Plan for Subsequent Reuse.
· Stored Procedures Can Be Individally. An Administrator CAN Grant Clients Permission To Execute A Stored Procedure, WITHOUT GRANTING TABLES.
· Stored procedures may result in easier maintenance, because it is generally easier to modify a stored procedure than to change a hard-coded SQL statement within a deployed component. However, the benefit decreases as the business logic implemented in the stored procedures increases.
· Stored procedures add an extra level of abstraction from the underlying database schema. The client of the stored procedure is isolated from the implementation details of the stored procedure and from the underlying schema.
· Stored Procedures Can Reduce Network Traffic. SQL Statements CAN Be Executed In Batches, Rather Than The Application Having to Send Multiple SQL Requests.
Despite The Advantages Listed Above, There Area Some Situations Where The Use of Stored Procedures Is Not Recommended or May Be Infeasible.
Disadvantages
· Applications that involve extensive business logic and processing could place an excessive load on the server if the logic was implemented entirely in stored procedures. Examples of this type of processing include data transfers, data traversals, data transformations and intensive computational operations. You should move this type of processing to business process or data access logic components, which are a more scalable resource than your database server. · Do not put all of your business logic into stored procedures. Maintenance and the agility of your application becomes an issue when you must .
· Writing and maintaining Stored Procedures IS MOSTEN A Specialized Skill Set That Not All Developers Possess. This Situation May Introduce Bottlenecks in The Project Development Schedule.
Recommendations for Using Stored Procedures with Data Access Logic Components
Consider The Following Recommendations for Using Stored Procedures in Conjunction with Data Access Logic Components:
· Exposing stored procedures. Data access logic components should be the only components that are exposed to database schema information, such as stored procedure names, parameters, tables, and fields. Your business entity implementation should have no knowledge of or dependency on database schemas.
· Associating stored procedures with data access logic components. Each stored procedure should be called by only one Data Access Logic Component, and should be associated with the Data Access Logic Component that owns the action. For example, imagine that a customer places an order with a retailer. you can write a stored procedure named OrderInsert, which creates the order in the database. in your application, you must decide whether to call the stored procedure from the Customer Data Access Logic Component or from the Order Data Access Logic Component. The Order Data Access Logic Component is a better choice because it handles all order-related processing (the Customer Data Access Logic Component handles customer information, such as the customer's name and address). · Naming stored procedures. When you define stored procedures for a Data Access Logic Component To Use, Choose Stored Procedure Names That Emphasize The Data Access Logic Component to which they pertain. This naming convention helps to easily identify which components call which stored procedures, and provides a way to logically group the stored procedures inside SQL Enterprise Manager. For example, you can proactively write stored procedures named CustomerInsert, CustomerUpdate, CustomerGetByCustomerID, And CustomerDelete for use by the customer data access logic component, and the provide More specific Stored Procedures-Such As CustomergetAllinRegion-to Support The Business Functions of Your Application.
Note Do not preface your stored procedure names with sp_, because doing so reduces performance. When you call a stored procedure that starts with sp_, SQL Server always checks the master database first, even if the stored procedure is qualified with the database name. · Addressing security issues. If you accept user input to perform queries dynamically, do not create a string by concatenating values without using parameters. Also avoid using string concatenation in stored procedures if you are using sp_execute to execute the resulting string, or if you do not Take Advantage Of SP_EXECUTESQL Parameter Support.
Managing Locking and Concurrency
Some applications take the "Last in Wins" approach when comes to updating data in a database. With the "Last in Wins" approach, the database is updated, and no effort is made to compare updates against the original record, potentially overwriting any it changes made by other users since the records were last refreshed. However, at times it is important for the application to determine if the data has been changed since it was initially read, before performing the update.
Data Access Logic Components Implement The Code To Manage Locking and Conturrence. There Are Two Ways to Manage Locking and Concurrency:
Perssimistic Concurrency. A User Who Reads a Row with the INTEN Updating It Establishes a Lock on The Row in The Data Source. No One else can change The row. No. No.
· Optimistic concurrency. A user does not lock a row when reading it. Other users are free to access the row in the meantime. When a user wants to update a row, the application must determine whether another user has changed the row since it was Read. Attempting to Update A Record That Has Already Been Caused Causes a Concurrency Violation.using Perssesimistic Concurrency
Pessimistic concurrency is primarily used in environments where there is heavy contention for data, and where the cost of protecting data through locks is less than the cost of rolling back transactions if concurrency conflicts occur. Pessimistic concurrency is best implemented when lock times will be short, AS in Programmatic Processing of Records.
..................... ..
Using Optimistic Concurrency
Optimistic concurrency is appropriate in environments where there is low contention for data, or where read-only access to data is required. Optimistic concurrency improves database performance by reducing the amount of locking required, thereby reducing the load on the database server.
Optimistic concurrency is used extensively in .NET to address the needs of mobile and disconnected applications, where locking data rows for prolonged periods of time would be infeasible. Also, maintaining record locks requires a persistent connection to the database server, which is not possible in Disconnected Applications.
Testing for Optimistic Concurrency ViOLATIONS
There Are Several Ways to Test for Optimistic Concurrency ViOLATIONS:
· Use distributed time stamps. Distributed time stamps are appropriate when reconciliation is not required. Add a time stamp or version column to each table in the database. The time stamp column is returned with any query of the contents of the table. When an update is attempted, the time stamp value in the database is compared to the original time stamp value contained in the modified row. If the values match, the update is performed and the time stamp column is updated with the current time to reflect the update. If the values do not match, an optimistic concurrency violation has occurred. · Maintain a copy of original data values. When you query data from the database, keep a copy of any original data values. When you update the database, verify that the current values In The Database Match The Original Values.
· DataSets Hold Original Values That The Data Adapter Can Use to Perform Optimistic Concurrency Checks When You Update The Database.
· Use centralized time stamps Define a centralized time stamp table in your database, to log all updates to any row in any table For example, the time stamp table can indicate the following:.. "Row with ID 1234 on table XYZ was updated by John on March 26, 2002 2:56 PM "
Centralized time stamps are appropriate in checkout scenarios and in some disconnected client scenarios where clear owners and management of locks and overrides may be needed. In addition, centralized time stamps provide the benefit of auditing when needed.
Manually Implementing Optimistic Concurrency
Consider The Following SQL Query:
Select Column1, Column2, Column3 from Table1
TO Test for an Optimistic Concurrency Violation When Updating A Row In Table1, Issue The Following Update Statement: Update Table1 Set Column1 = @ NewValueColumn1,
Set column2 = @ newvalueColumn2,
Set column3 = @ newvalueColumn3
Where column1 = @ oldvalueColumn1 and
Column2 = @ oldvaluecolumn2 and
Column3 = @ OldValueColumn3
If the original values match the values in the database, the update is performed. If a value has been modified, the update will not modify the row because the WHERE clause will not find a match. You can use a variation of this technique and apply A WHERE CLAUSE ONLY TO SPECIFIC Column, Resulting In Data Being Overwritten Unless Particular Fields Have Been Updated Since They WERE Last Queried.
Note Always return a value that uniquely identifies a row in your query, such as a primary key, to use in your WHERE clause of the UPDATE statement. This ensures that the UPDATE statement updates the correct row or rows.
If a column at your data source allows nulls, you may need to extend your WHERE clause to check for a matching null reference in your local table and at the data source. For example, the following UPDATE statement verifies that a null reference in the local Row Still Matches A Null Reference At The Data Source, or That The Value In The Local Row Still Matches The Value At The Data Source:
Update table1 set colorn1 = @ newcolumn1value
Where (@ oldcolumn1value is null and color) or column1 =
@ OldColumn1Value
Using Data Adapters and DataSets TO IMPLEMENT OPTIMITINCURENCY
The DataAdapter.RowUpdated event can be used in conjunction with the techniques described earlier to provide notification to your application of optimistic concurrency violations. The RowUpdated event occurs after each attempt to update a modified row from a DataSet. You can use the RowUpdated event to add special handling code, including processing when an exception occurs, adding custom error information and adding retry logic.The RowUpdated event handler receives a RowUpdatedEventArgs object, which has a RecordsAffected property that indicates how many rows were affected by an update command for a modified row in .. a table If you set the update command to test for optimistic concurrency, the RecordsAffected property will be 0 when an optimistic concurrency violation occurs Set the RowUpdatedEventArgs.Status property to indicate how to proceed; for example, set the property to UpdateStatus.SkipCurrentRow To Skip Updating The Current Row, But to Continue Updating The Other Rows in The Update Command. for More Information About The Rowupdated Event, See Working with DataAdapter Events.
An alternative way to test for concurrency errors with a data adapter is to set the DataAdapter.ContinueUpdateOnError property to true before you call the Update method. When the update is completed, call the GetErrors method on the DataTable object to determine which rows have errors. THEN, USE The RowError Property on these Rows to find specific Error Details. For more information about how to process row errors, see address.
The following code sample shows how the Customer Data Access Logic Component can check for concurrency violations. This example assumes that the client has retrieved a DataSet, made changes to the data, and then passed the DataSet to the UpdateCustomer method on the Data Access Logic Component . The UpdateCustomer method will invoke the following stored procedure to update the appropriate customer record; the stored procedure updates the record only if the customer ID and company name have not already been modified: CREATE PROCEDURE CustomerUpdate
{
@Companyname varchar (30),
@eldcuStomerid Varchar (10),
@OLDCompanyName Varchar (30)
}
AS
Update Customers Set CompanyName = @companyname
Where customerid = @OLDCUSTOMERID and companyNAME = @OLDCompanyName
Go
Inside the UpdateCustomer method, the following code sample sets the UpdateCommand property of a data adapter to test for optimistic concurrency, and then uses the RowUpdated event to test for optimistic concurrency violations. If an optimistic concurrency violation is encountered, the application indicates the violation by setting the RowError of the row for which the update was issued. Note that the parameter values passed to the WHERE clause of the UPDATE command are mapped to the Original values of the respective columns in the DataSet.
// UpdateCustomer Method in the customerdalc Class
Public void UpdateCustomer (Dataset DSCustomer)
{
// Connect to the Northwind Database
SqlConnection cnnorthwind = New SqlConnection
"Data Source = localhost; integrated security = sspi; initial
Catalog = northwind ");
// Create a data adapter to access the customers Table in Northwind
SqlDataAdapter Da = New SqlDataAdapter (); // SET The Data Adapter's Update Command, To Call The "UpdateCustomer"
Stored Procedure
Da.UpdateCommand = New Sqlcommand ("Customerupdate", cnnorthwind;
Da.UpdateCommand.commandtype = commandtype.storedprocedure;
// add two parameters to the data adapter's update command, to Specify
information
// for the where clause (To Facilitate Checking for Optimistic Concurrency
Vioc
Da.UpdateCommand.Parameters.Add ("@ companiesName", Sqldbtype.nvarchar, 30,
"CompanyName");
// Specify the Original Value of Customerid As The First Where Clause
Parameter
Sqlparameter myparm = da.updateCommand.Parameters.Add (
"@OLDCUSTOMERID", SQLDBTYPE.NCHAR, 5,
Customerid ");
myparm.sourceversion = DATAROWVERSION.ORIGINAL;
// Specify The Original Value of Customername As The Second Where Clause
Parameter
myparm = da.UpdateCommand.Parameters.Add (
"@OLDCompanyName", Sqldbtype.nvarchar, 30,
"CompanyName");
myparm.sourceversion = DATAROWVERSION.ORIGINAL;
// Add a Handler for Row Update Events
Da.RowUpdated = new sqlrowupdatedEventHandler (onrowupdated);
// Update The Database
Da.Update (DS, "Customers");
Foreach (DataRow Myrow In Ds.Tables ["Customers"]. ROWS)
{
IF (Myrow.haserRRORS)
Console.Writeline (Myrow [0] " Myrow.RowError);
}
}
// Method to handle row update events. If you register the Event But do not
Handle IT,
// a SQL Exception is thrown.
Protected static void onrowupdated (Object Sender, SqlrowUpdatedEventArgs
ARGS)
{
IF (args.recordsaffected == 0)
{
Args.row.RowError = "Optimistic Concurrency Violation Encounted"; args.status = updatestatus.skipcurrentrow;
}
}
When executing multiple SQL statements within one SQL Server stored procedure, you may, for performance reasons, choose to use the SET NOCOUNT ON option. This option prevents SQL Server from returning a message to the client after completion of each statement, thus reducing network traffic . However, you will not be able to check the RecordsAffected property as demonstrated in the previous code sample. The RecordsAffected property will always be-1. An alternative is to return the @@ ROWCOUNT function (or specify it as an output parameter) in your stored procedure; @@ ROWCOUNT contains the record count for the last statement completed in your stored procedure and is updated even when SET NOCOUNT ON is used Therefore, if the last SQL statement executed in your stored procedure is the actual UPDATE statement and you. Specify The @@ Rowcount As a return value, You Can Modify Application Code As Follows:
// Add Another Parameter to Data Adapter's Update Command, To Accept The
Return Value.
// you can name it anything you want.
Myparm = da.updateCommand.Parameters.add ("@ rowcount", sqldbtype.int);
myparm.direction = parameterDirection.ReturnValue;
// modify the onrowupdated method, to check the value of this parameter
// instead of the recordsaffected print.
Protected static void onrowupdated (Object Sender, SqlrowUpdatedEventArgs
ARGS)
{
IF (args.command.parameters ["@ rowcount"]. value == 0)
{
args.row.rowerror = "Optimistic Concurrence Violation Encounted";
Args.status = updatestatus.skipcurrentrow;
}
}
COM Interoperability
If you want your Data Access Logic Component class to be callable from COM clients, the recommended approach is to define your data access logic components by using the preceding guidelines and provide a wrapper component. However, if you want COM clients to be able to access Your Data Access Logic Components: Consider The Following Recommendations:
· Define the class and its members as public.
· Avoid Using Static MEMBERS.
DEFINE Event-Source Interfaces in Managed Code.
· Provide a constructor that does not use parameters.
· Do Not Use Overloaded Methods. Use methods with diffrent names instead.
· Use interfaces to evpose Common Operations.
· Use attributes to provide extra attribute for your class and memory.
· INCLUDE HRESULT VALUES in Any Exceptions Thrown from .Net Code.
· Use Automation-Compatible Data Types in Method Signatures.
For More Information About COM Interoperability, See the Microsoft .NET / COM MIGRATION AND UPERABILIDE.
Implementing Business Entities
Business Entities Exhibit The Following Characteristics:
· Business Entities Provide Stateful Programmatic Access To Business Data and (in Some Designs) Related FunctionAlity.
· Business enttive CAN Be Built from Data That Has Complex Schemas. The Data Typical Originates from Multiple Related Tables in The Database.
· Business Entity Data Can Be Passed As Part of The I / O Parameters of Business Processes.
· Business entities can be serializable, to persist the current state of the entities. For example, applications may need to store entity data on a local disk, in a desktop database if the application is working offline, or in a Message Queuing message. · Business Entities Do Not Access The Database Directly. All The Associated Data Access Logic Component.
.
AS Mentioned Earlier In this Document, There Are Various Ways To Repesent Business Entities In your application, Ranging from a data-centric model to a more object-Oriented Representation:
· XML
· Generic DataSet
· Typed DataSet
Custom Business Entity Components
Custom Business Entity Components with crud Behaviors
. The sections that follow describe how to represent business entity data in each of these formats To help you decide the most appropriate representation for business entities in your particular circumstances, the sections describe how to perform the following tasks for each business entity format:
Organize Collections of Business Entities
· Data Bind Business Entities To User-Interface Controls
· Serialize Business Entity Data
Pass Business Entity Data Between Tiers
The sections also consider the suitability of each business entity representation in terms of nonfunctional requirements, including performance, efficiency, scalability, and extensibility.Representing Business Entities as XML
.
XML Version = "1.0"?>
Product>
For more information, see how to use xml to represent collections and hierarchies of data in the appendix.
When you use xml to represent Business Entity Data, Consider The Following Guidelines:
· DECIDE WHENER THE XML Document Should Contain A Single Business Entity OR A Collection of Business Entities. The Preceding Example Represents A Single Product Business Entity.
• Use a namespace to unique Identify The XML Document, To Avoid Name Clash WITH CONTENT IN OTHER XML Documents. The Preceding Example Uses A Default Namespace Called URN: Auniquenamespace.
· Choose Appropriate Names for Elements and Attributes. The Preceding Example Uses The Column Names from the product Table, But this is not a requirement. Choose names..............
· Use ONE of the Following Approaches To Retrieve Your Business Entities in XML Format:
· If you are using SQL Server 2000, you can use the FOR XML clause in your queries or stored procedures. In performance tests, using FOR XML is only slightly faster than returning a DataSet. · Retrieve a DataSet and transform it or write it out AS An XML Stream. with this approach, you incote The overhead of create the dataset and additional overheadiff a transformation.
· Build an XML document from output parameters or by using a data reader. Data readers are the fastest way to retrieve multiple rows from the database, but the process associated with building XML may decrease the performance benefit.
For More Information and Performance Considances, See Performance Comparison: Data Access Techniques.
The Advantages of Reprresenting Business Entities As XML Are As Follows:
· Standards support. XML IS A World Wide Web Consortium (W3C) Standard Data Reperestation Format. For More Information About this Standard, See http://www.w3.org/xml.
Flexibility. Xml Can Repesent Hierarchies and collections, see how to use xml to represent collections and hierarchies of data in the appendix.
· Interoperability. XML is an ideal choice for exchanging information with external parties and trading partners, regardless of platform. If the XML data will be consumed by ASP.NET or Windows Forms applications, you can load the XML data into a DataSet to take advantage Of the data binding support provides by DataSets.
The disadvantages of representing business enttives as XML Are As Follows:
· Preserving type fidelity. Type fidelity is not preserved in XML. However, you can use XSD schemas for simple data typing. · Validating XML. To validate XML, you can parse the code manually or use an XSD schema. Both approaches are relatively slow . For an example of how to validate xml by using an xsd schema, see how to validate xml by using an xsd schema.
. · Displaying XML You can not automatically display XML data in the user interface You can write an XSLT style sheet to transform the data into a DataSet;. However, style sheets are not easy to write Alternatively, the style sheet can transform the XML into. A Displayable Format Such as HTML. for more information, see how to apply a style sheet programmatically in a .net application in the appendix.
· Parsing XML. To parse XML, you can use the Document Object Model (DOM) or the XmlReader class provided in the Microsoft .NET Framework class library. XmlReader provides fast-forward only, read-only access to XML data, but DOM is more flexible because it provides random read / write access However, parsing an XML document by using DOM is slower;. you must create an instance of XmlDocument (or another XML parser class) and load the entire XML document into memory.
Sorting XML. You Cannot Automatic Or Sort Xml Data. Instead, Use ONE Of The Following Techniques:
· Deliver The Data IN PRESORTED ORDER. THIS OPTION DOES NOT Support Dynamic Resorting of Data In The Calling Application.
· Apply an XSLT style sheet to sort the data dynamically. If necessary, you can alter the sort criteria in the XSLT style sheet at run time, by using DOM. · Transform the XML data into a DataSet, and use a DataView object to sort And Search the data elements.
Using Private Fields. You do Not Have The Option of Hiding Information.
Representing business enttive as a generic dataset
A generic DataSet is an instance of the DataSet class, which is defined in the System.Data namespace in ADO.NET. A DataSet object contains one or more DataTable objects to represent information that the Data Access Logic Component retrieves from the database.
Figure 7 shows a generic DataSet object for the Product business entity. The DataSet object has a single DataTable to hold information for products. The DataTable has a UniqueConstraint object to denote the ProductID column as a primary key. The DataTable and UniqueConstraint objects are created when The DataSet is Created in The Data Access Logic Component.
Figure 7. Generic DataSet for the Product Business Entity
Figure 8 shows a generic DataSet object for the Order business entity. This DataSet object has two DataTable objects to hold information for the orders and order details, respectively. Each DataTable has a corresponding UniqueConstraint object to identify the primary key in that table. Additionally, The Dataset Has a relation Object To Associate Order Details with Orders.
Figure 8. Generic DataSet for the Order Business Entity
The following code shows how to retrieve a generic DataSet from a Data Access Logic Component, bind the DataSet to a DataGrid control, and then pass the DataSet to the Data Access Logic Component to save data changes: // Create a ProductDALC object
ProductDalc DalcProduct = new productdalc ();
// Call a Method on Productdalc To Get a DataSet Containing Information for
All products
DataSet dsproducts = DalcProduct.getProducts ();
// Use dataset in the client. For example, bind the dataset to user interface
CONTROLS
DataGrid1.datasource = dsproducts.tables [0] .defaultView;
DataGrid1.databind ();
// when you are ready, pass the updated dataset to the productdalc to save
The change
// back to the database
DalcProduct.UpdateProducts (DSProducts);
You can Also Query and Modify The Tables, Constraints, And Relations in a Dataset At Run Time. For more information, see creating and using datasets.
The Advantages of Reprresenting Business Entities As A Generic DataSet Area Follows:
Flexibility. DataSets CAN Contain Collections of Data, And Can Represent Complex Data Relationships.
· Serialization. DataSets Natively Support Serialization When Passing Across Tiers.
Data Binding. DataSets Can Be Bound To Any User-Interface Controls In ASNET and Windows Forms Applications.
Sorting and filtering. DataSets can be sorted and filtered by using DataView Objects. An Application Create Several DataView Objects for the Same Dataset, To View The Data in Different Ways.
· Interchangeability with XML. DataSets can be read or written in XML format. This is a useful technique in remote and disconnected applications, which can receive a DataSet in XML format and recreate the DataSet object locally. Applications can also persist DataSets to XML format while the applications are disconnected from the database. · Availability of metadata. Full metadata can be provided for a DataSet, in the form of an XSD schema. You can also programmatically obtain metadata for the DataSet by using methods in the DataSet, DataTable, DataColumn, Constraint, and rate classes.
· Optimistic Concurrency. WHEN You are Updating Data, You CAN Use DataSets, in Conjunction with Data Adapters, To Perform Optimistic Concurrency Checks Easily.
· Extensibility. If the database schema is modified, the methods in the Data Access Logic Component can create DataSets that contain modified DataTable and DataRelation objects as appropriate. The Data Access Logic Component method signatures do not change. The calling application can be modified to use The Dataset.
The disadvantages of representing Business Entities As a Generic DataSet Areas Follows:
· Client code must access data through collections in the DataSet. To access a table in a DataSet, client code must index into the DataTable collections by using an integer indexer or a string indexer. To access a particular column, you must index into the DataColumn Collection by Using a Column Number OR a Column Name. The Following Example Shows How To Access The ProductName Column for the First Row In The Products Table:
· Ã, ...
· // Get The Product Name for the Product in The First Row of A DataSet Called
· // dsproducts. Note The Collectes Are Zero-based.
· String str = (string) DSProducts.tables ["products"]. Rows [0] ["productname"];
· Ã, ...
Note Note that there is no compile-time checking of these indexer values. If you specify an invalid table name, column name, or column type, the error is trapped at run time. There is no IntelliSense support when you use generic DataSets.
· High instantiation and marshalling costs. DataSets result in the creation of several subobjects (DataTable, DataRow, and DataColumn), which means that DataSets can take longer to instantiate and marshal than XML strings or custom entity components. The relative performance of DataSets improves as ....................... ..
...................
Representing Business Entities as a typed dataset
A typed DataSet is a class that contains strongly typed methods, properties, and type definitions to expose the data and metadata in a DataSet. For an example of how to create a typed DataSet, see How to Create a Typed DataSet in the appendix.
The following lists describe the advantages and disadvantages of typed DataSets, compared with generic DataSets. Note that typed DataSets exhibit approximately the same instantiation and marshalling performance as generic DataSets.
The advantages of representing business entities as a typed DataSet are as follows:. · Code readability To access tables and columns in a typed DataSet, you can use typed methods and properties, as shown in the following code:
· Ã, ...
· // Get The Product Name for the product in the first row of a typed
· DataSet Called
· // dsproducts. Note The Collectes Are Zero-based.
· String str = dsproducts.products [0] .productname;
· Ã, ...
In this example, dsProducts is an instance of a typed DataSet. The DataSet has a single DataTable, which is exposed by a property named Products. The columns in this DataTable are exposed by properties such as ProductName, which returns the appropriate data type for the Column (Rather Than Just Returning Object).
The Provision of Typed Methods and Properties Makes Typed DataSets Easier To Use Typed DataSets, IntelliSense Is Available.
COMPILE TYPE CHECKING. Invalid Table Names and Column Names Are Detected At Compile Time Rather Than At Run Time.
The disadvantages of representing Business Entities As a Typed DataSet Are As Follows:
· Deployment. The assembly. The ass................
· Support of Enterprise Services (COM ) callers. If a typed DataSet will be used by COM clients, the assembly containing the typed DataSet class must be given a strong name and must be registered on client computers. Typically, the assembly is installed in the global assembly cache. These steps will also be required for custom entity classes, as described later in this document. · Extensibility issues. If the database schema is modified, the typed DataSet class might need to be regenerated to support the new schema. The regeneration Process Will NOT PRESERVE ANY Custom Code That Was Implement In The Typed DataSet Class. The assemble.
..................
....................
DEFINING Custom Business Entity Components
Custom Classes That Represent Business Entities Typically Contain The Following Members:
..................................
· Public properties to access the state of the entity, and to access subcollections and hierarchies of data inside the entity. The properties can have the same names as the database column names, but this is not an absolute requirement. Choose property names according to the NEEDS OF Your Application, Rather Than The names in the database.
. -..............................
. Figure 9 shows how custom entity classes are used Note that the entity class has no knowledge of the Data Access Logic Component or the underlying database; all database access is performed by the Data Access Logic Component to centralize data access policies and business logic Also. , the way in which you pass business entity data through the tiers is not directly tied to the format of your business entity representation; for example, you can represent business entities locally as objects, yet choose a different approach (such as scalar values or XML .) To pass business.
Figure 9. The Role of Custom Business Entity Components (Click thumbnail for larger Image)
Recommendations for Defining Custom Business Entity Components
To Help You Implement Your Custom Entity Components, Consider The Following Recommendations:
· Choosing between structs and classes. For simple business entities that do not contain hierarchical data or collections, consider defining a struct to represent the business entity. For complex business entities, or for business entities that require inheritance, define the entity as a class instead . For a commitness of struct and class types, see STRUCTURES AND CLASSES.
· Representing the business entity's state. For simple values such as numbers and strings, define fields by using the equivalent .NET data type. For a code example that shows how to define a custom entity, see How to Define a Business Entity Components in the Apresenting Subcollections and Hierarchies in a Custom Business Entity Component. There Are Two Ways To Represent Subcollections and Hierarchies of Data IN a Custom Entity:
· A .NET Collection Such as arraylist. The .NET Collection Classes Offer a Convenient Programming Model for Resizable Collections, And Also Provide Built-in Support for Data Binding To User-Interface Controls.
· A DataSet. DataSets are well suited for storing collections and hierarchies of data from a relational database or from an XML document. Additionally, DataSets are preferred if you need to be able to filter, sort, or data bind your subcollections.
For a code example Shows how to represent Collection and hierarchies of data in a customs and hierchies of data in a business entity component in the appendix.
. · Supporting data binding for user-interface clients If the custom entity will be consumed by user interfaces and you want to take advantage of automatic data binding, you may need to implement data binding in your custom entity Consider the following scenarios.:
· Data binding in Windows Forms. You can data bind an entity instance to controls without implementing data binding interfaces in your custom entity. You can also data bind an array or a .NET collection of entities. · Data binding in Web Forms. You can not data bind an entity instance to controls in a Web Form without implementing the IBindingList interface. However, if you want to data bind only sets, you can use an array or a .NET collection without needing to implement the IBindingList interface in your custom entity.
For a code example shows how to bind Custom Entities To User-Interface Controls, See How to Bind Business Entity Components To User-Interface Controls in the appendix.
· Exposing events for internal data changes. Exposing events is useful for rich-client user-interface design because it enables data to be refreshed wherever it is being displayed. The events should be for internal state only, not for data changes on a server. For a code esample this show to evted events in a Custom Entity Class, See How to Expose Events in A Business Entity Component in the appendix.
· Making your business entities serializable. Making business entities serializable enables the business entity's state to be persisted in interim states without database interactions. The result can be to ease offline application development and design of complex user interface processes that do not affect business data until they Are Complete. There Are Two Types of Serialization:
· XML serialization by using the XmlSerializer class. Use XML serialization when you need to serialize only public fields and public read / write properties to XML. Note that if you return business entity data from a Web service, the object is automatically serialized to XML through XML serialization.You can perform XML serialization on business entities without implementing any additional code inside the entity. However, only the public fields and public read / write properties in the object are serialized to XML. Private fields, indexers, private properties, read- only properties and object graphs are not serialized. You can control the resulting XML by using attributes in your custom entity. For more information about how to serialize custom entity components to XML format, see How to Serialize Business Entity Components to XML format in the appendix .
· Formatted serialization by using the BinaryFormatter or SoapFormatter class. Use formatted serialization when you need to serialize all the public and private fields and object graphs of an object, or if you will pass an entity component to or from a remoting server.
The formatter classes serialize all of an object's fields and properties, both public and private. BinaryFormatter serializes the object to binary format, and SoapFormatter serializes an object to SOAP format. Serialization by using BinaryFormatter is faster than serialization by using SoapFormatter. To use either of these formatter classes, you must mark your entity class with the [Serializable] attribute. If you need explicit control over the serialization format, your class must also implement the ISerializable interface. For more information about how to use formatted serialization, see How to Serialize Business Entity Components to Binary Format and How to Serialize Business Entity Components to SOAP Format in the appendix. · Note Default constructors are not called when an object is deserialized. This constraint is placed on deserialization for performance reasons.
The Advantages of Defining a Custom Entity Are As Follows:
· Code Readability. To Access Data IN a Custom Entity Class, You Can Use Typed Methods and Properties, AS Shown In The Following Code:
· // CREATE A ProductDalc Object
ProductDalc DalcProduct = new productdalc ();
·
· // Use the productdalc Object to create and populate a product
Object.
· // this code assumes the productdalc class Has a Method Named getProduct,
· // Which Takes a Product ID AS A Parameter (21 in this example) and
· Returns a
· // Productentity Object Containing All The Data for this Product.
Product = DalcProduct.getProduct (21);
·
· // Change The Product Name for this Product
· Aproduct.ProductName = "rosted coffee beans";
In the preceding example, a product is an instance of a custom entity class named ProductEntity. The ProductDALC class has a method named GetProduct, which creates a ProductEntity object, populates the object with data for a specific product and returns the ProductEntity object. The calling Application Can Use Properties Such AS ProductName To Access The Data on The Productent Ibject and Can Call Methods To Manipulate The Object.
. · Encapsulation Custom entities can contain methods to encapsulate simple business rules These methods operate on the business entity data cached in the entity component, rather than accessing the live data in the database Consider the following example..:
· // Call a Method Defined in The Productentity Class.
· Aproduct.IncreaseUnitpriceby (1.50);
In the preceding example, the calling application calls a method named IncreaseUnitPriceBy on the ProductEntity object. This change is not made permanent until the ProductEntity object is saved back to the database when the calling application invokes an appropriate method on the ProductDALC object.
· Modeling of complex systems. If you are modeling a complex domain problem that has many interactions between different business entities, it may be beneficial to define custom entity classes to absorb the complexity behind well-defined class interfaces.
· Localized validation. Custom entity classes can perform simple validation tests in their property accessors to detect invalid business entity data. For more information, see How to Validate Data in Property Accessors in Business Entity Components. · Private fields. You can hide information that you Do Not Want to Expose to the Caller.
The disadvantages of defining a Custom Entity Are As Follows:
· Collections of business entities. A custom entity represents a single business entity, not a collection of business entities. The calling application must create an array or a .NET collection to hold multiple business entities.
· Serialization. You must implement your own serialization mechanism in a custom entity. You can use attributes to control how entity components are serialized, or you can implement the ISerializable interface to control your own serialization.
· Representation of complex relationships and hierarchies in a business entity. You must implement your own mechanism for representing relationships and hierarchies of data in a Business Entity Component. As described previously, DataSets are often the easiest way to achieve this effect.
· Searching and sorting of data. You must define your own mechanism to support searching and sorting of entities. For example, you can implement the IComparable interface to allow entity components to be held in a SortedList or Hashtable collection.
· Deployment. You Must Deploy, ON All Physical Tiers, The assembly containing the customer.
· Support for Enterprise Services (COM ) clients. If a custom entity will be used by COM clients, the assembly containing the entity must be given a strong name and must be registered on client computers. Typically, the assembly is installed in the global assembly Cache. · EXTENSIBILITY ISSUES. IF The Database Schema is Modified, you might nesed to modify the cousts.
Defining Custom Business Entity Components with crud Behaviors
When you define a custom entity, you can provide methods to completely encapsulate the CRUD operations on the underlying Data Access Logic Component. This is the more traditional object-oriented approach, and may be appropriate for complex object domains. The client application no longer accesses the Data Access Logic Component class directly. Instead, the client application creates an entity component and calls CRUD methods on the entity component. These methods forward to the underlying Data Access Logic Component.
Figure 10 shows the role of custom entity classes with crud Behaviors.
Figure 10. The Role of Custom Business Entity Components with Crud Behaviors (Click thumbnail for larger image)
The Advantages of Defining Custom Entity Classes with crud Behaviors Are As Follows:
. The underline.
Interface to Caller. The Caller Must Deal with Only ONE Interface To Persist Business Entity Data. There is no need to access the data access logic component directly.
Private Fields. You can hide information That You Do Not Want To Expose to the Caller.The Disadvantages of Defining Custom Entity Classes with crud Behaviors Are As Follows:
· Dealing with sets of business entities. The methods in the custom entity pertain to a single business entity instance. To support sets of business entities, you can define static methods that take or return an array or a collection of entity components.
· Increased Development Time. The Traditional Object-Oriented Approach Typically Requires More Design and Development Effort Than Working with existing Objects, Such As DataSets, Requires.
Recommendations for REPRESENTING DATA AND Passing Data THROUGH TIERS
The way in which you represent data throughout your application, and the way in which you pass that data through the tiers, do not necessarily need to be the same. However, having a consistent and limited set of formats yields performance and maintenance benefits that reduce Your NEED for Additional Translation Layers.
The data format that you use should depend on your specific application requirements and how you want to work with the data. There is no universal way to represent your data, especially because many of today's applications are required to support multiple callers. However, it is Recommended That You Follow Thase General Guidelines:
· If your application mainly works with sets and needs functionality such as sorting, searching and data binding, Datasets are recommended. However, if your application works with instance data, scalar values will perform better.
· If your application mainly works with instance data, custom business entity components may be the best choice because they prevent the overhead caused when a DataSet represents one row. · In most cases, design your application to use a data-centric format, such as XML documents or DataSets. You can use the flexibility and native functionality provided by the DataSets to support multiple clients more easily, reduce the amount of custom code, and use a programming API that is familiar to most developers. Although working with the data in an Object-Oriented Fashion Provides Some Benefits, Custom Coding Complex Business Entities Increases Development and Maintenance Costs in ProPlease To The Amount of Features You Want To Provide.
Transactions
Most of today's applications need to support transactions for maintaining the integrity of a system's data There are several approaches to transaction management; however, each approach fits into one of two basic programming models.:
MANUAL Transactions. You Write Code That Uses The Transaction Support Features of Either ado.net or transact-sql directly in Your Component Code or Stored Procedures, respective.
· Automatic transactions. Using Enterprise Services (COM ), you add declarative attributes to your .NET classes to specify the transactional requirements of your objects at run time. You can use this model to easily configure multiple components to perform work within the same transaction.
This section provides guidance and recommendations to help you implement transaction support in data access logic components and business entity components. For examples and a more in-depth discussion of transactions in .NET, see the .NET Data Access Architecture Guide.Implementing Transactions
In most circumstances, the root of the transaction is the business process rather than a Data Access Logic Component or a Business Entity Component. The reason is that business processes typically require transactions that span multiple business entities, not just a single business entity.
However, situations may arise where you need to perform transactional operations on a single business entity without the assistance of a higher-level business process For example, to add a new customer to the database discussed earlier, you must perform the following operations.:
· INSERT A New Row In The Customer Table.
INSERT A New Row or Rows in the address table.
Both of these operations must succeed, or the customer will not be added to the database. If the Customer business entity will never be a part of a larger business process that will initiate the transaction, use manual transactions within the Customer business entity. Manual transactions .
Figure 11 shows how to decide whether to use manual transactions or automatic transactions. Due to the overhead of COM transactions, the recommended approach is to push the transaction to the database and control the transactional behavior in stored procedures where possible.
Figure 11. Deciding how to import transactions
Note If you are calling from an ASP.NET-based client, and there is no business process to initiate the transaction, you may be tempted to start the transaction in the ASP.NET code-behind This is not a good design;. You should never initiate a transaction from an ASP.NET-based client. Instead, separate the presentation of the data from the business process. Performance is also an issue due to issues such as network latency, because this is the most common layer to be physically Deployed on another tier.
Recommendations for USING MANUAL Transactions in Data Access Logic Components
WHEN You Implement Manual Transactions In Data Access Logic Components: Consider The Following Recommendations:
· Where possible, perform your processing in stored procedures. Use the Transact-SQL statements BEGIN TRANSACTION, END TRANSACTION, and ROLLBACK TRANSACTION to control transactions. For a code example, see "How To Perform Transactions With Transact-SQL" in the .NET Data Access Architecture Guide.
· If you are not using stored procedures, and the data access logic components will not be called from a business process, you can control transactions programmatically by using ADO.NET. For a code example, see "How to Code ADO.NET Manual Transactions "in the .NET Data Access Architecture Guide.
Recommendations for Using Automatic Transactions in Data Access Logic Components
Despite the overhead associated with COM transactions, automatic transactions provide a simpler programming model than manual transactions, and are necessary when your transactions span multiple distributed data sources as they work in conjunction with the DTC. If you implement automatic transactions in data access logic components, consider the following recommendations: · The Data Access Logic Component must inherit from the ServicedComponent class in the System.EnterpriseServices namespace Note that any assembly registered with COM services must have a strong name For more information about strong-named assemblies, see Creating and.. Using strong-named assembly.
· Annotate the Data Access Logic Component with the Transaction (TransactionOption.Supported) attribute so that you can perform read and write operations in the same component. This option avoids the overhead of transactions where they are not required-unlike Transaction (TransactionOption.Required) , Which always requires a transaction.
The Following Code Sample Shows How To Support Automatic Transactions In A Data Access Logic Component Class:
Using system.enterprises;
Transaction (TransactionOption.supported)]
Public Class Customerdalc: ServicesDComponent
{
...
}
If you use automatic transactions, your data access logic components should vote in transactions to indicate whether the operation succeeded or failed. To vote implicitly, annotate your methods by using the AutoComplete attribute and throw an exception if the operation fails. To vote explicitly, call The SetComplete Or Setabort Method on The ContextUtil Class.
For More Information About Automatic Transactions, See "Using Automatic Transactions" in The .NET Data Access Architecture Guide.USING Automatic Transactions in Business Entity Components
If you implement custom business entity components that have behaviors, you can use automatic transactions to specify the transactional behavior of these objects. The recommendations for using automatic transactions to specify the transactional behavior of business entity components are the same as the previously listed recommendations for implementing Automatic Transactions in Data Access Logic Components.
Note If the Business Entity Component does not contain any business logic that requires it to vote in the transaction, it can ignore the transaction context altogether The custom Business Entity Component does not need to inherit from ServicedComponent;. The transaction context will still flow, but The Entity Component Will Ignore The Context.
Validations
You can Perform Data Validation at Many Tiers in your application. Different Types of validation Are Appropriate in Each Tier:
· The Client Application CAN Validate Business Entity Data Locally, Before The Data IS Submitted.
Business Processes CAN Validate Business Documents as The Documents Are Received by Using An Xsd Schema.
• Data Access Logic Components and Stored Procedures CAN Validate Data TO Ensure Referenceial Integrity and to Enforce Constraints and Nontrol Department Business Rules.
There Are Two General Kinds of Validation:
· Point-in-time validation. This is validation that is performed at a specific point in time. For example, a business process validates an XML document when the document is received. · Continuous validation. This is validation that is performed on an ongoing Basis at Many Different Levels in Your Application. Example The Following:
· User Interfaces Can Specify Maximum Field Lengths to Prevent The User from Entering Strings That Are Too Long.
· DataSets Can Specify The Maximum Length of Data Columns.
· Custom Business Entity Components CAN Perform Range Checks, Length Checks, Non-Null Checks, AND Other Simple Tests on Entity Data.
· Data Access Logic Components, Stored Procedures, And The Database Itself CAN Perform Similar Tests To Ensure That Data Is Valid Before It Is Saved In The Database.
At times, you may want to implement an out-of-band aggregator or a transformer process. This approach may be useful if the validations and transformations change often, but it incurs a performance penalty. For example, if an ISV wanted to use the Same Components To Support Two Versions of A Database Schema, you Create a Separate Component To Perform Validation and Transformations Between The Two Database Schema Versions.
How to validate xml by using an xsd schema
To Validate An Xml Document Against An Xsd Schema, Take The Following Steps:
1. Create An XmlvalidatingReader Object As a Wrapper Arounder Object As A Wrapper Arounder Object As a Wrapper Arounder Object, AS Shown In The Following Code:
2. 'Create An XmlValidatingReader Object, To Read and Validate Product.xml3. XmlTextReader Tr = New XmlTextReader ("Product.xml");
4. XmlvalidatingReader VR = New XmlValidatingReader (TR);
5. Specify The Type of Validation Required, by using the validationType Enumeration. The .NET Framework Supports Three Types of XML Validation:
· Document Type Definitions (DTDS); Specify ValidationType.dtd
· Microsoft XML Data-Reduced (XDR) Schemas; Specify ValidationType.xdr
· W3C-Standard XSD Schemas; Specify ValidationType.Schema
The Following Code Shows The Use of the ValidationType Enumeration:
Vr.validationType = ValidationType.schema; 'Specify XSD Schema
Validation
6. Register a Validation Event-Handler Method, AS Shown In The Following Code:
7. vr.validationEventhandler = new validationEventhandler (MyHandlerMethod);
8. Provide An Implementation for the Validation Event-Handler Method, AS Shown In The Following Code:
9. Public void MyHandlerMethod (Object Sender, ValidationEventArgs E)
10. {
11. Console.writeline ("Validation Error:" E.MESSAGE);
12.}
13. Read and Validate The Following Code. Validation Errors Are Picked Up by The Validation Event-Handler Method.
14. TRY
15. {
16. While (Vr.Read ())
17. {
18. // Process The XML Data, AS Appropriate ...
19.}
20.}
21. Catch (XMLException EX) 22. {
23. Console.writeline ("XMLException:" EX.MESSAGE);
twenty four. }
25. vr.close ();
How To Validate Data In Property Accessors in Business Entity Components
The following code fragment shows how to perform simple validation in property accessors in a custom entity. If the validation test fails, you can throw an exception to indicate the nature of the problem. You can also use regular expressions within your set property accessors to validate Specific Data and Formats.
Public Class ProductDalc
{
Ã, ...
Public Short ReorderLevelLevel
{
Get {return reorderLevel;}
}
set
{
Value <0)
{
Throw New ArgumentOutofrangeException ("ReorderLevel Cannot Be
");");
}
REORDERLEVEL = Value;
}
// Plus Other Members in The ProductDalc Class ...
}
Exception management
When errors occur in .NET applications, the general advice is to throw exceptions rather than return error values from your methods. This advice has implications for the way you write data access logic components and business entity components. There are two general kinds of exceptions that Will Occur:
· Technical Exceptions, Which Include:
· ADO.NET
Connection to Database
· Resources (Such AS Database, NetWork Share, And Message Queuing Are Unavailable
Business Logic Exceptions, Which Include:
Validation ErrorS
Errors in Stored Procedures That IMPLEMENT Business Logic
Recommendations for Managing Exceptions in a Data Access Logic ComponentData access logic components should propagate exceptions, and should wrap exception types only if doing so makes the exception easier for the client to manage. Wrapping the exceptions in two main exception types (technical and business) helps EXCEPTION HANDLING STRUCTURE AND EXCETION PUBLISHING LOGIC for the potentially Diverse Callers.
Your application should publish exception information. Technical exceptions can be published to a log that is monitored by administrators or by a Windows Management Instrumentation (WMI) monitoring tool like Microsoft Operations Manager. Business exceptions can be published to an application-specific log. In general Allow the Exceptions to Propagate from your data access Logic Component and be published by the caller so that you have the entire context of the exception.
The Following Example Illustrates these Recommendations:
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
}
}
}
Recommendations for Managing Exceptions in Business Entity Components
Business entity components should propagate exceptions to callers. Business entity components may also raise exceptions if they are performing validation, or if the caller tries to perform an operation without providing all the required data for the operation.
The following example illustrates how a business entity component can raise an exception In this example, the Update method throws an exception if the customer's first name is not provided:. Public class CustomerEntity
{
Public void update ()
{
// Check what 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 ("You Must Provide a First Name);
}
...
}
}
For more information about dealing with exceptions in .NET applications, see Exception Management in .NET. You can inherit your custom technical exceptions and custom business exceptions from the ApplicationException class or the BaseApplicationException class provided in the Exception Management Application Block.
Authorization and security
This section explains how security applies to your data access logic components and your business entity components. The .NET common language runtime uses permissions objects to implement its mechanism for enforcing restrictions on managed code. There are three kinds of permissions objects, each with a specific Purpose:
.
· Identity. The Required Identity Characteristics That An Assembly Must Have in Order To Run.
· Role-based security. These permissions objects provide a mechanism for discovering whether a user (or the agent acting on the user's behalf) has a particular identity or is a member of a specified role. The PrincipalPermission object is the only role-based security permissions object.Managed code can discover the identity or the role of a principal by using a Principal object, which contains a reference to an Identity object. It might be helpful to compare identity and principal objects to familiar concepts like user and group accounts. In the .NET Framework, identity objects represent users, whereas roles represent memberships and security contexts. The principal object encapsulates both an identity object and a role. Applications in the .NET Framework grant rights to the principal object based on its identity or, more commonly , ITS Role Membership.
For More Information About Permissions and Security IN .NET, See Key Security Concepts.
Recommendations for Security In Data Access Logic Components
Data Access Logic Components Are Designed To Be Used by Other Application Components, and Are The Last Place In your application code where you can ustement security before the caller has access to your data.
Often, data access logic components can rely on the security context set by the caller. However, there are some situations where the Data Access Logic Component should perform its own authorization checks to determine whether a principal is allowed to perform a requested action. Authorization occurs .
Perform Authorization CHECKS At The Data Access Logic Component Level if you need to: · Share Data Access Logic Components with developers of business processes That you do not fully trust
Protect Access To Powerful Functions Exposed by The Data Stores
After You Define Identity and Principal Objects, There Are Three Different Ways To Perform Role-Based Security Checks:
· Use the PrincipalPermission Object To Perform Imperative Security Checks.
· Use The PrincipalPermissionattribute Attribute To Perform Declarative Security Checks.
· Use the property and the isinrole method in The Principal Object To Perform Explicit Security Checks.
The Following Code Sample Shows How To Use PrincipalPermissionattribute To Specify A Declarative Role-Based Security Check ON A Method in A Data Access Logic Component Class:
Using system;
Using system.security.permissions;
Public Class Customerdalc
{
Public Customerdalc ()
{
}
// use principalpermissionattribute to demand this caller of this
Method
// HAS An Identity Named "Myuser", And Belongs to the "administrator" role.
[PrincipalPermissionatTribute (SecurityAction.Demand,
Name = "myuser", role = "administrator"]]
Public void deletecustomer (String Customerid)
{
// delete customer code here
}
}
The Following Code Shows How To create a Principal Object That Has The Required Identity and Role, So That You Can Call The Deletecustomer Method ON A Customerdalc Object:
Using system;
Using system.security.principal;
Using system.threading;
Public class mainclass
{
Public static int main (String [] ARGS)
{
Console.write ("User Name:"); string username = console.readline ();
Console.write ("Password:");
String password = console.readline ();
IF (Password == "Password" && username == "myuser")
{
// Create a generic identity with the name "myuser"
GenericIdentity myidentity = new genericidentity ("myuser");
// CREATE ROLES
String [] mystring = {"administrator", "user"};
// Create a Generic Principal
GenericPrincipal myprincipal = new genericprincipal (MyIdentity,
Mystring);
// SET this Thread's Current Principal, for use in role-based security
Thread.currentprincipal = myprincipal;
}
// Create a Customerdalc Object, and try to call its deletecuStomer
Method.
// this Will Only succeed if the capital principal's Identity and Role
Are OK.
Customerdalc C = New Customerdalc ();
C. DeleteCustomer ("VINET");
}
}
Windows Authentication
Ideally, you should use Windows Authentication, rather than using SQL Server Authentication, when you connect to the database. However, you should use service accounts and avoid impersonating through to the database, because this will impede connection pooling. Connection pooling requires identical connection strings ; if you try to open the database by Using DiffERENT Connection Strings, you will create Separate Connection Pools, Which Will Limit Scalability.
For More Information and Connection Pooling, See The "Managing Database Connections" Section in The .NET Data Access Architecture Guide.
Secure Communication Recommendations
To achieve secure communication between calling applications and data access logic components, consider the following recommendations: · If your data access logic components are called over the wire from diverse tiers, and the exchange involves sensitive information that needs to be protected, use Distributed Component Object Model (DCOM), Secure Sockets Layer (SSL), or Secure Internet Protocol (IPSec) Secure Communication Technology Technologies.
· If data is stored encrypted in a database, data access logic components are usually responsible for encrypting and decrypting the data. If the risk of exposing the information is high, strongly consider securing the communication channel to and from the data access logic components.
Recommendations for Security In Business Entity Components
If you implement your business entities as data structures (such as XML or DataSets), you do not need to implement security checks However, if you implement your business entities as custom business entity components with CRUD operations, consider the following recommendations.:
· If the entities are exposed to business processes that you do not fully trust, implement authorization checks in the business entity components and in the data access logic components. If you do implement checks at both levels, however, you may encounter the maintenance issue of Keeping The security policies synchronized.
.
Deployment
THIS Section Provides Recommendations To Help You Decide How To Deploy Data Access Logic Components and Business Entity Components.Deploying Data Access Logic Components
There Are Two Ways To Deploy Data Access Logic Components:
· Deploy Data Access Logic Components TOGETHER WITH The Business Process Objects. This Deployment Method Provides Optimum Performance for Data Transfers, And Has Several Additional Technical Benefits:
· Transactions can flow seamlessly between the business process objects and the data access logic components. However, transactions do not flow seamlessly across remoting channels. In the remoting scenario, you need to implement transactions by using DCOM. Furthermore, if the business process and the Data Access Logic Component Were Separated by A Firewall, You Would Require Firewall Ports Open Between Both Physical Tiers to enable DTC Communication.
· Deploying Business Process Objects and Data Access Logic Components TOGETHER Reduces The Number of Transaction Failure Nodes.
· The Security CONTEXT FLOWS Automatical Between The Business Process Objects and the data access logic components. There is no need to set principal objects.
. · Deploy data access logic components together with the user-interface code Data access logic components are sometimes used directly from UI components and UI process components To increase performance in Web scenarios, you can deploy data access logic components together with the UI code.; this deployment method enables the UI layer to take advantage of data reader streaming for optimum performance However, if you do consider this deployment method, bear in mind the following:. · A common reason for not deploying data access logic components together with UI code is To Prevent Direct Network Access To your data source from your Web Farms.
· If your Web farm is deployed in a DMZ scenario, firewall ports must be opened to access SQL Server. If you are using COM transactions, additional firewall ports must be opened for DTC communication. For more information, see the .NET Data Access Architecture Guide.
Deploying Business Entities
Business entities are used at many different tiers in your application. Depending on how you implement your business entities, you may need to deploy them to multiple locations if your application spans physical tiers. The following list describes how to deploy business entities in different implementation scenarios :
· Deploying Business Entities implemented as typed DataSets. The typed DataSet class must be accessed by the Data Access Logic Component and by the calling application. Therefore, the recommendation is to define typed DataSet classes in a common assembly to be deployed on multiple tiers.
· Deploying Business Entities implemented as custom business entity components. The custom entity class may need to be accessed by the Data Access Logic Component, depending on how you defined the method signatures in the Data Access Logic Component. Follow the same recommendation as for typed DataSets by defining custom entity classes in a common assembly to be deployed on multiple tiers. · Deploying Business Entities implemented as generic DataSets or XML strings. Generic DataSets and XML strings do not represent a separate data type. There are no deployment issues for business entities implemented In these formats.
Appendix
How to Define a Data Access Logic Component Class How to Use XML to Represent Collections and Hierarchies of Data How to Apply a Style Sheet Programmatically in a .NET Application How to Create a Typed DataSet How to Define a Business Entity Component How to Represent Collections and Hierarchies of Data in a Business Entity Component How to Bind Business Entity Components to User-Interface Controls How to Expose Events in a Business Entity Component How to Serialize Business Entity Components to XML Format How to Serialize Business Entity Components to SOAP Format How to Serialize Business Entity Components to Binary Format
How to Define a Data Access Logic Component Class
The code that follows is a sample definition of a class named CustomerDALC, which is the Data Access Logic Component class for Customer business entities. The CustomerDALC class implements the CRUD operations for the Customer business entity and provides additional methods to encapsulate business logic for this object .
Public Class Customerdalc
{
PRIVATE STRING CONN_STRING
Public Customerdalc () {
// acquire the connection string from a secure or encrypted location
// and assign to conn_string
}
Public CustomerDataSet GetCustomer (String ID)
{
// Code to Retrieve A Typed DataSet Containing Customer Data
}
Public String CreateCustomer (String Name)
String Address, String City, String State,
String Zip)
{
// CODE TO CREATE A New Customer in The Database, Based on The Scalar
// Parameters Passed Into this Method.
// Return The Customerid from this Method.
}
Public void UpdateCustom (CustomerDataSet UpdatedCustomer)
{
// Code to update the database, based on the customer data Sent in As A
Parameter
// of Type CustomerDataSet
}
Public void deletecustomer (String ID)
{
// code to delete the customer with the specified id
}
Public DataSet getCustomersWhopurchaseDProduct (int Productid)
{
// Code to Retrieve Customers Using a Generic Dataset, Because THIS
Method is not
// Retrieving All The Information Associated with a CUSTOMER
}
}
How to use xml to represent collections and hierarchies of data
The following example shows how to represent collections and hierarchies of data in an XML document The XML document represents a single order made by a customer;. Note that the
OrderDetail>
OrderDetail>
OrderDetail>
OrderDetails>
Order>
How to Apply a Style Sheet ProgramMAAMATILY IN A .NET Application
To Apply A Style Sheet Programmatically In a .NET Application, Take The Following Steps:
1. Import the system.xml.xsl namespace as shown in The Following Code. The System.xml.xsl Namespace Contains The Xslt Transformation Classes in The .NET Framework Class Library.
2. using system.xml.xsl;
3. Create An Xsltransform Object As Shown In The Following Code:
4. xsltransform stylesheet = new xsltransform ();
5. Load The Required Style Sheet Into The Xsltransform Object As Shown In The Following Code:
6. Stylesheet.load ("MyStylesheet.xsl");
.
8. Stylesheet.Transform (Sourcedoc, Resultdoc);
How to create a typed dataset
You can use typed DataSets to represent business entities. There Area Several Ways to create a typed dataset:
· From A Data Adapter With, Microsoft Visual Studio® .NET
· From an Xsd Schema File with Visual Studio .NET
· From the .NET Framework command prompt window by using the XSD Schema Definition Tool (xsd.exe) Note It is also possible to define a typed DataSet programmatically by inheriting from the DataSet and defining methods, properties, and nested classes to represent the structure Of the dataset. The Easiest Way To Do this is to create a type ieping dataset code as the basis for your own type..................
CREANG A TYPED DATASET by Using A Data Adapter
To create a typed dataset by using a data adapter, FOLLOW THESE STEPS:
1. In Visual Studio .NET, add a data adapter to your form or component. In the data adapter Configuration Wizard, specify connection information for the data adapter. Also specify SQL strings or stored procedures for the Select, Insert, Update, and Delete Commands for your data adapter, as appprike.
2. In The Component Designer, Right-Click The Data Adapter Object, And The Click Generate Dataset.
3. In The Generate DataSet Dialog Box, Click New, Type A Name for the New DataSet Class, And The Click OK.
4. To verify that the typed DataSet has been created, in Solution Explorer, click the Show All Files button. Expand the node for the XSD schema file, and verify that there is a code file associated with the XSD schema. The code file defines The New Typed DataSet Class.
Creating a type
To create a typed dataset from an xsd schema file by Using Visual Studio .NET, FOLLOW THESE STEPS:
1. In Visual Studio .NET, CREATE A New Project or Open an existing project.
2. Add an existing XSD schema to the project, or create a new XSD schema in the Component Designer.3. In Solution Explorer, double-click the XSD schema file to view the XSD schema in the Component Designer.
4. Select The Primary XSD Schema Element in The Component Designer.
5. On The Schema Menu, Click Generate Dataset.
6. To verify that the typed DataSet has been created, in Solution Explorer, click the Show All Files button. Expand the node for the XSD schema file, and verify that there is a code file associated with the XSD schema. The code file defines The New Typed DataSet Class.
Creating a typed dataset by using the xsd schema definition Tool (xsd.exe)
The XML Schema Definition tool can generate a typed DataSet from an XSD schema file, an XDR schema file, or an XML instance document. The following command uses an XSD schema file named XsdSchemaFile.xsd to generate a typed DataSet in a Visual C # source file Named xsdschemafile.cs in The Current Directory:
XSD / Dataset / Language: C # xsdschemafile.xsd
For More Information, See Generating A Strongly Typed DataSet.
How To Define a Business Entity Component
The Following Example Shows How To Define a Custom Entity Class for the Product Business Entity:
Public Class Productentity
{
// Private Fields, to Hold The State of the Product Entity
Private int products;
Private string productname;
PRIVATE STRING QuantityPerunit;
Private Decimal Unitprice;
PRIVATE SHORT UnitsStock;
PRIVATE SHORT UNITSONORDER;
Private short reporderLevel;
// public property, to expose the state of the entity
Public int productID
{
Get {return products;
Set {productId = value;}
}
Public String ProductName
{
Get {return productname;}
Set {productName = value;
}
Public String QuantityPerUnit
{
Get {return quantityPerunit;}
Set {QuantityPerunit = value;
}
Public Decimal Unitprice
{
Get {return unitprice;}
Set {UNITprice = value;}
}
Public Short UnitsStock
{
Get {return unitsinstock;
Set {UnitsInstock = Value;}
}
Public Short Unitsonorder
{
Get {return unitsonorder;}
Set {unitsonorder = value;
}
Public Short ReorderLevelLevel
{
Get {return reorderLevel;}
Set {reorderLevel = Value;}
}
// Methods and Properties to Perform Localized Processing
Public Void IncreaseUnitpriceby (Decimal Amount)
{
UNITprice = Amount;
}
Public Short UnitsAboveReorderLevel
{
Get {Return (UnitsSinstock - REOREDERLEVEL);
}
Public String stockstatus
{
get
{
Return "in stock:" UnitsInstock ", ON Order:" Unitsonorder;
}
}
}
How to represent collections and hierarchies of data in a business entity component
.
Public class Orderentity
{
// private fields, to hold the order information
Private int orderId;
Private string customerid;
Private datetime orderdate;
Private datetime shippedddate;
// Private Field, to Hold The Order Details Information
Private Dataset OrderDetails;
// public property, to expose the order information
Public int OrderID
{
Get {return ORDERID;
Set {ORDERID = VALUE;
}
Public String Customerid
{
Get {returnj
SET {Customerid = Value;}}
Public DateTime OrderDate
{
Get {return orderdate;}
Set {ORDERDATE = VALUE;
}
Public DateTime ShippedDate
{
Get {return.com
Set {shippeddate = value;
}
// public property, to expose the order details information
Public Dataset OrderDetails
{
Get {returnraldetails;
Set {OrderDetails = Value;
}
// Additional Method, To Simplify Access to Order Details Information
Public Bool IsProductOrdered (int ProductID)
{
// Primary Key Column Must Be Defined in DataTable
DataRow Row = OrderDetails.tables [0] .rows.find (ProductID);
IF (row! = null)
Return True;
Else
Return False;
}
// Additional Property, To Simplify Access to Order Details Information
Public int NumberoforderItems
{
get
{
Return OrderDetails.tables [0]. ROWS.COUNT;
}
}
}
Note The Following Points Concerning The Orderentity Class:
· The class contains private fields to hold information about the order. There is also a private DataSet field, to hold additional details about the order. The Data Access Logic Component will populate all these fields when it creates the OrderEntity object.
· The Class Has Public Properties To Expose Information About The Order. There ISO a Property TO Expose The Dataset, TO Enable The Calling Application To Access The Order Details.
· The Class Has An Additional Method and Property To Provide Simplified Access To Order Details:
.
· The NumberoforderItems Property Indicates The Number of Order Lines In The ORDER.HOW TO BIND Business Entity Components To User-Interface Controls
You can Bind User-Interface Controls to Custom Entities in Windows Forms and in Asp.Net Applications. There Are Two Possible Scenarios:
· Binding a single business entity to user-interface controls. The following code sample shows how you can get an OrderEntity object from the OrderDALC object and bind the OrderEntity object to controls in a Windows Form. When the user changes values in these controls, the Data in the underlying Orderentity Object Is Also Changed AutomaticLay.
· // CREATE AN ORDERDALC OBJECT.
· ORDERDALC DALCORDER = New ORDERDALC ();
·
· // Use Dalcorder to get an orderentity object for Order ID 10248.
· // this code assumes the orderdalc class haas a method named getorder (),
Which
· // Returns an Orderentity Object for a Particular Order ID.
· Orderentity Order = Dalcorder.GetORDER (10248);
·
· // Bind The OrderId Property of The Orderentity TO A TextBox Control.
· TextBox1.dataBindings.add ("text", order, "orderid");
·
· // Bind The Customerid Property of The Orderentity To Another TextBox
.
· TextBox2.Databindings.add ("text", Order, "Customerid");
·
· // Bind The OrderDate Property of the Orderentity to a datepicker control.
· DateTimePicker1.Databindings.add ("Value", Order, "ORDERDATE"); · ·
· // Bind The shippedDate Property of the Orderentity to Another DatePicker
.
· DateTimePicker2.Databindings.add ("Value", ORDER, "ShippedDate");
·
· // Bind The OrderDetails DataSet of The Orderentity to a DataGrid Control.
· // The DataGrid Displays Each DataRow of The DataSet in a Separate Row in
· The grid.
· DataGrid1.datasource = Order.OrderDetails.tables [0] .defaultview;
................ ..
// Save The Orderentity Object Back to the Database, Via Dalcorder.
// this code assumes the Orderdalc Class Has A Method Named UpdateOrder (),
Which
// receives an orderentity parameter and updates the appropriate entry in
THE DATABASE
Dalcorder.UpdateORDER (Order);
· Binding a collection of business entities to a DataGrid control. The following code sample shows how to get an array of OrderEntity objects from the OrderDALC and then bind the array to a DataGrid control in a Windows Form. The DataGrid displays each array element (that IS, Each Orderentity Object) I Separate Row In The Grid.
· // CREATE AN ORDERDALC OBJECT.
· ORDERDALC DALCORDER = New ORDERDALC ();
·
· // Use Dalcorder to Get An Array of Orderentity Objects for Customer
· "Vinet".
· // this code assumes the orderdalc class haas a method named · getordersForcustomer (),
· // Which returns an array of ordertity Objects for a particular
Customer.
Orderentity [] Orderentities = Dalcorder.GetOrDersForcustomer ("Vinet");
·
· // Bind The Array to a DataGrid Control.
· DataGrid1.datasource = Orderentities;
WHEN You are Ready, you can pass the model of the folding cotalog
// Save the Orderentity Objects Back to the Database, Via Dalcorder.
// this code assumes Orderdalc Has a Method named updateOrDERS (), Which
Takes an Array
// of Orderentity Objects and Updates the appropriate entries in the appropriate
Database.
Dalcorder.UpdateRDERS (Orderentities);
How to Expose Events in a Business Entity Component
Custom entities can raise events when the business entity state is modified. These events are useful for rich client, user-interface design because data can be refreshed wherever it is being displayed. The following code sample shows how to raise business entity-related events in The Orderentity Class:
// define a common event class for all business entity events
Public Class EntityEventArgs: Eventargs
{
// Define Event Members, To Provide Information About The Event
}
// define a delegate specifying the signature for business entity-related
Events
Public Delegate Void EntityEventHandler (Object Source, EntityEventArgs E);
// define a Custom Entity Class That Raises Events When the Business Entity
State Changes
Public class Orderentity
{
// define 'Before' and 'After' Events for Business Entity State Changespublic Event EntityEventhandler BeforeChange, AfterChange
// Private Fields, To Hold The Business Entity's State
Private int orderId;
Private int Customerid;
Private datetime orderdate;
Private datetime shippedddate;
Private Dataset OrderDetails;
// public property, to expose the business entity's state
Public int OrderID
{
Get {return ORDERID;
set
{
BeforeChange (this, new entryeventargs ()); // raise a 'before' Event
ORDERID = VALUE;
Afterchange (this, new entryryEventArgs ()); // raise an 'after' Event
}
}
Public Int Customerid
{
Get {returnj
set
{
BeforeChange (this, new entryeventargs ()); // raise a 'before' Event
Customerid = Value;
Afterchange (this, new entryryEventArgs ()); // raise an 'after' Event
}
}
Public DateTime OrderDate
{
Get {return orderdate;}
set
{
BeforeChange (this, new entryeventargs ()); // raise a 'before' Event
ORDERDATE = VALUE;
Afterchange (this, new entryryEventArgs ()); // raise an 'after' Event
}
}
Public DateTime ShippedDate
{
Get {return.com
set
{
BeforeChange (this, new entryeventargs ()); // raise a 'before' Event
SHIPPEDDATE = VALUE;
Afterchange (this, new entryryEventArgs ()); // raise an 'after' Event
}
}
// Additional Members, As Required ...
}
Note The Following Points Concerning The Preceding Code:
· The EntityEvent class provides information about business entity-related events. The EntityEventHandler delegate specifies the signature for all business entity-related events raised by custom entity classes. The delegate signature follows the recommended .NET Framework guidelines for event-handler delegates. For guidelines On How to Define and Use Events in .NET, See Event Usage Guidelines. The Orderentity Class Defines Two Events Named BeforeChange AndreatChange.
.
How to Serialize Business Entity Components To XML Format
This Section Discusses The Following Issues:
· Using XMLSerializer to Serialize A Custom Entity Object
· XML Serialization Of Objects in XML Web Services
· Default XML Format of a serialized Custom Entity Object
· Controlling The XML Format of a Serialized Custom Entity Object
Using XMLSerializer to Serialize a Custom Entity Object
The Following Code Sample Shows How To Use The Xmlserializer Class to Serialize An Orderentity Object To XML Format:
Using system.xml.Serialization; // this name namespace Contains
XMLSerializer Class
...
// Create An XmlSerializer Object, To Serialize Orderentity-Type Objects
XMLSerializer Serializer = New XMLSerializer (TypeOf (ORDERENTITY))
// serialize an orderientity Object to an XML file named
"MyXMLORDERENTITY.XML"
TextWriter Writer = New StreamWriter ("MyXMLORDERETITY.XML");
Serializer.Serialize (Writer, Order); Writer.Close ();
Serializing Objects in XML Web Services
The Following Code Sample Shows How To Write An XML Web Service That Uses Custom Entity Objects:
Namespace MywebService
{
[WebService (Namespace = "URN: MyWebServiceNamespace")]]]
Public class Orderws: System.Web.Services.Webservice
{
[WebMethod]
Public Orderentity GetOrder (int OrderID)
{
// CREATE An ORDERDALC Object.
ORDERDALC DALCORDER = New Orderdalc ();
// use dalcorder to get an orderentity object for the specified order
ID.
// this code assumes the Orderdalc Class Has a Method Named GetOrder,
// Which Takes An ORDER ID AS A Parameter And Returns An ORDERENTITY
Object
// containing all the data for this order.
Orderentity Order = Dalcorder.GetORDER (10248);
// Return The Orderentity Object. The Object Will Be Serialized
Automatically.
Return ORDER;
}
[WebMethod]
Public void UpdateOrder (Orderentity Order)
{
// CREATE An ORDERDALC Object.
ORDERDALC DALCORDER = New Orderdalc ();
// Use Dalcorder to save the Orderentity Object's data to the database.
// this code assumes the Orderdalc Class Has A Method Named UpdateOrder,
// Which Receives An Orderentity Object and Saves The Data to The Data To THE
Database.
Dalcorder.UpdateORDER (Order);
}
Note The Following Points Concerning The Preceding Code:
· The getorder method receivers An ORDER ID AS A Parameter And Returns An Orderentity Object That Contains The Data for this Order.
· The UpdateOrder Method Receives An Orderentity Object and Saves The Object's Data To The Database.
· If the client application invokes the GetOrder and UpdateOrder methods, OrderEntity objects will automatically be serialized to XML format for the method call.Default XML Format of a Serialized Custom Entity Object
The Following XML Document Shows The Default XML Serialization Format for Orderent Ibjects:
XML Version = "1.0" encoding = "UTF-8"?>
XMLns: xsi = "http://www.w3.org/2001/xmlschema-instance"> Orderentity> The Preceding Document Illustrate The Default Rules for XML Serialization: · The root element in the xml document is the same as the class name, Ordereentity. · Each Public Property (AND Field) in The Orderentity Object Is Serialized to an Element That Has The Same Name. THE ORDERDETAILS Property In The Orderentity Class Is A DataSet. DataSets Provide Built-in Support for XML Serialization. The OrderDetails DataSet IS Serialized As Follows: XMLns: XS = "http://www.w3.org/2001/xmlschema" XMLns: MSData = "URN: Schemas-Microsoft-COM: XML-MSDATA"> /> xs: sequence> xs: complexType> xs: element> xs: kice> xs: complexType> xs: element> xs: schema> XMLns: Diffgr = "URN: Schemas-Microsoft-COM: XML-DIFFGRAM-V1"> Diffgr: Haschanges = "Inserted"> OrderDetails> Diffgr: Haschanges = "Inserted"> OrderDetails> Diffgr: Haschanges = "Inserted"> OrderDetails> NewDataSet> DIFFGR: DIFFGRAM> OrderDetails> Note The Following Points Concerning The Serialization of DataSets: · The · The Controlling the XML Format of a serialized Custom Entity Object You can use .Net Attributes in Your Custom Entity Class To Control How The Properties and Fields Are Serialized to Xml. Consider The Following Revised Version of The Ordereentity Class: [XMLROOT (ElementName = "Order", Namespace = "URN: MyNameSpace")]]] Public class Orderentity { [Xmlattribute (attributename = "id")]]]] Public int OrderId {... get and set code, as before ...} [XMlattribute (AttributeName = "CustID")]]] Public String Customerid {... get and set code, as before ...} [XMLELEMENT (ElementName = "Ordered")]] Public DateTime OrderDate {... get and set code, as before ...} Public Dataset OrderDetails {... get and set code, as before ...} [XMLELEMENT (ElementName = "Shipped") Public DateTime ShippedDate {... get and set code, as before ...} // Additional Members, As Required ... } · When an Orderentity Object IS Serialized to XML, IT Now Has The Following Format: XML Version = "1.0" encoding = "UTF-8"?> Custid = "Vinet" XMLns = "URN: MyNamespace" XMLns: xsd = "http://www.w3.org/2001/xmlschema" XMLns: xsi = "http://www.w3.org/2001/xmlschema-instance"> Order> For More Information About How To Use Attributes To Control XML Serialization, See Attributes That Control XML Serialization. How To Serialize Business Entity Components to SOAP Format The following code sample shows how to use the SoapFormatter class to serialize an OrderEntity object to SOAP format. SOAP serialization also occurs (implicitly) when you pass an object to or from an XML Web service by using the SOAP protocol, and when you pass an Object to or from a remoting server by using an http recoting channeling channeling channeling channel. in addition, you can use the TCP Remoting Channel. Using system.Runtime.Serialization.formatters.soap; // for the SOAPFORMATTER CLASS ... // Create a soapformatter Object, To serialize Orderentity-Type Objects SOAPFORMATTER FORMATTER = New soapFormatter (); // serialize an orderentity Object to a soap (xml) file named "MysoapordERENTITY.XML" FileStream Stream = file.create ("MySoaPordERENTITY.XML"); Formatter.Serialize (stream, order); stream.close (); To Use Soap Serialization for Custom Entity Components You Must Annotate Your Entity Class by Using The Serializable Attribute, AS Shown In The Following Code: [Serializable] Public class Orderentity { // MEMBERS, AS BEFORE If you want to customize the SOAP format generated during serialization, your entity class must implement the ISerializable interface. You must provide a GetObjectData method for the SoapFormatter to call during serialization, and you must provide a special constructor for the SoapFormatter to call to recreate the object during deserialization The following code demonstrates the use of the ISerializable interface, the GetObjectData method, and the special constructor: using System.Runtime.Serialization; // For ISerializable interface, and. Related Types ... [Serializable] Public Class Orderentity: iSerializable { // Serialization function, Called by The SoapFormatter During Serialization Void iSerializable.GetObjectData (SerializationInfo Info, StreamingContext CTXT) { // Add Each Field to the SerializationInfo Object Info.addvalue ("ORDERID", ORDERID; // Additional Code, As Required ... } // Deserialization Constructionor, Called by the soapformatter during DeSerialization Public Orderentity (SerializationInfo Info, StreamingContext CTXT) { // deserialize from the serializationInfo object to the orderientity Fields ORDERID = (int) info.getValue ("ORDERID", TypeOf (int)); // Additional Code, As Required ... } // Other members, as before ... } For More Information About Customized SOAP Serialization, See Basic Serialization. How To Serialize Business Entity Components to Binary Format The following code sample shows how to use the BinaryFormatter class to serialize an OrderEntity object to binary format. Binary serialization also occurs (implicitly) when you pass an object to or from a Remoting server by using a TCP remoting channel. In addition, to improve Performance, you can singy the http remoting channel.using system.runtime.serialization.formatters.binary; // for the Binaryformatter Class ... // Create a binaryformatter Object, To serialize Orderentity-Type Objects BinaryFormatter Formatter = new binaryformatter (); // serialize an orderentity Object to a binary file named "Mybinaryorderentity.dat" FileStream Stream = file.create ("MyBinaryOrdereentity.dat); Formatter.Serialize (stream, order); stream.close (); To use binary serialization for custom entity objects, you must annotate your custom entity class by using the Serializable attribute. To customize the binary format generated during serialization, your custom entity class must implement the ISerializable interface. The coding details in both scenarios are the same As for soap serialization. For more information about binary serialization, see binary serialization. Collaborators Many thanks to the following contributors and reviewers: Luca Bolognese, Mike Pizzo, Keith Short, Martin Petersen-Frey (PSS), Pablo De Grande, Bernard Chen (Sapient), Dimitris Georgakopoulos (Sapient), Kenny Jones, Chris Brooks, Lance Hendrix Pradyumna Siddhartha, Franco A. Ceruti (VBNext), Diego Gonzalez (Lagash), And Chris Schoon. Thanks, Also, To The Content Team: Chris Sfanos, Angela Crocker, Andy Olsen, And Sharon Smith.