1. Trang chủ
  2. » Công Nghệ Thông Tin

Tài liệu Module 4: Managing Transactions and State pptx

86 423 0
Tài liệu đã được kiểm tra trùng lặp

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Tiêu đề Managing Transactions and State
Trường học Microsoft Corporation
Chuyên ngành Computer Science
Thể loại Module
Năm xuất bản 2000
Thành phố Redmond
Định dạng
Số trang 86
Dung lượng 1,12 MB

Các công cụ chuyển đổi và chỉnh sửa cho tài liệu này

Nội dung

Contents Overview 1 The IObjectContext Interface 6 Lab 4.1 Using Context Object Services 15 Programming COM+ Transactions 38 Lab 4.2 Managing Transactions 48 Using the Shared Proper

Trang 1

Contents

Overview 1

The IObjectContext Interface 6

Lab 4.1 Using Context Object Services 15

Programming COM+ Transactions 38

Lab 4.2 Managing Transactions 48

Using the Shared Property Manager 59

Lab 4.3 Storing State in the Middle Tier 69

Review 76

Module 4: Managing Transactions and State

Trang 2

products, people, characters, and/or data mentioned herein are fictitious and are in no way intended

to represent any real individual, company, product, or event, unless otherwise noted Complying with all applicable copyright laws is the responsibility of the user No part of this document may

be reproduced or transmitted in any form or by any means, electronic or mechanical, for any purpose, without the express written permission of Microsoft Corporation If, however, your only means of access is electronic, permission to print one copy is hereby granted

Microsoft may have patents, patent applications, trademarks, copyrights, or other intellectual property rights covering subject matter in this document Except as expressly provided in any written license agreement from Microsoft, the furnishing of this document does not give you any license to these patents, trademarks, copyrights, or other intellectual property

 2000 Microsoft Corporation All rights reserved

Microsoft, BackOffice, MS-DOS, Windows, Windows NT, Intellisense, PowerPoint, and Visual Basic are either registered trademarks or trademarks of Microsoft Corporation in the U.S.A and/or other countries

The names of companies, products, people, characters, and/or data mentioned herein are fictitious and are in no way intended to represent any real individual, company, product, or event, unless otherwise noted

Other product and company names mentioned herein may be the trademarks of their respective owners

Trang 3

Instructor Notes

This module describes transactions and related concepts and issues Students learn to activate and deactivate components by using Just In Time (JIT) Activation and As Soon As Possible (ASAP) deactivation They will learn to use the Shared Property Manager (SPM) to manage state This module also covers best programming practices to increase application scalability and efficiency

After completing this module, students will be able to:

! Use the context object to retrieve information about a COM+ component

! Add transaction support for COM+ components by using the Component Services tool

! Enable JIT Activation for COM+ components

! Create COM+ components that support and manage distributed transactions

! Use the SPM to manage the application data referred to as state

! Describe some of the best practices when managing transactions and state

In the first two labs, students will learn how to use the context object services to retrieve information about the context object and to manage transactions In the third lab, students will use the Shared Property Manager to store state in the middle tier of the Purchase Order Online application

Materials and Preparation

This section provides you with the required materials and preparation tasks that are needed to teach this module

Required Materials

To teach this module, you need the following materials:

! Microsoft PowerPoint® file 1907A_04.ppt

! Module 4: Managing Transactions and State

! Lab 4.1: Using Context Object Services

! Lab 4.2: Managing Transactions

! Lab 4.3: Storing State in the Middle Tier

Preparation Tasks

To prepare for this module, you should:

! Read all of the materials for this module

! Complete the labs

! Read the instructor notes and the margin notes for the module

Presentation:

135 Minutes

Lab:

90 Minutes

Trang 4

Module Strategy

Use the following strategy to present this module:

! COM+ Context Discuss the concept of an object’s context and how each COM+ object is created with an associated context For components that do not use COM+ services, the context is largely ignored However, for components running inside COM+ applications, contexts are the foundation on which COM+ services are provided The context object information is exposed through

several interfaces on the ObjectContext object

! Just In Time Activation Discuss how JIT Activation is used to create an object when a COM+ component is instantiated JIT Activation helps make COM+ solutions scalable by activating objects as they are required and by preventing idle objects from consuming valuable resources on the server

! Managing Transactions Discuss how transactions can be managed automatically by using COM+ services Describe the purpose of transactions in an enterprise solution Transactions are required to maintain data integrity and to synchronize updates to data in multiple data sources

! Programming COM+ Transactions Explain that sometimes developers need to control transactions programmatically even though they can be managed declaratively through COM+ services The main reason for programming COM+ transactions is to gain a greater degree of control over the process For example, a component may enforce a business rule that causes a transaction to abort if certain conditions arise, such as a balance transfer exceeding a specified maximum amount Discuss the context object interfaces and how they are used to program COM+ transactions

! Managing State Discuss that state refers to the data used within the business processes of an application When building enterprise solutions, managing state is a major design concern Explain that components can be stateful or stateless, and discuss the implications on component design resulting from state

! Using the Shared Property Manager Discuss how the SPM is a resource dispenser provided by COM+ to store transient shared data in a COM+ application The SPM allows you to retain global data between component activations and share it among all

component instances in the COM+ application process

! Best Practices Summarize all the best practices taught in the module

Trang 5

Demonstration

This section provides demonstration procedures that will not fit in the margin notes or that are not appropriate for the student notes

Using the ObjectControl Interface

! Explain the demonstration scenario

• The demonstration scenario is based on the Northwind database A COM+ application is used to discontinue products that are no longer available The client application calls a component named Traders, which invokes its

DiscontinueProduct method The Traders component calls a component named EventLog, invoking its LogEvent method to record the name of the

user discontinuing the product Next, Traders calls a component named

Product, which invokes its Discontinue method to update the Products

table If an error occurs, Traders calls a component named ErrorLog,

invoking its LogError method to record the error information and the

ActivityID of the COM+ activity

! Run the test client

1 Run the NwindClient.exe client application from the <install

folder>\Democode\Mod04\NorthwindClient folder

2 Enter a number below 100 and click Discontinue A message will confirm

the discontinued product

3 Enter a number over 200 and click Discontinue An error message will be

displayed

! Examine the database

1 Start Enterprise Manager from the Microsoft SQL Server 7.0 program group

2 Expand the nodes in the Tree pane to view the tables in the Northwind database

3 View the contents of the EventLog table and note the name of the user recorded there by the Traders component

4 View the contents of the ErrorLog table and note the ActivityID recorded there by the Traders component

! Examine the component code

1 Open Northwind.vbp in the <install

Trang 6

4 Under the comment Get a reference to the Object Context, add the

following code:

Set objCtx = COMSVCSLib.GetObjectContext

5 Point out the following line of code:

strUser = "Graeme" 'Get name from ISecurityProperty

6 Change this line to the following:

strUser = objCtx.Security.GetOriginalCallerName

7 Point out the following line of code in the error handler:

strActivity = "{00000000-0000-0000-0000-000000000000}"

8 Change the code to:

strActivity = objCtx.ContextInfo.GetActivityID

9 Save and recompile the component (you may need to shut down the Northwind COM+ application) and close Microsoft Visual Basic

! Run the test client

1 Run the NwindClient.exe client application from the <install

folder>\Democode\Mod04\NorthwindClient folder

2 Enter a number below 100 and click Discontinue A message will confirm

the discontinued product

3 Enter a number over 200 and click Discontinue An error message will be

displayed

! Examine the database

1 Start Enterprise Manager from the SQL Server 7.0 program group

2 Expand the nodes in the Tree pane to view the tables in the Northwind database

3 View the contents of the EventLog table and note the name of the user recorded there by the Traders component

4 View the contents of the ErrorLog table and note the ActivityID recorded there by the Traders component

Managing Transactions

! To prepare for the demonstration

! Ensure the SetupDemos.cmd file has been executed as previously described

! Run the test client

1 Run the NwindClient.exe client application from the <install

folder>\Democode\Mod04\NorthwindClient folder

2 Enter a number below 100 and click Discontinue A message will confirm

the discontinued product

3 Enter a number over 200 and click Discontinue An error message will be

displayed

Trang 7

! Examine the database

1 Start Enterprise Manager from the SQL Server 7.0 program group

2 Expand the nodes in the Tree pane to view the tables in the Northwind database

3 View the contents of the EventLog table and note that events have been recorded for product updates that did not take place Explain that the reason

is that the business process is not atomic

! Configure the COM+ components

1 Open the Component Services administration tool and display the properties

of the components in the Northwind application

2 Point out that the Traders component does not support transactions Change

its Transaction support attribute to Required

3 Ask students to explain why the Transaction support property of the

ErrorLog component is set to Requires New

4 Shut down the Northwind application and close Component Services

! Add code to commit or abort the transaction

1 Open Northwind.vbp in the <install

4 Add the following line of code under the comment Abort Transaction:

objCtx.SetAbort

5 Save and recompile the project and close Visual Basic

! Run the test client

1 Run the NwindClient.exe client application from the <install

folder>\Democode\Mod04\NorthwindClient folder

2 Enter a number below 100 and click Discontinue A message will confirm

the discontinued product

3 Enter a number over 200 and click Discontinue An error message will be

displayed

! Examine the database

1 Start Enterprise Manager from the SQL Server 7.0 program group

2 Expand the nodes in the Tree pane to view the tables in the Northwind database

3 View the contents of the EventLog table and note that events have not been recorded for product updates that did not take place Explain that the reason

is that the business process is not an atomic transaction

Trang 9

# Overview

! COM+ Context

! Lab 4.1: Using Context Object Services

! Just In Time(JIT) Activation

! Managing Transactions

! Programming COM+ Transactions

! Lab 4.2: Using Context to Manage Transactions

! Managing State

! Using the Shared Property Manager

! Lab 4.3: Storing State in the Middle Tier

! Best Practices and Review

In this module, you will learn how to use the context object to obtain security, transactional, and other information about COM+ components You will learn how COM+ uses Just In Time (JIT) Activation to free system resources and improve performance You will also learn how to manage distributed transactions both declaratively and programmatically Finally, you will learn how to manage state by using the Shared Property Manager (SPM)

Objectives

After completing this module, you will be able to:

! Use the context object to retrieve information about a COM+ component

! Add transaction support for COM+ components by using the Component Services tool

! Enable JIT Activation for COM+ components

! Create COM+ components that support and manage distributed transactions

! Use the Shared Property Manager to manage the application data referred to

as state

Trang 10

# COM+ Context

! Overview of the Context Object

! Interfaces for the Context Object

! The IObjectContext Interface

! The IContextInfo Inteface

! The ISecurityProperty Interface

! The IContextState Interface

! Demonstration: The Context Object

Every COM object is created with an associated context For components that

do not use COM+ services, the context is largely ignored However, for components running inside COM+ applications, contexts are the foundation on which COM+ services are provided The context object information is exposed

through an object named ObjectContext

This section includes the following topics:

! Overview of the Context Object

! Interfaces for the Context Object

! The IContextInfo Interface

! The ISecurityProperty Interface

! The IContextState Interface

! Demonstration: The Context Object

Trang 11

Overview of the Context Object

Client

COM+ Component

Context

The data that COM+ uses to keep track of what each object is doing is referred

to as an object's context Each context must be associated with a particular context object that monitors its properties The context object, which is named

ObjectContext, maintains information about the object and its current status,

including:

! Whether the object is involved in a transaction

! What the object is currently doing

! The security level of the component

! The identity of the object’s caller

! Security role membership of the object’s caller

! A Done flag to control the object’s activation and lifetime

! A Consistency flag to control transactional behavior

Shared Context

When an object is instantiated, it is either associated with an existing context or

a new context is created for it If a client program creates an instance of a COM+ component, a new context will be created for the component If the COM+ component then instantiates another component with a compatible configuration, the new component will be created in the same context The following illustration shows the relationship between the client, the COM+ components, and the associated shared context

Trang 12

be created for the called component because each transactional component requires its own context to vote on the transaction outcome However, the

TransactionID and ActivityID properties will be inherited from the calling

context so that the new component can participate in the same transaction and the same logical business process The following illustration shows how the new component inherits certain properties from the calling component

In this illustration, the calling component creates a second component that requires its own context The new context inherits some properties from the calling context despite having it has its own separate context

Trang 13

Interfaces for the Context Object

Dim objCtx As COMSVCSLib.ObjectContext Dim objInfo As COMSVCSLib.ContextInfo Dim objSec As COMSVCSLib.SecurityProperty Dim objSt As COMSVCSLib.IContextState Set objCtx = COMSVCSLib.GetObjectContext() Set objInfo = objCtx.ContextInfo

Set objSec = objCtx.Security Set objSt = objCtx

ObjectContext

IObjectContext

IContextState

ContextInfo SecurityIUnknown

The context object provides a number of interfaces that can be used to retrieve context information and control the object’s behavior

You can retrieve most context information that you will need by using the

IObjectContext interface This interface provides a wide range of methods and

properties that you can use to create an instance of a component, retrieve security information, and retrieve and manage transactions This interface can

be obtained programmatically by using the GetObjectContext function, which

is provided by COM+

The IObjectContext interface contains two properties that are themselves objects These objects are the ContextInfo and Security objects and they implement the IContextInfo and ISecurityProperty interfaces, respectively The IContextInfo interface provides methods and properties relating to the

status of the context, including the Context ID, the GUID identifying the activity to which the object instance belongs and other useful logging information

The ISecurityProperty interface provides information about the caller’s

identity and is also useful for logging You should note however that the

ISecurityProperty interface is provided mostly for backward compatibility with MTS and that a separate interface named ISecurityCallContext provides

a more flexible approach to programmatic security

Finally, the ObjectContext object also implements an interface named IContextState that provides methods for controlling object lifetime and transactions This interface can be obtained by calling GetObjectContext or by assigning an IContextState variable to an instantiated ObjectContext object

Each of these interfaces is discussed in more detail later in this section

Trang 14

The IObjectContext Interface

! Methods of the IObjectContext Interface

Dim objCtx As COMSVCLib.ObjectContext Set objCtx = GetObjectContext

If objCtx.IsInTransaction Then

‘Do Something End If

The IObjectContext interface provides the methods described in the following

table

Method Description CreateInstance Creates an instance of another COM+ component (method

required for backward compatibility with code written for Microsoft Transaction Server only)

DisableCommit Prevents a transaction from committing temporarily

EnableCommit Allows a transaction to commit

IsCallerInRole Checks the role membership of the caller

IsInTransaction Determines whether the object is in a transaction

IsSecurityEnabled Determines if security checking is enabled for the

component

SetAbort Declares that a transaction must be aborted

SetComplete Declares a component as ready to commit the transaction

The IObjectContext interface provides the properties described in the

following table

Property Description ContextInfo Provides an object with further methods and properties relating to

the context

Count Returns the number of named context object properties

Item Returns a specific named property

Security Provides an object with further methods and properties relating to

security

Trang 15

Accessing the Context Object

To access the ObjectContext object, you must set a reference to the COM+ Services Type Library Afterward, you can access the ObjectContext object by using the GetObjectContext method, as shown in the following code

If GetObjectContext.IsInTransaction Then ' Do Something

Else ' Do Something Else End If

You can either use the GetObjectContext method each time you need to access the ObjectContext object or you can declare a variable of type

COMSVCLib.ObjectContext and instantiate it by using the GetObjectContext

method You can then use the variable to access the properties and methods of

ObjectContext, as shown in the following code:

Dim objCtx As COMSVCLib.ObjectContext Set objCtx = GetObjectContext

If objCtx.IsInTransaction Then 'Do Something

End If

Trang 16

The IContextInfo Interface

! Methods of the IContextInfo Interface

Methods of the IContextInfo Interface

The IContextInfo interface provides the following methods

Method Description IsInTransaction Determines whether the object is in a transaction (The same

method is available on the Context object.)

GetTransaction Retrieves a pointer to the ITransaction interface of the

current transaction (This interface does not support Automation from Microsoft Visual Basic®.)

GetTransactionID Retrieves a unique value identifying the transaction (if any)

in which the object is participating

GetActivityID Retrieves a unique value identifying the activity of which the

object is a part

GetContextID Retrieves a unique value identifying the context object

Accessing ContextInfo Methods

You can access the methods of the ContextInfo object through the ObjectContext as shown in the following code:

Dim objCtx As COMSVCSLib.ObjectContext Dim strActID As String

Set objCtx = GetObjectContext strActID = objCtx.ContextInfo.GetActivityID

Trang 17

Alternatively, you can declare a variable of type COMSVCSLib.ContextInfo

and instantiate it by using the ContextInfo property of the ObjectContext as

shown in the following code:

Dim objCtx As COMSVCSLib.ObjectContext Dim objCtxInfo As COMSVCSLib.ContextInfo Dim strActID As String

Set objCtx = GetObjectContext Set objCtxInfo = objCtx.ContextInfo strActID = objCtxInfo.GetActivityID

Trang 18

The ISecurityProperty Interface

! Methods of the ISecurityProperty Interface

Methods of the ISecurityProperty Interface

The ISecurityProperty interface provides the following methods

Method Description GetDirectCallerName Retrieves the name of the user account of the process

calling this component directly

GetDirectCreatorName Retrieves the name of the user account of the process

that created this object (for backward compatibility with Microsoft Transaction Server)

GetOriginalCallerName Retrieves the name of the user account of the process

that started the current call chain

GetOriginalCreatorName Retrieves the name of the user account of the process

that created the object at the beginning of the call chain (for backward compatibility with Microsoft Transaction Server)

Trang 19

Accessing SecurityProperty Methods

You can access the methods of the ISecurityProperty interface through the ObjectContext object’s Security property, as shown in the following code

Dim objCtx as COMSVCSLib.ObjectContext Dim strUsrName as string

Set objCtx = GetObjectContext strUserName = objCtx.Security.GetOriginalCallerName

Alternatively, you can instantiate a variable of type COMSVCSLib.SecurityProperty by using the Security property of ObjectContext, as shown in the following code

Dim objCtx as COMSVCSLib.ObjectContext Dim objCtxScy as COMSVCSLib.SecurityProperty Dim strUsrName as string

Set objCtx = GetObjectContext Set objCtxScy = objCtx.Security strUsrName = objCtxScy.GetOriginalCallerName

You can also access security methods and properties through the

ISecurityCallContext interface This interface provides greater functionality than the ISecurityProperty interface and should usually be used to manage programmatic security For more information about the ISecurityCallContext

interface, see Module 8: Making Applications Secure

Note

Trang 20

The IContextState Interface

! Methods of the IContextState interface

$ SetDeactivateOnReturn

$ SetMyTransactionVote

$ GetDeactivateOnReturn

$ GetMyTransactionVote

! Used to control activation and transactions

The IContextState interface is a COM interface that contains methods to control the Done and Consistency flags Although these flags are usually set by using the SetComplete, SetAbort, DisableCommit, and EnableCommit methods of the ObjectContext interface, you can get a finer level of control by using the IContextState interface The SetComplete, SetAbort,

DisableCommit, and EnableCommit methods of the ObjectContext interface

are discussed later in this module

Methods of the IContextState Interface

The IContextState interface provides the following methods

Method Description SetDeactivateOnReturn Sets the Done flag

SetMyTransactionVote Sets the Consistency flag GetDeactivateOnReturn Returns the value of the Done flag

GetMyTransactionVote Returns the value of the Consistency flag

Accessing the IContextState Interface

The IContextState interface is implemented by the ObjectContext class You can access the IContextState interface by instantiating a variable of type COMSVCSLib.IContextState, either by using the GetObjectContext function

or by using an already instantiated ObjectContext object variable

You can use the GetObjectContext function to instantiate the IContextState

interface, as shown in the following code

Dim objCxSt As COMSVCSLib.IContextState Set objCxSt = GetObjectContext

Trang 21

Alternatively, you can access the IContextState interface through an already instantiated ObjectContext object, as shown in the following code

Dim objCx As COMSVCSLib.ObjectContext Dim objCxSt As COMSVCSLib.IContextState Set objCx = GetObjectContext

Set objCxSt = objCx

Trang 22

Demonstration: The Context Object

In this demonstration, you will be shown how to access the IObjectContext, ISecurityProperty, and IContextInfo interfaces by using the ObjectContext

object

Delivery Tip

The step-by-step

instructions for this

demonstration are in the

instructor notes for this

module

Trang 23

Lab 4.1 Using Context Object Services

In this lab, you will use the services of the context object in the POBusiness.bus_Order component The context object provides information about the context of the current object instance You will use some of this information to identify the user who is calling the component

Objectives

After completing this lab, you will be able to:

! Use properties of the context object

! Exercise 1: Using the Security Property

In this exercise, you will use the Security property of the context object to

identify the user who is calling the component

In this lab, you will use the

services of the context

object in the

POBusiness.bus_Order

component to identify who is

calling the component

Trang 24

Exercise 1:

Using the Security Property

In this exercise, you will use the Security property of the context object to

identify the user who is calling the component

! Set a reference to the COM+ Services Type Library

1 Open the POBusiness.vbp project that you saved in Lab 3.2 If you did not

complete Lab 3.2, open the POBusiness.vbp project in <install

folder>\Labs\Lab04\POBusiness

2 On the Project menu, click References

3 Select the COM+ Services Type Library check box

4 Click OK

! Declare a variable for the security property

In this procedure, you will display the code window for the bus_Order class

module, and in the Raise method, declare the following variables:

1 Declare a variable objCtx of type COMSVCSLib.ObjectContext

2 Declare a variable objSec of type COMSVCSLib.SecurityProperty

! Use the security object

In this procedure, you will replace the code strUser = “Student” with code to

do the following:

1 Instantiate objCtx by using the GetObjectContext function

2 Instantiate objSec by assigning it to the Security property of objCtx

3 Use the GetOriginalCallerName method of objSec to assign a value to

strUser

! Test the component

1 Compile the POBusiness.dll in the same folder as the project and save the project (If Visual Basic cannot overwrite the existing DLL, use the Component Services administrative tool to shut down the Purchase Order COM+ application)

2 Close Visual Basic

3 Use the Web-based Purchase Order Online application to place an order

4 Note the order number when it is displayed

5 On the Start menu, point to Programs, Microsoft SQL Server 7.0, and then click Query Analyzer

6 Log on to the (local) SQL Server and use Windows NT Authentication

7 In the Query window, select PurchaseOrderSystem from the DB

drop-down list

Trang 25

8 Enter the following SQL query in the Query window, and then click

Trang 26

# Just In Time Activation

! Introduction to JIT Activation

! Enabling JIT Activation

! Using the ObjectControl Interface

When a COM+ component is instantiated, a process known as Just In Time (JIT) Activation is used to create the object JIT Activation helps make COM+ solutions scalable by activating objects as they are required and preventing idle objects from consuming valuable resources on the server

This section includes the following topics:

! Introduction to JIT Activation

! Enabling JIT Activation

! Using the ObjectControl Interface

Trang 27

Introduction to JIT Activation

If a client instantiates a COM+ component, the instance of the component is created in a context When this event happens, the instance is said to be activated An active object runs on a thread in the COM+ application When a component instance is not in use, COM+ can deactivate it until it is required When a component is deactivated, it frees the resources being used by the object When the client calls a method on the object, the instance is reactivated

to run the method

When a component instance is deactivated, the client retains a reference to the object until the object variable is set to nothing or goes out of scope When subsequent calls are made to methods of the object, a new activation occurs The above illustration shows a component using JIT Activation

Trang 28

Enabling JIT Activation

By default, all COM+ components support JIT Activation You can manually

enable or disable JIT Activation from the Activation tab of the component Properties dialog box in the Component Services administration tool The above illustration shows the Properties dialog box with the Activation tab

selected:

Components that support transactions must also support JIT Activation

An object will be deactivated at the end of a method call if the Done flag in the object’s context has been set to True You can set the Done flag by writing code to call the SetComplete and SetAbort methods of the ObjectContext object, or the SetDeactivateOnReturn method of the IContextState interface

This code will tell COM+ that the object has completed all requested processing and can be deactivated when the method call returns

Note

Trang 29

You can also configure methods so that they automatically set the Done flag when returning by setting the Auto-Done property This option is sometimes

called As Soon As Possible (ASAP) Deactivation To automatically set the

Done flag, check the Automatically deactivate this object when this method returns check box on the Properties page for the method in the Component

Services administration tool, as shown in the following illustration:

Trang 30

Using the ObjectControl Interface

! Activating and deactivating components in Visual Basic

Implements COMSVCSLib.ObjectControl Private Sub ObjectControl_Activate() Set objCtx = GetObjectContext Set objCtxInfo = objCtx.ContextInfo StrActID = objCtxInfo.GetActivityID End Sub

Private Function ObjectControl_CanBePooled() As Boolean ObjectControl_CanBePooled = False

End Function Private Sub ObjectControl_Deactivate() Set objCtxInfo = Nothing

Set objCtx = Nothing End Sub

To write efficient and scalable applications, you need to write code to initialize variables when an object is instantiated and to clean up variables and object references when an object terminates In Visual Basic class modules, this code

is usually written in the Initialize and Terminate event procedures

When JIT Activation is used, the Initialize event fires when a new component

instance is instantiated However, the first activation does not occur until a

method is called or a property is set When a method returns with the Done flag set to True, COM+ deactivates the object and checks to see if the object

supports object pooling Object pooling is a way of recycling component instances for multiple clients If the object can be pooled, it is kept for another

client to use Otherwise, COM+ terminates the object and the Terminate event

fires The next time a method is called on object that is not pooled, the

Initialize event will occur again

Trang 31

Activating and Deactivating Components in Visual Basic

Components written in Visual Basic 6.0 do not support object pooling The reason is that the apartment-threading model used by Visual Basic is not compatible with the neutral threaded apartment model used for pooled objects However, if required, you can use Visual Basic to write code that runs when the

object is activated and deactivated by using the ObjectControl interface The ObjectControl interface provides three events, as described in the

following table

Event Description Activate Fires when a method is called on a deactivated object You can

use this event to initialize variables needed by the object

Deactivate Called when a component instance is deactivated Use this event

for any clean up code you require

CanBePooled Returns a Boolean indicating whether the object can be pooled

Because apartment-threaded components do not support object pooling, the value returned from this function is irrelevant

Generally, you should return False from this event procedure

when creating components with Visual Basic 6.0

Implementing the ObjectControl Interface

You can use the ObjectControl events to write initialization and clean-up code

To access these events, you must implement the ObjectControl interface in

your Visual Basic class First, set a reference to the COM+ Services Type

Library because it contains the definition of the ObjectControl interface You can then implement the ObjectControl interface in your Visual Basic class by

adding the following code to the General Declarations section:

Implements COMSVCLib.ObjectControl

This code will add the ObjectControl interface and its events to your Visual Basic class You can access the events by choosing ObjectControl from the

Object combo box in the Visual Basic Code Window You must create the

event procedure for each method on the interface of ObjectControl

Trang 32

Using the ObjectControl Interface

You can use the ObjectControl interface to initialize variables and clean up

variables after an object terminates, as shown in the following code:

Implements COMSVCSLib.ObjectControl Private objCtx As COMSVCSLib.ObjectContext Private objCtxInfo As COMSVCSLib.ContextInfo Private strActID As String

Private Sub ObjectControl_Activate() Set objCtx = GetObjectContext

Set objCtxInfo = objCtx.ContextInfo StrActID = objCtxInfo.GetActivityID End Sub

Private Function ObjectControl_CanBePooled() As Boolean ObjectControl_CanBePooled = False

End Function

Private Sub ObjectControl_Deactivate() Set objCtxInfo = Nothing

Set objCtx = Nothing End Sub

Trang 33

! Determining Transaction Outcome

! Observing Transaction Behavior

In an enterprise solution, transactions are often required to maintain data integrity and to synchronize updates to data in multiple data sources In this section, you will learn how transactions can be managed automatically by using COM+ services

This section includes the following topics:

! Introduction to Transaction Processing

! Distributed Transactions

! Managing Transactions Declaratively

! Processing Transactions

! Determining Transaction Outcome

! Observing Transaction Behavior

Trang 34

Introduction to Transaction Processing

This kind of all-or-nothing work management is called a transaction

Transactions are often defined in terms of their four primary characteristics by using the acronym ACID, which means atomicity, consistency, isolation, and durability

Atomicity

A whole transaction is considered to be one atomic unit of work All tasks within a transaction must be completed (or committed) If any task fails, the effect of all the other tasks in the transaction must be undone (or rolled back) For example, the balance transfer transaction described above consists of two tasks:

1 Add the specified amount of money to the target account

2 Deduct the specified amount from the source account

If step 2 fails for any reason (for example, if there are insufficient funds in the account), then the work done in step 1 must be rolled back (that is, the amount must not be added to the target account) Conversely, if step 1 fails, the work done in step 2 must be rolled back

Consistency

Data must be consistent with the business rules at the beginning and end of a transaction For example, if a business rule in the banking system states that no account can have a negative balance, then any transaction that would leave an account with a negative balance must be rolled back

Trang 35

Isolation

Data involved in a transaction must be isolated from activities outside of the transaction while the outcome is in doubt For example, if step 1 of the balance transfer transaction has been completed, no external activity should be allowed

to check the balance of the account until step 2 has also been completed

Databases usually enforce transaction isolation by placing locks on any records involved in a transaction

Durability

When a transaction is committed, the data involved in the transaction must be guaranteed to be recoverable in the event of a system failure Usually, this requirement necessitates storing the data in a durable medium such as on a disk Different data sources use different techniques to ensure durability; for

example, Microsoft SQL Server™ uses a write-ahead transaction log to ensure that all committed transactions are recoverable

Trang 36

Distributed Transactions

! Distributed Transaction Coordinator (DTC)

! Two-Phase Commit Protocol

When a transaction updates data in more than one Resource Manager or data source, it is called a distributed transaction Many aspects of a distributed transaction are identical to a transaction involving a single database For example, a distributed transaction enforces the ACID rules that define all transactions

What makes distributed transactions difficult to manage is that different Resource Managers may be used and each might have different ways of managing transactions The following illustration shows an example of a distributed transaction

A common approach to managing distributed transactions is to use a special piece of software, known as a Transaction Monitor, to coordinate the transaction The Transaction Monitor uses a protocol called two-phase commit

to ensure that all of the Resource Managers involved in the transaction commit

or rollback consistently Each Resource Manager is responsible for the details

of how ACID rules are enforced on that particular data source; the Transaction Monitor ensures that the ACID rules are enforced for the transaction as a whole

Trang 37

The following illustration shows the role of a Transaction Monitor in processing a transaction

Distributed Transaction Coordinator

Microsoft Windows 2000 includes a Transaction Monitor service called the Distributed Transaction Coordinator (DTC) This service allows COM+

components to use transactions when modifying data in distributed data sources

When a component requires a transaction, COM+ calls the BeginTransaction method on the ITransactionDispenser interface, which is provided by the DTC on the local computer The BeginTransaction method returns a Transaction object, which implements the ITransaction interface The Commit and Abort methods on the ITransaction interface are then used by

COM+ to control the transaction

When a transaction involves Resource Managers on remote computers, the Resource Managers each enlist with the DTC service on their local computer For this reason, the DTC service must be running on all computers hosting data sources for use in the enterprise solution The computer hosting the component

that started the transaction is known as the coordinating DTC The computers

hosting the resource managers are known as the enlisted DTCs

Trang 38

The following illustration shows how a distributed transaction can be coordinated by the DTC

Two-Phase Commit Protocol

When a COM+ application commits a transaction, the two-phase commit protocol is used to ensure that every Resource Manager commits and leaves the data in a consistent state As the name suggests, the two-phase commit protocol involves two steps

In the first phase, the coordinating DTC sends a query message to the DTC on each enlisted Resource Manager This message asks the Resource Managers to confirm that they are ready to commit the transaction When each Resource Manager is prepared, a confirmation message is returned to the coordinating DTC

In the second phase, the coordinating DTC sends a commit message to the DTC

on each Resource Manager if they all confirmed they were prepared or sends a rollback message if they did not The commit message instructs the Resource Manager to proceed and commit the transaction When the transaction is committed, each Resource Manager returns a done message to the coordinating DTC, as shown in the following illustration

Trang 39

Managing Transactions Declaratively

Many of the complexities of distributed transaction management are hidden from the developer by COM+ You can use the Component Services administrative tool to configure COM+ components to use distributed transactions with little or no programming effort This option makes it possible

to build complex, distributed applications relatively easily

Every COM+ component has a transaction support attribute that specifies whether the component supports transactions You can set the transaction

support attribute in the Transaction support frame on the Transactions tab of

the component Properties page in the Component Services administrative tool,

as shown in the above illustration

You can set transaction support to one of the following options

Option Description Supported The component will participate in the same transaction as the

client calling it If the client is not in a transaction, this component will not be transactional

Required The component will participate in the same transaction as the

client calling it If the client is not in a transaction, the COM+ run time will start a new transaction for this component

Requires New The component will not participate in the same transaction as

the client calling it COM+ will always start a new transaction for the component

Not Supported This component will never participate in a transaction

Disabled COM+ transaction management is disabled for this component

If it participates in a transaction, it will do so by calling the DTC directly

Trang 40

The MTSTransactionMode property of a Visual Basic class module affects the Transaction Support attribute of a component when it is added to a

COM+ application When the component has been added, changing the

MTSTransactionMode property has no effect on the component The

MTSTransactionMode property is primarily used by Visual Basic to emulate

appropriate COM+ behavior when debugging the component

Note

Ngày đăng: 21/12/2013, 19:15

TỪ KHÓA LIÊN QUAN