Scot Hillier’s COM+ Programming with Visual Basic
®
Scot Hillier
800 East 96th St., Indianapolis, Indiana, 46240 USA
Copyright
©
2000 by Sams Publishing
ASSOCIATE PUBLISHER
FIRST EDITION
Bradley L. Jones
All rights reserved. No part of this book shall be reproduced, stored in a retrieval system, or transmitted by any means, electronic, mechanical, photocopying, recording, or otherwise, without written permission from the publisher. No patent liability is assumed with respect to the use of the information contained herein. Although every precaution has been taken in the preparation of this book, the publisher and author assume no responsibility for errors or omissions. Neither is any liability assumed for damages resulting from the use of the information contained herein. For information, address Sams Publishing, A division of Macmillan Computer Publishing, 201 W. 103rd St., Indianapolis, IN 46290.
ACQUISITIONS EDITOR
International Standard Book Number: 0-672-31973-X
Sharon Cox
DEVELOPMENT EDITOR Susan Shaw Dunn
MANAGING EDITOR Charlotte Clapp
PROJECT EDITOR Paul Schneider
COPY EDITOR Rhonda Tinch-Mize
Library of Congress Catalog Card Number: 00-102598
INDEXER
Printed in the United States of America
Chris Barrick
First Printing: September 2000 03
02
01
00
4
3
2
1
Interpretation of the printing code: the rightmost double-digit number is the year of the book’s printing; the rightmost single-digit, the number of the book’s printing. For example, a printing code of 98-1 shows that the first printing of the book occurred in 1998.
PROOFREADER Kimberly Campanello
TECHNICAL EDITOR Rick Anderson
TEAM COORDINATOR
Composed in Function Condensed, AGaramond and MCPdigital by Macmillan Computer Publishing
Meggo Barthlow
Trademarks
William Eland, Jr. Dan Scherf
All terms mentioned in this book that are known to be trademarks or service marks have been appropriately capitalized. Sams Publishing cannot attest to the accuracy of this information. Use of a term in this book should not be regarded as affecting the validity of any trademark or service mark.
SOFTWARE SPECIALISTS
INTERIOR DESIGNER Anne Jones
COVER DESIGNER
Warning and Disclaimer
Aren Howell
Every effort has been made to make this book as complete and as accurate as possible, but no warranty or fitness is implied. The information provided is on an “as is” basis. The author and the publisher shall have neither liability nor responsibility to any person or entity with respect to any loss or damages arising from the information contained in this book or from the use of the CD or programs accompanying it.
LAYOUT TECHNICIANS Ayanna Lacey Heather Hiatt Miller Stacey Richwine-DeRome
Contents at a Glance Part I
Understanding COM+ Applications
1
Windows DNA and COM+
2
Administering COM+
3
Designing COM+ Applications
4
COM+ Application Fundamentals
Part II
9
27
Accessing Data with COM+
6
COM+ Data Components
7
COM+ Transactions
149
Business Services COM+ Security
9
COM+ Business Features
Part IV
113
181
8
10
83
Data Services
5
Part III
53
207 231
Asynchronous COM+ Applications
255
User Services
11
COM+ and the Internet
12
COM+ and Win32
13
Integrating COM+ with Groupware
14
Debugging and Deploying COM+ Applications
15
COM+ Catalog Administration
Part V
281
311 331 353
377
PubsOnLine.com
16
Designing the PubsOnLine.com Application
17
Building the PubsOnLine.com Application Index
449
391 417
Contents INTRODUCTION 1 How This Book Is Organized ..................................................................1 Part I: Understanding COM+ Applications........................................1 Part II: Data Services..........................................................................2 Part III: Business Services..................................................................3 Part IV: User Services ........................................................................3 Part V: PubsOnLine.com ....................................................................4 Conventions Used in This Book ..............................................................5
PART I
UNDERSTANDING COM+ APPLICATIONS
7
1
WINDOWS DNA AND COM+ 9 Windows 2000 Services ........................................................................11 Active Directory ..............................................................................12 Internet Information Server 5.0 ........................................................12 Message Queuing ............................................................................14 Universal Data Access ......................................................................14 XML Support....................................................................................14 Network Load Balancing..................................................................16 Component Services ........................................................................16 Tiered Architecture Overview................................................................18 Two-Tier Architecture ......................................................................19 Three-Tier Architecture ....................................................................21 Establishing a Test Environment ..........................................................23 Windows 2000 Advanced Server......................................................24 SQL Server 2000 ..............................................................................26 Visual Studio ....................................................................................26
2
ADMINISTERING COM+ 27 The Component Services Explorer........................................................28 Computer Properties ........................................................................29 Application Properties ......................................................................34 The System Application ..................................................................40 Creating Applications ......................................................................40 Component Properties ......................................................................42 Installing COM+ Components into an Application ........................46
3
DESIGNING COM+ APPLICATIONS 53 Assessing Functional Requirements ......................................................54 Problem Statement............................................................................54 Gathering Requirements ..................................................................55 Assessing Requirements ..................................................................57
Describing the System ..........................................................................58 Identifying Actors and Use Cases ....................................................59 Documenting the Use Cases ............................................................60 Flow Charts ......................................................................................64 Creating the Paper Prototype ................................................................65 System Modeling..............................................................................66 Database Model ................................................................................66 Logical Model ..................................................................................67 Three-Tier Diagram..........................................................................69 4
PART II 5
COM+ APPLICATION FUNDAMENTALS 83 Understanding Contexts ........................................................................84 Object Activation ..................................................................................88 Communicating with the Context ....................................................93 State Management ............................................................................96 The ObjectControl Interface ............................................................99 Managing Shared Properties................................................................102 SharedPropertyGroupManager ................................................102 SharedPropertyGroup................................................................102 SharedProperty ..........................................................................103 DATA SERVICES
111
ACCESSING DATA WITH COM+ 113 OLEDB Session Pooling ....................................................................114 Controlling the Number of Pools ..................................................115 Tuning Session Pooling ..................................................................117 Understanding Data Transportation ....................................................123 Understanding Cursors ..................................................................123 Understanding Transports and Payloads ........................................125 Delimited Strings............................................................................126 Variant Arrays ................................................................................127 Disconnected Recordsets................................................................129 Property Bags ................................................................................131 Conclusion ......................................................................................134 XML ....................................................................................................134 XML Fundamentals........................................................................135 The Stream Object..........................................................................139 Web Services and SOAP ................................................................141 Updating Records ................................................................................142 Handling Collisions ........................................................................143
vi
SCOT HILLIER’S COM+ PROGRAMMING
WITH
VISUAL BASIC
6
COM+ DATA COMPONENTS 149 Encapsulating Stored Procedures ........................................................151 Parameter Passing ................................................................................154 Strong Function Signatures ............................................................154 Variant Arrays ................................................................................155 XML ..............................................................................................158 Error Handling ....................................................................................161 Polymorphic Interfaces ........................................................................163 Understanding Polymorphism ........................................................164 Creating Standards..........................................................................165 The DNA Payload................................................................................167 Overview ........................................................................................169 Dataset Properties and Methods ....................................................169 Field Object Properties ..................................................................170 Passing Parameters with the DNA Payload ..................................170 Returning Data with the DNA Payload..........................................173 Displaying HTML with the DNA Payload ....................................174 Conclusion ..........................................................................................175
7
COM+ TRANSACTIONS 181 Understanding Transaction Attributes ................................................182 The Microsoft Distributed Transaction Coordinator ..........................183 Transactional Components ..................................................................184 Understanding Transaction Context ..............................................185 Voting in Transactions ....................................................................190 Monitoring Transactions ......................................................................198
PART III 8
BUSINESS SERVICES
205
COM+ SECURITY 207 Distributed Security ............................................................................208 Certificates......................................................................................208 Kerberos Protocol ..........................................................................209 Active Directory ..................................................................................210 Single Sign-On ..............................................................................211 Microsoft Installer ..........................................................................211 Personalization................................................................................212 Active Directory Services Interface ....................................................213 Using ADSI ....................................................................................213 Manipulating Properties ................................................................216 Authenticating Users ......................................................................220 COM+ Security Features ....................................................................222 Declarative Security ......................................................................222 Programmatic Security ..................................................................223 Conclusion ..........................................................................................226
CONTENTS 9
COM+ BUSINESS FEATURES 231 The COM+ Event System....................................................................232 Event Classes..................................................................................233 Event Subscribers ..........................................................................234 Event Publishers ............................................................................237 Filtering Events ..............................................................................238 COM+ Constructors ............................................................................238 Compensating Resource Manager System ..........................................242 CRM Workers ................................................................................242 CRM Clerks....................................................................................243 Compensating Resource Managers ................................................245 CRM Issues ....................................................................................249
10
ASYNCHRONOUS COM+ APPLICATIONS 255 The Microsoft Message Queue............................................................256 MSMQ Applications ............................................................................258 MSMQApplication Object ............................................................258 MSMQQuery Object ......................................................................259 MSMQQueueInfos Object..............................................................260 MSMQQueueInfo Object ..............................................................260 MSMQQueue Object......................................................................261 MSMQEvent Object ......................................................................261 MSMQMessage Object ..................................................................262 MSMQ Limitations ........................................................................264 Queued Components............................................................................265 Designing Queued Components ....................................................266 Calling Queued Components..........................................................268 Using Queued Components in Transactions ..................................271 Exception Classes ..........................................................................272
PART IV 11
USER SERVICES
279
COM+ AND THE INTERNET 281 New Internet Information Server Features ..........................................282 Isolating Internet Applications ......................................................282 Generating Custom Error Messages ..............................................285 Using Scriptless ASP......................................................................290 Creating Transactional Web Pages ......................................................290 Understanding Transactional Attributes ........................................290 Creating Multi-Page Transactions ..................................................292 Creating Classes in Scripts ............................................................294
vii
viii
SCOT HILLIER’S COM+ PROGRAMMING
WITH
VISUAL BASIC
Accessing ASP Objects with COM+ Components..............................298 Understanding XSL Style Sheets ........................................................300 XSL Fundamentals ........................................................................300 XSL Templates ..............................................................................302 XSL Elements ................................................................................305 12
COM+ AND WIN32 311 Maintaining Application State ............................................................312 Custom Collections ........................................................................314 Data Binding ..................................................................................315 User Interface Strategies......................................................................319 ActiveX Controls............................................................................319 HTA Pages ......................................................................................324
13
INTEGRATING COM+ WITH GROUPWARE 331 Integrating Exchange 2000 Server with COM+..................................332 Understanding Web Storage ..........................................................332 ActiveX Data Objects: Accessing Web Stores ..............................334 Collaboration Data: Using Contact and Message Objects ............336 Integrating Microsoft Outlook 2000 with COM+ ..............................338 The Outlook Design Environment ................................................340 Coding Outlook Items ....................................................................343 Integrating Digital Dashboards with COM+ ......................................348
14
DEBUGGING AND DEPLOYING COM+ APPLICATIONS 353 Debugging COM+ Components ..........................................................354 Debugging in Visual Basic ............................................................354 Debugging in Visual InterDev ........................................................355 Deploying COM+ Applications ..........................................................356 Deploying Data Services ................................................................357 Deploying Business Services ........................................................357 Deploying User Services ................................................................359 Deployment Checklist ....................................................................362 Analyzing COM+ Applications ..........................................................363 The Testing Process........................................................................364 Assessing Performance ..................................................................366 Load Balancing ..............................................................................367
15
COM+ CATALOG ADMINISTRATION 377 The COM+ Administration Object Model ..........................................378 The COMAdminCatalog Object ....................................................378 The COMAdminCatalogCollection Object................................380 The COMAdminCatalogObject Object ........................................382
CONTENTS Performing COM+ Administration with the Windows Scripting Host....................................................................................383 The WScript Object........................................................................384 The Shell Object ............................................................................385
PART V
PUBSONLINE.COM
389
16
DESIGNING THE PUBSONLINE.COM APPLICATION 391 Problem Statement ..............................................................................392 Gathering Requirements ......................................................................392 Membership and Personalization ..................................................393 Promotions......................................................................................393 Analysis ..........................................................................................393 Identifying Actors and Use Cases........................................................393 Log In ............................................................................................394 Add Book to Cart ..........................................................................397 View Cart........................................................................................399 Checkout ........................................................................................401 Screen Shots and the Paper Prototype ................................................403 Data Model ..........................................................................................407 System Models ....................................................................................408 The Three-Tier Model ....................................................................408 Log In ............................................................................................410 Add Book to Cart ..........................................................................412 Check Out ......................................................................................414 Defining Components ..........................................................................415
17
BUILDING THE PUBSONLINE.COM APPLICATION 417 Development Environment ..................................................................418 Creating the Database ..........................................................................419 Creating the COM+ Components ........................................................425 Data Services ..................................................................................428 Business Services ..........................................................................436 Deploying Components ..................................................................440 Creating the Web Interface ..................................................................445 Index
449
ix
About the Author Scot Hillier is the director of technical staff for DataLan Corporation. With offices in White Plains and New York City, DataLan offers broad expertise in strategic consulting, networking, communications, IT security, network management, line of business solutions, and knowledge management solutions. Scot has written several books, including MTS Programming with Visual Basic (Sams Publishing) and Inside Microsoft Visual Basic Scripting Edition (Microsoft Press). In addition to writing, Scot is a regular speaker at industry events such as VBITS and Developer Days. Scot can be reached at
[email protected].
Dedication Illegitimi non Carborundum
Acknowledgments Only an overdue software project can make you appreciate people as much as writing a book. In the same way that great software requires a great team, creating a book is the work of many people. I am always amazed that my name gets prominently displayed when I am but a part of the effort. I would first like to thank Sharon Cox, my acquisitions editor. Sharon has been the “go-to” person for both of my books with Sams. She has not only ensured the success of the process, but also has been exceedingly patient with me. Through contracts and politics, she kept her eye on just one thing—producing a quality book. Thank you. Susan Dunn, my development editor, is the embodiment of professional publishing. While juggling many different books, she kept me focused and provided excellent input. Rhonda Tinch-Mize was the copy editor who meticulously corrected my misuse of passive voice, commas, dashes, and capitalized words. Without her, the book would be far less readable. Paul Schneider was the project editor. I would like to give a special mention to Rick Anderson, the technical editor, who was forced to work every exercise in the book. Thank you to the team. As I get older, I learn to appreciate my wife, Nancy, more and more. This past year was certainly turbulent for our family. Nancy began a job as an elementary school teacher after 13 years of raising our children. She now teaches at the school where our kids, Ashley and Matthew, are students. In fact, she is our daughter’s sixth-grade teacher. As for myself, I changed jobs after five years, and in the middle of it all was the book. Thank you, family, for your support and understanding throughout everything. Many more friends and family members regularly give advise and companionship. I am truly blessed to know people whose compassion is independent of my success, failure, disagreements, or hardships. The true ones are always there. Thanks again to everyone.
Tell Us What You Think! As the reader of this book, you are our most important critic and commentator. We value your opinion and want to know what we’re doing right, what we could do better, what areas you’d like to see us publish in, and any other words of wisdom you’re willing to pass our way. As an Associate Publisher for Sams, I welcome your comments. You can fax, email, or write me directly to let me know what you did or didn’t like about this book—as well as what we can do to make our books stronger. Please note that I cannot help you with technical problems related to the topic of this book, and that due to the high volume of mail I receive, I might not be able to reply to every message. When you write, please be sure to include this book’s title and author as well as your name and phone or fax number. I will carefully review your comments and share them with the author and editors who worked on the book. Fax: Email: Mail:
(317) 581-4770
[email protected]
Bradley L. Jones, Associate Publisher Sams Publishing 201 West 103rd Street Indianapolis, IN 46290 USA
Introduction Several years ago, when I was working on my second or third book, I asked a colleague, “What do developers want from a book?” He responded simply, “Code they can steal.” This advice has been a guiding principle for me in the creation of this book. This book is designed to get you started quickly creating business applications with COM+. The book isn’t intended to cover more theory than is necessary to start solving business problems. The primary audience for the book is the intermediate developer with a working knowledge of ActiveX components. This isn’t to say that beginners or advanced programmers won’t benefit from the content, but the ideal reader has struggled with Windows DNA architecture and is ready for some guidance. These readers should find plenty of code they can steal. This book assumes that you have a significant mastery of several key technologies. You should have a strong background in Visual Basic object principles. You should be able to create class modules with property procedures and methods compiled into a dynamic link library (DLL). You should also have a strong understanding of Visual InterDev for creating Active Server Pages (ASP) applications. Throughout the book, I develop a repeatable architecture for creating COM+ applications. This isn’t to say that mine is the only way to create COM+ applications. I have no doubt that some people will disagree, even vigorously, with the architecture described here. However, I like to think of this book as a contribution to the discussion of architecture based on Windows DNA 2000. If you follow the guidelines presented here, your application will work. In the end, I hope you will find the material presented here to help you create better business applications.
How This Book Is Organized If you’ve read MTS Programming with Visual Basic, you will find the format and presentation of this book to be familiar. Each chapter contains a narrative explanation sprinkled with “Quick Checks”—short exercises—to drive home a lesson. At the end of most chapters, you will find a complete exercise designed to bring many elements together.
Part I: Understanding COM+ Applications The four chapters in Part I introduce you to the fundamental concepts necessary to understand Windows DNA applications and COM+: • Chapter 1, “Windows DNA and COM+,” introduces you to Windows DNA and COM+ services. In an overview of tiered applications, you’ll learn the fundamentals of partitioning and the advantages of creating COM+ applications. You’ll also receive guidance for creating an appropriate test bed. This section helps you prepare for the exercises used throughout the rest of the book.
2
SCOT HILLIER’S COM+ PROGRAMMING
WITH
VISUAL BASIC
• Chapter 2, “Administering COM+,” explains all the administrative tasks associated with COM+. You’ll get an overview of all the available attributes for computers, applications, and components. You’ll see how to administer computers that run COM+. You’ll also learn how to take advantage of COM+ features at the application level. Administrative security information is presented to help you prevent unauthorized changes to your COM+ applications. Finally, this chapter details component attributes, to help you take advantage of resource and transaction management features for the components you create. • Chapter 3, “Designing COM+ Applications,” explains the design process for COM+ applications from problem statement to deployed application. You’ll learn about a methodology based on the Rational Unified Process that helps properly define COM+ applications. This methodology provides tangible outputs that you can use to successfully create applications. This chapter also presents an overview of the Unified Modeling Language (UML), which is used in later chapters to design COM+ applications. • Chapter 4, “COM+ Application Fundamentals,” presents the fundamental concepts behind COM+. This information forms the foundation for future chapters on specific features. You’ll learn the concept of a context, the fundamental container for a component under COM+. The context helps manage resources and transactions. This chapter also presents fundamental issues such as object activation and state management. You’ll see why building COM+ applications requires a thought process different from typical Visual Basic applications.
Part II: Data Services The three chapters in Part II detail the construction of a data services layer for your COM+ applications. You’ll learn proven data techniques to create transactional systems that scale. • Chapter 5, “Accessing Data with COM+,” presents the fundamentals of data access with COM+ components. It focuses on the use of ADO for data access, as well as on database connection pooling. The latter feature speeds data access by maintaining a pool of connections that can be reused. Also, COM+ applications require that data be transported between various components. This chapter explains how to move data between COM+ components efficiently. You’ll see several different options for creating and presenting data sets. • Chapter 6, “COM+ Data Components,” focuses on creating components specifically for data services. You’ll read about parameter passing and query encapsulation. You’ll learn to decouple the data access process from the business rules, as well as how to handle errors that occur during data access. This chapter also explains polymorphic interfaces within the context of data access. You’ll see how to use interfaces to simplify data access components and improve maintainability. • Chapter 7, “COM+ Transactions,” shows how to create, manage, and monitor transactions within your COM+ application. You’ll find out how the Distributed Transaction Coordinator (DTC) provides strong transactional control and how to access it from
INTRODUCTION
COM+. You’ll also see how transactional contexts allow your COM+ components to vote for the success or failure of a pending transaction.
Part III: Business Services The three chapters in Part III describe how to construct a middle tier for your COM+ applications. These chapters will help you secure your system and take advantage of new COM+ features: • Chapter 8, “COM+ Security,” addresses security for your COM+ applications and components. The Active Directory is the central security and profile database for application users. You’ll see how to use it to log users in to an application and then personalize the application for individual users. You’ll also learn about COM+’s role-based and programmatic security features, which allow you to limit access to the functions within a COM+ component. • Chapter 9, “COM+ Business Features,” presents several new features of COM+ that weren’t available in the Microsoft Transaction Server. For example, loosely coupled events allow your COM+ components to send event messages to other components. This system allows for greater flexibility and maintainability in you applications. Then there are constructors, special strings sent into a COM+ component when it’s activated. Constructors can be used to customize the behavior of any component. Finally, Compensating Resource Managers allow you to create components that can participate in transactions involving resources other than a database. This feature extends the transactional capabilities of COM+ to resources such as flat files. • Chapter 10, “Asynchronous COM+ Applications,” focuses on creating applications that perform work asynchronously. This allows you to build applications that process information as a batch. You’ll learn the fundamentals of the Microsoft Message Queue (MSMQ) and how to use it to set up asynchronous processing. Queued components are a new feature of COM+. Based on MSMQ, these components provide a simpler mechanism for integrating asynchronous applications into COM+.
Part IV: User Services The five chapters in Part IV help you to create both Internet and rich client front ends for your COM+ applications. You also will learn to improve the performance of your applications and deploy them easily to end users. • Chapter 11, “COM+ and the Internet,” focuses on features, services, and techniques that are particular to Internet development. Internet Information Server 5.0 provides several new features important to COM+ developers. You’ll learn the new security and isolation features available to your application. You’ll also learn about the new features of Active Server Pages and how to create transactional Web pages that use script to take advantage of COM+ features.
3
4
SCOT HILLIER’S COM+ PROGRAMMING
WITH
VISUAL BASIC
• Chapter 12, “COM+ and Win32,” presents information necessary to create rich client front ends for COM+ applications. Maintaining state in COM+ applications requires thought and planning. This chapter will show you basic strategies for using the client resources to efficiently maintain application state. However, Visual Basic forms aren’t the only choice for rich client interfaces. This chapter also will explain several alternatives to forms that are easier to maintain, but still provide full-featured user interfaces. • Chapter 13, “Integrating COM+ with Groupware,” focuses on using COM+ with the programmatic features of Microsoft Exchange 2000 and Outlook 2000. You can use Microsoft Exchange 2000 to create full-featured collaborative applications from COM+. This chapter will explain how to access the new Web storage facility with the Collaboration Data Objects. Outlook 2000 provides a simple way to create collaborative applications for the enterprise. In this chapter, you’ll learn some simple ways to create collaborative applications using the existing features of Outlook 2000. • Chapter 14, “Debugging and Deploying COM+ Applications,” investigates the issues surrounding deployment and performance analysis for your applications. Because quantifying performance has historically been difficult, you’ll learn how to use the Web Application Stress Tool to verify the performance of your COM+ application. Windows 2000 offers a new way to deploy COM+ applications by using the Windows Installer and group policies. Together these technologies allow network administrators to deploy applications to many desktops from a single server location. • Chapter 15, “COM+ Catalog Administration,” focuses on using the programmatic interface of COM+ services to easily create automated administration tools. In a discussion on the COM+ Catalog Administration object model, you’ll discover how to automate tasks such as application creation and component installation. This chapter also covers the Windows Scripting Host, about which you’ll learn the fundamentals of creating scripts to automate COM+ administration.
Part V: PubsOnLine.com In these last two chapters, you put all that you learned in the previous chapters to work by developing the PubsOnLine.com application. The completed application simulates an e-commerce bookstore that uses a shopping cart to gather and purchase books. This application is intended as a complete learning application that uses many of the features presented in the book. • Chapter 16, “Designing the PubsOnLine.com Application,” presents the design documentation for the application built in the next chapter. It also presents the application development lifecycle you should follow.
INTRODUCTION
• Chapter 17, “Building the PubsOnLine.com Application,” presents the actual code for the project designed in Chapter 16. After completing this chapter, you will have a working example that can be used as a pattern for your own COM+ development efforts.
Conventions Used in This Book The following typographic conventions are used in this book: • Code lines, commands, statements, variables, and any text you type or see onscreen appears in a monospace typeface. Bold monospace typeface represents what you need to type. • Placeholders in syntax descriptions appear in an italic monospace typeface. Replace the placeholder with the actual filename, parameter, or whatever element it represents. • Also in syntax, bracketed information, such as [Step IncrementVal], represents optional settings or values that you can include in your code if your program requires it. • Italics highlight technical terms when they’re being defined. • The ➥ icon is used before a line of code that is really a continuation of the preceding line. Sometimes a line of code is too long to fit as a single line on the page. If you see ➥ before a line of code, remember that it’s part of the line immediately above it. In addition to typographical conventions, the following special elements are used to set off various pieces of information and to make them easily recognizable:
NOTE Special notes augment the material you are reading in each chapter. They clarify concepts and procedures.
TIP You’ll find numerous tips that offer solutions to common problems as well as shortcuts.
CAUTION These warn you about pitfalls and other serious problems that might occur. Reading them will help you save time and trouble.
5
6
SCOT HILLIER’S COM+ PROGRAMMING
WITH
VISUAL BASIC
Key Principle These call out critical design concepts or implementation concerns that must be observed. Observing them will help you create better applications.
PART
Understanding COM+ Applications
I
IN THIS PART 1 Windows DNA and COM+ 2 Administering COM+
9
27
3 Designing COM+ Applications
53
4 COM+ Application Fundamentals
83
Windows DNA and COM+
IN THIS CHAPTER • Windows 2000 Services
11
• Tiered Architecture Overview
18
• Establishing a Test Environment
23
CHAPTER
1
10
Understanding COM+ Applications PART I
The Windows Distributed interNet Application 2000 (Windows DNA 2000) platform is Microsoft’s vision for creating scalable, maintainable, reliable Web-based applications. Throughout this book, I will examine various aspects of this vision, identify what parts are strong and what parts are weak. In the end, I will develop a complete methodology and architecture based on the Windows DNA concept that you can use to create your own e-commerce, business-to-business, and intranet applications. If you are already familiar with Windows DNA, you might want to skip this discussion. If you’ve never built a distributed application before, take the time to read this overview.
NOTE This chapter functions as an overview of new principles as well as a review of key concepts. Because subsequent chapters won’t spend time on these fundamental concepts, readers who are weak in these areas should consult other references before beginning this text.
Like many terms in the Microsoft lexicon, Windows DNA seems to change meaning from time to time. I’ve heard Microsoft personnel refer to Windows DNA as a tiered architecture as well as a set of services designed to support a tiered architecture. At one point, I even witnessed a presentation in which Microsoft personnel suggested that the term DNA was synonymous with Visual Studio. That would make Windows DNA an architecture, a set of services, and a set of development tools! It’s no wonder developers are often confused by the messages that come out of Redmond. With all these definitions in mind, I will define Windows DNA for the purposes of this book. I am partial to thinking of Windows DNA solely as a tiered architecture. To us, Windows DNA is a vision of creating tiered applications that result in outstanding performance. To support the creation of this architecture, Microsoft has provided a set of services we can take advantage of, and a set of tools to use when we construct our architecture. Before we begin, I should discuss the services and tools that live under the Windows DNA umbrella.
What About Microsoft.NET? As this book was going to print, Microsoft announced a new initiative named Microsoft.NET. By the time you read this book, you will already be inundated with information about the .NET initiative, however, that information might leave you confused about the role of COM+ in future development. Here, I’ll explain the positioning of .NET relative to COM+ as it’s currently being defined. Keep in mind, however, that no software was generally available for the .NET platform at the time of this writing. Therefore, the standard caveat applies: This could all change.
Windows DNA and COM+ CHAPTER 1
Perhaps the best way to understand the positioning of a .NET solution is to compare it to a Windows DNA solution. Windows DNA 2000 is the framework used to create three-tier applications targeting the Microsoft Windows 2000 platform. Windows.NET, on the other hand, unifies services on all platforms. This allows, for example, an application written in Visual Basic running on Windows 2000 to call a service across the Internet that was written in Java and runs on a Sun platform. This interoperability is accomplished through the extensive use of the Extensible Markup Language (XML) to facilitate cross-platform communication. The question you might ask is, Does this mean that COM+ is no longer relevant? The answer, of course, is no. COM+ is still a vital part of creating solutions for the Windows 2000 platform. However, it’s not now nor never was intended to be a crossplatform technology. Instead, you will use elements of the .NET framework to allow your COM+ applications to communicate with non-Microsoft services. Therefore, you will find the information in this book both relevant and useful as Microsoft begins to release tools for the .NET framework.
Windows 2000 Services Windows 2000 is the operating system that makes cutting-edge Windows DNA applications possible. Windows DNA, of course, didn’t originate with the release of Windows 2000; however, this new OS brings many strong features to the table. These new features form the set of services that we will use to create our Windows DNA applications. These services are packaged under several different versions of Windows 2000 including the Data Center Server, Advanced Server, Standard Server, and Professional Workstation.
NOTE Microsoft often refers to DNA services in Windows 2000 as Windows DNA 2000. The “2000” label is used to distinguish the set of tools and services from those available under Windows NT. In this book, I simply refer to all Microsoft-based tiered architecture as Windows DNA.
1 WINDOWS DNA AND COM+
Microsoft.NET is intended to be a framework that allows developers to create Webbased applications that integrate different Internet services regardless of the platform or language used by the services. From this perspective, the .NET framework is separate from COM+ because COM+ is specific to the Windows 2000 platform, whereas the .NET framework is platform independent.
11
12
Understanding COM+ Applications PART I
Active Directory One of the most significant new features of Windows 2000 is support for the Active Directory, a Lightweight Directory Access Protocol (LDAP) service that functions as a replacement for the old Windows Security Accounts Manager (SAM). This means that network administrators will now use the Active Directory to manage all users, groups, and computers on the enterprise. However, Active Directory is much more than just a replacement for the SAM. Active Directory is essentially a high-performance database optimized for read access. This database contains not only information about users, groups, and computers, but also tracks virtually any resource on the enterprise. Active Directory can be used to catalog enterprise printers, files, and other resources that can then be searched by clients. This means that users can search for a specific resource such as a color printer in the same building that uses legal sized paper. Active Directory also keeps track of specific user information. The profiles kept in the directory can include a wide variety of information from email addresses to your boss’s name. This information can then be published on the enterprise like a network yellow pages. Also, e-commerce sites can use Active Directory to store information about customers and then return it later to personalize the Web site. For users within the domain, Active Directory also serves as a single point of authentication. Active Directory can not only authenticate users when they log on in the morning, but it can also authenticate them before they access their email accounts on Microsoft Exchange or request pages from the corporate intranet. All of this is designed to make the network administrator’s life easier. Developers should always create software with Active Directory in mind when targeting the Windows 2000 platform. Users have come to expect a significant degree of personalization. Developers should use Active Directory to personalize applications whether they are ecommerce, intranet, or even Win32 applications. Developers should also use Active Directory as their sole security mechanism. No one should ever again create a custom security system consisting of tables in a database. Active Directory already has the infrastructure complete. Figure 1.1 shows a simple home page giving a personal welcome. I discuss Active Directory in more detail in Chapter 8, “COM+ Security.”
Internet Information Server 5.0 Internet Information Server (IIS) is in its fifth release under Windows 2000. Microsoft has added enhancements to the security, performance, and administrative features of IIS to more fully support Windows DNA applications. This version also contains a number of enhancements for developers utilizing ASP and client-side scripting. These new features are covered in Chapter 11, “COM+ and the Internet.”
Windows DNA and COM+ CHAPTER 1
13
1 WINDOWS DNA AND COM+
FIGURE 1.1 Active Directory contains profile information about users that can be used to welcome them by name to a Web site.
For managing IIS, you can still use the familiar MMC application that was introduced with version 4.0. However, Windows 2000 provides an enhanced Microsoft Management Console (MMC) application that shows many of the key services in one location. This applet can be found on the Start menu under Computer Management. Figure 1.2 shows the new MMC applet for service management.
FIGURE 1.2 Most of the key services are accessible through the Computer Management console.
14
Understanding COM+ Applications PART I
Message Queuing Message queuing is a technology that was introduced with the Windows NT 4.0 Option Pack. Message queuing is a service that allows developers to create asynchronous communications between components. The Microsoft Message Queue (MSMQ) service allows a component to leave a “message” in a queue and then immediately return processing to the calling client. The message can then be picked up by another component and processed asynchronously. The processing component can leave a success or failure message in a outgoing queue for the original component. Message queuing is critical to enhancing the performance of distributed systems because it frees calling clients from waiting for synchronous processes to finish. I have witnessed several examples of poor Web site design in which scripted pages actually timed out while waiting for a long process to complete. This often occurs because processes run quickly when developed on a single machine, but perform poorly when they are deployed. Asynchronous processing is often the answer. Message queuing is discussed in detail in Chapter 10, “Asynchronous COM+ Applications.”
Universal Data Access Universal Data Access (UDA) is the Microsoft acronym for technology embodied in OLEDB. OLEDB is the specification that defines the functionality of the data access objects found in the ActiveX Data Objects (ADO). The version of ADO released with Windows 2000 is ADO 2.5. ADO 2.5 has several enhancements, but the single largest enhancement is the capability to stream Extensible Markup Language (XML) text. Streaming XML allows developers to create Windows DNA applications in which specialized data components use ADO 2.5 technology internally, but return XML Strings externally. Because XML Strings are primitive data, they don’t require marshaling and can operate across various platforms. This capability is a critical part of the general architecture developed in this book. Strong knowledge of ADO 2.5 is a requirement for building Windows DNA applications. Figure 1.3 shows the new ADO 2.5 object model. I’ll discuss the new ADO capabilities where appropriate throughout the book.
XML Support Along with streaming XML support in ADO 2.5, Windows 2000 ships with version 2.0 of the XML Document Object Model (DOM). The XML DOM is the Microsoft XML parsing engine. The DOM allows components that receive streamed XML to parse the XML and locate information. This support makes XML a strong solution for the transport of data over distances. Internet Explorer has innate support for XML and can display it directly. Figure 1.4 shows an ADO Recordset converted to XML and displayed in the browser. I discuss XML and the DOM in detail in Chapter 5, “Accessing Data with COM+.”
Windows DNA and COM+ CHAPTER 1
1
Connection Error
Properties
Property
Command Parameters
Parameter
Properties
Property
Recordset Fields
Field
Properties
Property
Record
Stream
FIGURE 1.3 ADO 2.5 supports several new features and objects.
FIGURE 1.4 Internet Explorer has built-in support for XML.
Field
WINDOWS DNA AND COM+
Errors
Fields
15
16
Understanding COM+ Applications PART I
Network Load Balancing As the number of users increases on an application, that application must scale gracefully. Scaling is the process of adding hardware and enhancing software to handle increased numbers of users. Windows 2000 supports scaling Web-based applications through the use of Network Load Balancing (NLB). NLB allows several machines on the enterprise to share a single Internet Protocol (IP) address. The browser requests are then spread among the available machines to even the load. As demand on the Web site grows, more machines can be added to the node.
NOTE Don’t confuse NLB with the Microsoft Cluster Server technology. NLB is primarily intended to support the scaling of TCP/IP based applications such as Web sites. Essentially, this is the technology we use to create a Web farm.
NLB is discussed in detail in Chapter 14, “Debugging and Deploying COM+ Applications.”
Component Services Component Services is the formal name for COM+. These services are designed to support scaling and maintaining tiered systems built on component technology. In many ways, COM+ is simply the next release of the Microsoft Transaction Server (MTS). If you have built MTS applications in the past, you will find COM+ applications to be familiar. Because this set of services is the primary focus of the book, I will spend some additional time examining the specific services provided by COM+.
Thread Support Threads are a sequence of execution steps within a component. Individual components can support one or more execution points operating simultaneously. Such components are known as multi-threaded components. Before Windows 2000, components could support either the single-threaded apartment (STA) model or the multi-threaded apartment (MTA) model. With the advent of Windows 2000 and COM+, components can now support the thread-neutral apartment (TNA). TNA components are essential to tapping the full feature set of COM+ because they eliminate many of the drawbacks of STA and MTA components. STA components are confined to executing on just a single thread. This is problematic because it can result in deadlock situations in which a process holds the only available thread to a component thus blocking other processes. MTA components solve the problem of a single thread by allowing multiple threads to operate within a given component. The problem with STA and
Windows DNA and COM+ CHAPTER 1
In all large applications, proper thread management is critical to scalability and performance. Regardless of the threading model in use, COM+ provides the underlying support to manage threads for your components. This means that STA, MTA, and TNA components all work with COM+; however, other COM+ features can be negatively affected by the choice of threading model. The most significant consequence of using Visual Basic for COM+ development is that Visual Basic 6.0 doesn’t support the thread-neutral apartment model. Visual Basic components support only the STA model. Microsoft has indicated that Visual Basic will support the TNA model under version 7.0.
Memory Support Along with threads, COM+ also provides support for managing the memory used for creating components. In the most efficient case, COM+ provides for pooling instances of objects created that might be reused by subsequent client calls. This mechanism of object pooling is designed to eliminate the overhead involved in object creation. Object pooling works by taking objects that are released by calling clients and storing them in a common pool. The objects in this pool can then be retrieved for subsequent client calls without creating a new object instance. Unfortunately, object pooling requires that components show no thread affinity. For this reason, object pooling requires that components support the TNA model. Because Visual Basic 6.0 components can’t be created using the TNA model, they can’t support object pooling. On the bright side, however, Visual Basic object creation routines are generally highly optimized. For this reason, lack of object pooling features won’t significantly affect your application’s overall performance. Having said this, you can bet Microsoft will be trumpeting object pooling as soon as it’s possible under Visual Basic 7.0. In the absence of object pooling, COM+ helps manage memory through the use of just-in-time activation and as-soon-as-possible deactivation. This feature ensures that an object lives for only the minimum amount of time necessary to process a function call. Effectively managing the available memory is critical to scaling a distributed application.
Event Support Of the new component services provided by COM+, event support is one of the most useful to Visual Basic programmers. COM+ events form a mechanism for enabling one COM+ component to receive events fired by another. In and of itself, this might not seem like a new feature.
1 WINDOWS DNA AND COM+
MTA components, however, is that they suffer from restrictions on just which threads are allowed to run in the component. TNA components solve this problem by supporting any available thread at any time.
17
18
Understanding COM+ Applications PART I
After all, Visual Basic has supported the Event keyword for some time. COM+ events, however, are said to be loosely coupled. This means that event receivers (called subscribers) don’t need specific knowledge of event providers (called publishers). In fact, a COM+ component can subscribe to any published event at any time. This significantly simplifies application development as you add new features to a system. COM+ events are covered in Chapter 9, “COM+ Business Features.”
Transaction Support COM+ components provide transactional support just like their Microsoft Transaction Server predecessors. However, COM+ introduces the concept of automatic transactions. Automatic transactions allow a component to participate in a transaction and vote for the success or failure of a transaction without any special coding. Automatic transactions are intended to simplify COM+ programming; however, they don’t always work well with Visual Basic 6.0 components. I will present specific recommendations for building transactional components in Chapter 7, “COM+ Transactions.”
Asynchronous Support Another of the newest features of COM+ is support for queued components. These inherently asynchronous components work with MSMQ to process messages stored in a queue. The setup to support message queuing is built into the COM+ explorer; therefore, you don’t have to engage in any separate MSMQ programming to create an asynchronous solution. Queued components are discussed in Chapter 10.
Security Support COM+ provides several enhancements to security checking in a distributed application. For MTS programmers, you will still find the familiar role-based and programmatic programming models. However, COM+ also introduces new improvements such as authentication services that can improve you component’s capability to secure access to resources. Security is discussed in Chapter 8, “COM+ Security.”
State Support Application state support is provided by the Shared Property Manager (SPM) in COM+. This is essentially the same feature set available to MTS programmers. In my experience, however, developers don’t make enough use of this feature for managing system-wide information. I cover the SPM in Chapter 4, “COM+ Application Fundamentals.”
Tiered Architecture Overview At this point in the evolution of distributed application development, you might think that everyone understands the principles behind tiered applications. I find, however, that this architectural philosophy is slow to penetrate the Visual Basic community. In early 1999, Deb Kurata
Windows DNA and COM+ CHAPTER 1
Two-Tier Architecture Two-tier architecture is the most common and well-understood approach to database applications. In this model, the display of data is tightly bound to the storage of the data in the database. In most of these applications, the user interface is merely a reflection of the underlying data structure. Developers will often take a recordset directly from the database and display it in a table in which it looks exactly the same as it would if you opened the table directly in the database. Users interact directly with the data for add, edit, update, and delete functionality. Business rules that perform functions on the data are either built directly into the user interface or reside in the database through mechanisms such as triggers. Examples of this type of application include data-bound controls and, most recently, ASP pages on the Web. If you write all your data access code directly in your Web pages, you are creating a two-tier application. Figure 1.5 shows a diagram of a typical two-tier ASP application.
ASP Pages
Internet Information Server
SQL Server
FIGURE 1.5 Two-tier architecture ties the Web page directly to the database.
In a two-tier application, data access is most often performed through the use of cursors. Database cursors allow an application to maintain an open connection to the database while users scroll and manipulate the data. In most two-tiered applications, the database connection is established when the application is started and is kept open until the application is closed. When cursors are combined with a constantly available database connection, applications can handle concurrency issues through the use of record locking. Record locking prevents two users from simultaneously making changes to the same database record.
1 WINDOWS DNA AND COM+
was still teaching fundamental object-oriented programming at the VBITS conferences, and it was still one of the best received talks long after everyone was supposed to have known the information cold. With that in mind, I present the fundamentals of tiered architecture. If you are already familiar with this discussion, you’ll want to move on.
19
20
Understanding COM+ Applications PART I
Under many Internet applications, cursors have become less of an issue because Internet development inherently drives correct use of database connections. For an application to scale properly, it must be connected to the database only long enough to read and write data. The very nature of a technology like ASP is that it can’t support connections to the database for any longer than a single page. Therefore, the connection must be made and broken each time a new page is generated. The exception to this rule is when a developer uses an Application or Session variable to hold a database connection. These ASP objects allow stateful information to exist between page calls. Although I see very little of this architecture, you should be keenly aware that using Application and Session variables—particularly to maintain database connections—can destroy your application’s scalability and performance. Distributed programming requires accessing resources only when absolutely necessary. Another hallmark of two-tiered applications is the use of SQL statements directly in the application code or calls to stored procedures directly from the application code. In this design, the front end requires an intimate knowledge of the database structure and available stored procedures. If the database structure is changed or the stored procedure is altered, it will undoubtedly require maintenance on the front end. Two-tiered applications are generally simpler to design and build than multi-tier applications. However, simplicity doesn’t come without a price. The tight binding between the database and the user interface almost always results in an unsatisfying design. Developers are often content to display database information in tables and lists without much care for the end-user experience. This mentality reaches its pinnacle when developers dump thousands of records into a single Web page of search results and declare their job complete simply because the data is now visible. Users are then left to fend for themselves as they wade through thousands of records searching for the data they really need. Another significant disadvantage of two-tier applications is that they are difficult to maintain. As I’ve pointed out, tight binding between the application and the database means that changes to either tier can have a disastrous effect on the other tier. This means that new versions of a product quite often require a complete rewrite of the application. I’ve seen the impact of this design regularly in the creation of ASP Web sites. Many of these sites have a tremendous amount of code directly in the page. This disastrous mix of business rules and presentation information makes for a maintenance nightmare. Often developers can be seen scrolling endlessly back and forth in an ASP page searching for a small snippet of code they need to fix. Does your Web site look like the page shown in Figure 1.6? All this discussion is not to say that two-tier applications have no place in the new order of applications. Sometimes when you just want an HTML form to send some email, a quick little
Windows DNA and COM+ CHAPTER 1
FIGURE 1.6 Two-tier architecture often results in unmaintainable code.
Three-Tier Architecture Three-tier architecture represents an improvement over the disadvantages of two-tier architecture. In this architecture, the database is separated from the user interface by an intermediate layer known as business services. This layer eliminates the tight binding between the user interface (called the user services layer) and the database (called the data devices layer). Separating user services from data services results in immediate advantages. Because the intermediate layer can process the data before it is displayed, developers can massage the data into a form that is much easier for the user to work with. Rather than be simply presented in a table, data can be presented in more meaningful formats. The business services layer makes this massaging easier to create and maintain. This separation of layers in an application is referred to as partitioning. Figure 1.7 shows a simple block diagram of a typical three-tier system.
1 WINDOWS DNA AND COM+
ASP page is just what you need. The decision to create a two-tier application should be based on the business objectives of the software. You must often balance issues such as time to develop against system maintainability and overall cost.
21
22
Understanding COM+ Applications PART I
COM+ Components
XML Pages User Services
Internet Information Server Business Services
SQL Server Data Services
FIGURE 1.7 Three-tier architecture often improves scalability and maintainability.
The partitioning of service layers also removes the intimate relationship between SQL statements, stored procedures, and the front-end code. This means that the front end can be changed more easily without affecting the database, and the database can be altered without rewriting ASP code. The business services layer also provides a segregated home for the business rules that work on the data. In this way, the business rules can be changed without affecting the data or the user interface. This is superior to the use of database triggers that reside directly in the data services layer. A separate business services layer also offers an opportunity to construct an application that shares components in the middle tier. This means that all clients using the application can take advantage of the functionality provided by the business services. This is a significant advantage in maintenance because changes to the shared central tier will immediately affect all clients on the system. This type of design virtually eliminates the need to constantly revise software on many client machines. It also encourages the reuse of components by fostering a “building block” approach for applications. These components can participate in one or more applications simultaneously, making it easier to build and maintain new applications. Many different technologies are available to create tiered application on Windows 2000. The choice of which technologies to use depends largely on the application’s objectives. Perhaps one of the biggest questions you have to answer is whether your application will run in a browser and if that solution must be supported by both Netscape and Microsoft browsers. Despite Microsoft’s dominance in the browser market, a significant number of individuals and companies still rely on the Netscape browser. Because Netscape doesn’t support all the technologies available to Internet Explorer, we must carefully design our solution with browser support in mind. Generally, this means returning only HTML to the browser. Technologies like XML might be used internally in your system, but they can’t be delivered directly to all browsers that might visit your site.
Windows DNA and COM+ CHAPTER 1
Tiered architecture truly requires a change in the way you understand software systems. The shift in thought is similar to the change required to move from traditional functional programming to object-oriented (OO) programming. Over the years, when I’ve taught VB developers OO principles, they’ve had difficulty absorbing the philosophy. However, those who persevere most often report what I call the “ah-ha” experience. This seems to happen unexpectedly when, in a sudden flash (usually when the person is involved in a non-programming activity), OO principles suddenly make sense. I remember clearly a colleague telling me that he had significant trouble with OO until one day he was fixing a lawn tractor. As he took apart the engine, his mind suddenly started describing the pieces as if they were software objects with properties and methods. He got so excited that he took the tractor completely apart just to describe each piece as an object. This experience is often repeated by developers mastering tiered applications. The tiers can be thought of as “super objects.” Tiers gather objects to form a larger functional block. Much like the engine is part of the tractor, but the engine is also made up of constituent parts. This idea of grouping permeates OO systems, and tiered applications are no different. Therefore, the data services engine can be thought of as a “black box” that delivers data to the system. Internally, it is made up of components, which in turn are made up of objects. However, just like a good object, the data services layer doesn’t care what other services call it. Data services just returns data no matter who calls on it. This idea is expanded and defined throughout the book and constitutes one of the main goals.
Establishing a Test Environment This book adopts a “blue-collar” approach to Windows DNA applications. This approach, to me, means an emphasis on building practical solutions—not just discussing theory. To that end, this book is full of exercises and projects that you can work through to gain a real understanding of everyday architectural issues surrounding distributed application design and development. Before you begin, you’ll want to establish a test environment where you can easily work all the projects.
1 WINDOWS DNA AND COM+
Creating a three-tier application is, of course, significantly more complicated than a two-tier application. Right away you have to deal with designing and creating distributed components that run remotely. Also, the machines that make up the business services are shared among many users, so the proper management of these shared resources is critical to the success of the application. This complexity is the single biggest disadvantage of tiered applications and the main reason that so few of them are built.
23
24
Understanding COM+ Applications PART I
Windows 2000 Advanced Server Windows 2000 forms the backbone of our test environment. Although you can work with different versions of the operating system at different points in the book, I always assume that you have the Windows 2000 Advanced Server available. This operating system will allow you complete access to all the key features from Active Directory to network load balancing. Installation of the operating system is fairly straightforward with Windows 2000. You can either upgrade an existing Windows NT platform, create a dual boot system, or boot directly from the CD-ROM for installation. Throughout the setup, you will find that there are no confusing trouble spots. Just be sure to install the correct services that you will need to run the exercises in the book as described in the following sections.
Active Directory When Windows 2000 is first installed, it doesn’t have the Active Directory available. You will want to install the Active Directory for the server you will use. In some cases, the server you create might be on a Windows 2000 network already. Under these circumstances, you might choose to use an existing Active Directory. Note, however, that we will often make changes to the directory, and you should evaluate the impact before using a live directory. The best bet is to set up your own server with its own domain separate from any other domain. Install the Active Directory after you install the operating system. On the Start menu, select Programs, Administrative Tools, Configure Your Server. This brings up a dialog box that will allow you to “promote” your server to a domain controller. Figure 1.8 shows the home page of the configuration utility.
FIGURE 1.8 Set up Active Directory after Windows 2000 is installed.
Windows DNA and COM+ CHAPTER 1
FIGURE 1.9 Active Directory requires the DNS service.
Internet Information Services Internet Information Services (IIS) installs automatically with your Windows 2000 Advanced Server. This book doesn’t require any special configurations for IIS during installation. However, you should ensure that you are designated with sufficient permissions to administer your IIS service. Again, it’s best to simply set up a separate domain for completing exercises.
Microsoft Message Queue MSMQ is required for working with queued components. MSMQ isn’t installed by default; you must specify that it be installed during the setup process for Windows 2000 Advanced Server. MSMQ also requires additional setup after the Windows 2000 installation is complete. Figure 1.10 shows the Windows component dialog for installing MSMQ.
1 WINDOWS DNA AND COM+
During the promotion process, you will be prompted to set up the Domain Name Service (DNS). DNS allows computer names to be resolved to TCP/IP addresses. Active Directory requires this service to operate correctly. Although the setup will make appropriate DNS entries for your promoted server, you might have to make additional entries by hand if you are working with several Windows 2000 machines on a network. Figure 1.9 shows the typical server entry for the promoted server. Obviously, this text can’t describe in detail the setup requirements for all Windows 2000 services, but you should have a good plan before you begin the installation process.
25
26
Understanding COM+ Applications PART I
FIGURE 1.10 MSMQ setup must be completed after Windows 2000 is set up.
SQL Server 2000 Many database exercises in this book require SQL Server 7.0 or higher. In many cases, the book uses the pubs database that ships with SQL Server. You must also be designated as the administrator for SQL Server, although it is perfectly acceptable to leave unchanged the default system administrator designation of sa with no password. When this book uses custom SQL Server databases, you will generally find a batch of SQL files that you can run to set up the databases. Therefore, you should be familiar with essential SQL Server administrator tasks such as creating accounts and establishing permissions for database objects.
Visual Studio Visual Studio, Enterprise Edition, contains all the software necessary to code the exercises in the book. The exercises are all created in Visual Basic 6.0; however, several other applications are required to support the projects. In particular, this book relies heavily on Visual InterDev for Web site construction. This book assumes a strong background in the fundamentals of Web site development with Visual Studio.
CHAPTER
Administering COM+
2
IN THIS CHAPTER • The Component Services Explorer
28
28
Understanding COM+ Applications PART I
The bulk of this book is dedicated to creating solutions—and that means writing code. However, you can’t create COM+ solutions unless you understand the administrative tasks associated with installing and maintaining the components. This chapter will give you the essentials you need to understand the management tools associated with COM+.
The Component Services Explorer Administering COM+ components is done through the Component Services, or COM+, explorer. This interface is accessible from the Start menu by selecting Programs, Administrative Tools, Component Services. If you are familiar with the Microsoft Transaction Server (MTS) explorer from Windows NT, you will find the COM+ explorer to be similar. Figure 2.1 shows the Component Services interface.
FIGURE 2.1 COM+ is managed through the Component Services interface.
The Component Services explorer divides COM+ management into a hierarchical structure with a treeview on the left and listview on the right. The treeview creates a simple hierarchy of computers, applications, and components. Opening the Component Services node reveals the Computers folder, which allows access to servers running COM+ components. Opening a computer node reveals the COM+ Applications folder, which groups components into a logical package. Opening a COM+ application node reveals the Components folder, which allows
Administering COM+ CHAPTER 2
29
access to COM+ features for any component. Together, these three divisions form the core of Component Services.
Computer Properties Inside the COM+ explorer, you can access properties for any item by right-clicking and selecting Properties. Opening the Properties dialog for My Computer reveals six tabs that help you manage settings for the computer as a whole.
The General Tab
FIGURE 2.2 Enter a server description in the General tab.
The Options Tab The second tab on My Computer Properties is Options (see Figure 2.3). This tab allows you to set the global timeout property for transactions managed by COM+. This setting causes transactions to automatically be aborted if they take longer than the designated interval. If you never want a transaction to timeout, you can set this value to zero; however, a zero value isn’t recommended because a bad transaction could hang the system. The global timeout is the default for all components in COM+; however, the setting can be overridden by any individual component. Later in this chapter, we’ll see that each individual component can set a transaction timeout. This value is normally not set, but must be manually activated.
2 ADMINISTERING COM+
The first tab in the dialog, General, serves as a place to enter a description of the server. The description can be as long as 500 characters. Figure 2.2 shows the General tab.
30
Understanding COM+ Applications PART I
FIGURE 2.3 The Options tab.
Along with the transaction timeout, the Options tab allows you to specify an alternate application proxy server. The purpose of this setting is to support the installation of remote Win32 client front ends. This is done from the COM+ explorer through a process known as exporting. When a proxy is exported, COM+ creates a special installation for a remote client front end that will allow the client to use COM+ components. The issue here is that Win32 clients need to know the name of the server where the COM+ components can be located. Exporting a proxy normally points all client software at the server where the export is done. However, if you want the proxies directed to a different server, you can enter the name of the server in the Options tab.
The MSDTC Tab The third tab on My Computer Properties, the MSDTC tab, gives you control over settings for the Microsoft Distributed Transaction Coordinator (MSDTC). The MSDTC is responsible for managing distributed transactions in COM+. Distributed transactions enable your COM+ systems to perform transactions across multiple components and multiple databases. The MSDTC is discussed in detail in Chapter 7, “COM+ Transactions.” Figure 2.4 shows the MSDTC tab.
The Default Properties Tab The Default Properties tab in My Computer Properties allows you to set properties for Distributed COM (DCOM). DCOM services, enabled by default when you set up Windows 2000, form the backbone of any distributed system. These services enable applications on one computer to call the COM+ components on another computer. If you disable DCOM services, you can run your COM+ applications only on a single machine. This essentially defeats the purpose of COM+.
Administering COM+ CHAPTER 2
31
2 ADMINISTERING COM+
FIGURE 2.4 The MSDTC tab.
When DCOM is enabled for the server, you can set the Default Authentication Level and the Default Impersonation Level for the server. The Default Authentication Level setting determines when a caller’s identity is authenticated. Just as you must be authenticated before being logged on to a network, COM+ will authenticate users who are attempting to access the services of a distributed component. The authentication level settings enable authentication at various levels based on how tightly you want to control security. Table 2.1 lists the available settings and explains their effect. TABLE 2.1
DCOM Authentication Levels
Setting
Explanation
Default None Connect
Use the default security settings for the application. No authentication is performed. Callers are authenticated only when they first connect to a component. Callers are authenticated each time they access a method of a component. Each data packet is authenticated. Authenticates each packet and ensures that no packet data has been modified during transmission. Authenticates each packet, ensures that no packet data has been modified during transmission, and encrypts the data.
Call Packet Packet Integrity Packet Privacy
32
Understanding COM+ Applications PART I
Impersonation is a process that allows a component to assume the permissions of a Windows 2000 user for the purpose of accessing system resources. The Default Properties tab provides a number of different settings that affect the capability of a component to access the system. Table 2.2 lists the settings and their features. TABLE 2.2
Impersonation Level Settings
Setting
Explanation
Anonymous Identify
The caller can’t be identified. The component can impersonate the caller for identification purposes only. The component can impersonate the caller to access system resources. The component can impersonate the caller to gain access to system resources and to make calls to other objects.
Impersonate Delegate
Although the DCOM subsystem is essential for creating distributed applications, it can have limitations when you want to distribute the system across the Internet. DCOM can run over HTTP protocol; however, DCOM requires the use of many different ports to successfully communicate in a range of 1024-65535. Typically, firewalls and proxy servers block the ports that DCOM requires, which effectively prevents DCOM from functioning over the Internet. To overcome this problem, you can enable COM Internet Service on the Default Properties tab. When COM Internet Services are enabled (see Figure 2.5), COM+ components use port 80 to perform an initial handshake that establishes connectivity through a firewall or proxy server. This allows you to create true distributed applications that work across the Internet. COM Internet Services require the use of a special moniker called OBJREF that allows a browser to locate a running component on a Web server.
The Default Security Tab The Default Security tab allows you to set default access and launch permission for COM applications running on this server. The important distinction here is that these settings have no effect on COM+ applications—they affect only COM applications. Figure 2.6 shows the Default Security tab.
The Default Protocols Tab The final tab on My Computer Properties is Default Protocols. This tab specifies the protocols available to the DCOM subsystem. The order that they are listed affects the order in which they are used. Figure 2.7 shows the Default Protocols tab.
Administering COM+ CHAPTER 2
33
2
The Default Properties tab.
FIGURE 2.6 The Default Security tab.
My Computer Tasks Along with access to the properties of My Computer, the Action menu also allows you to perform two other useful tasks: managing the MSDTC service and refreshing COM+ components. From the Action menu, you can start and stop the MSDTC. Starting and stopping this service can actually be done from a number of places, including the MSDTC tab and the Services
ADMINISTERING COM+
FIGURE 2.5
34
Understanding COM+ Applications PART I
node found at the bottom of the COM+ explorer. Refreshing COM+ components is useful any time you install a new version of a DLL into COM+. This is common during development, but also happens when new versions are rolled out.
FIGURE 2.7 The Default Protocols tab.
Application Properties COM+ components are grouped under a server into COM+ applications. The term application is somewhat misleading when used in this context because developers might tend to think of executable content. However, the truth is that a COM+ application is a grouping of components for administrative and security purposes. The COM+ application is similar to the “package” under MTS. Along with security and administration features, each COM+ application is associated with a running instance of the executable dllhost.exe. This executable provides a runtime environment for COM+ components, which allows COM+ to provide services. This one-to-one mapping between COM+ applications and dllhost.exe is a critical architectural point that will affect your system design significantly as you proceed through the book.
The General Tab As with My Computer, you can access the properties for any COM+ application by rightclicking and selecting Properties from the pop-up menu. The first tab you will see on the property sheet is the General tab, which contains the name and description of the COM+ application.
Administering COM+ CHAPTER 2
35
Each COM+ application is also assigned an AppID, a globally unique identifier (GUID) that identifies the COM+ application. This number is useful when you are performing administrative tasks programmatically. In Chapter 15, “COM+ Catalog Administration,” I discuss programmatic administration. Figure 2.8 shows the General tab.
2 ADMINISTERING COM+
FIGURE 2.8 The General tab.
The Security Tab The Security tab on the COM+ application property sheet allows you to specify whether access to the COM+ components in the application will require permission and exactly how the authentication will occur. For security checking to be active, you must check the Enforce Access Checks for this Application box. When security is enabled for the application, COM+ uses special “roles” that you define to determine whether access is allowed to the components in this application. Roles are discussed in Chapter 8, “COM+ Security.” In the Security Level settings, you can choose to have COM+ perform security checks at the process or component level. The default is to check at the component level. Checking security at the component level enables you to find out additional information about calling clients. For example, you can determine the identity of a calling client programmatically when you check access at the component level. The Security tab also allows you to set the Authentication and Impersonation levels for the application. These settings are the same as the default settings discussed under the My Computer properties, and will override those settings. Figure 2.9 shows the Security tab.
36
Understanding COM+ Applications PART I
FIGURE 2.9 The Security tab.
The Identity Tab The Identity tab on the COM+ application property sheet allows you to set the Windows 2000 user under whom the application will run. On this tab, you may select to run the application as the Interactive User or under a particular account. When you specify that a COM+ application should run as the Interactive User, you are stating that all COM+ components in the application will have the identity and permissions of the person currently logged in to the server where the application is located. This setting is useful if you are a developer building a COM+ system on a single machine, but has little value in a final, deployed application. This is because you would actually have to have someone logged in to the server when the application is deployed. If you log out of the server where the COM+ application is running, the components won’t run and all clients will receive permission errors. The correct way to set up a COM+ application is to select a specific account to run your components. We normally set up an account with just the minimum number of permissions necessary to run the application. You will need just such an account to run several of the applications in this book. Figure 2.10 shows the Identity tab.
The Activation Tab The Activation tab on the COM+ application property sheet allows you to specify whether the COM+ application runs as a server or a library application (see Figure 2.11). Server applications run in a copy of dllhost.exe, whereas library applications run in the client application’s memory space.
Administering COM+ CHAPTER 2
37
2
The Identity tab.
FIGURE 2.11 The Activation tab.
The default setting for the Activation tab is to run as a server application. Running within dllhost.exe enables COM+ to provide full support to the components in the application. It also enables components to be called from remote clients. Selecting to run as a library application, on the other hand, removes all COM+ support, with the exception of role-based security, because the runtime environment isn’t used. All application support must come from the client application itself. This setting also implies that the client application must be located on the same machine as the COM+ components so that they can be loaded into the client memory space.
ADMINISTERING COM+
FIGURE 2.10
38
Understanding COM+ Applications PART I
Component Services run on clients as well as servers. If you export an application proxy for a client to use, it will be installed as a COM+ application on the client. When you install an application proxy, the name of the server where the component is located appears in the Remote Server Name box.
The Queuing Tab The Queuing tab on the COM+ application property sheet allows you to designate the component as a queued component (see Figure 2.12). Queued components are associated with queues in the Microsoft Message Queue (MSMQ). Setting the Queued property automatically sets up special queues for incoming messages to this component. You can then write code to programmatically examine and process messages in these queues.
FIGURE 2.12 The Queuing tab.
If you don’t want to write the queue processing code yourself, you can further designate that the component should listen. When a component is set to listen, it will automatically process messages in its associated queues as they arrive. This means you can establish asynchronous processing with no code at all. Queued components are covered in detail in Chapter 10, “Asynchronous COM+ Applications.”
The Advanced Tab Advanced, the sixth and final tab on the COM+ application property sheet, allows you to control many aspects of how the COM+ application behaves. The first setting you can affect determines what happens to your COM+ application when there are no longer any clients calling it. When your COM+ application is idle, you might choose to leave it running or shut it down after a period of time. The default is to shut down the application after three minutes to
Administering COM+ CHAPTER 2
39
conserve resources. However, if this application is critical to the performance of your system or takes a long time to initialize, you might want to leave it running. After the COM+ application is defined, you might want to disable changes and deletions to the application. Disabling changes and deletions prevents people not designated as a COM+ administrator from modifying the application. I discuss designating COM+ administrators in the next section. The Advanced tab also provides support for launching compiled Visual Basic components in the C++ debugger. If you want, check the box to launch the specified debugger. The COM+ application has a default entry, but you can change the debugger launch string if you need to.
Finally, the Advanced tab allows you to specify that your COM+ application can access up to 3GB of memory within Windows 2000. Using this feature requires that you enable access to 2GB and larger memory blocks within Windows 2000 itself. Figure 2.13 shows the Advanced tab.
FIGURE 2.13 The Advanced tab.
ADMINISTERING COM+
COM+ provides support for automatic transactions that you can use to create transactional systems. For many business purposes, database transactions are enough support. However, you might have another data source that you want involved in a transaction. For these sources, you might have to create a Compensating Resource Manager (CRM), which provides support for voting in transactions. Once created, you typically install them in a COM+ application and then select to enable the CRM. This check box allows the CRM to be used. You can build a complete CRM in Chapter 9, “COM+ Business Features.”
2
40
Understanding COM+ Applications PART I
The System Application Earlier, I alluded to designating administrators for Component Services. Setting up administrative privileges is accomplished through a special COM+ application called the System Application. The System Application is a COM+ application that contains the components which perform administrative tasks in COM+. When Windows 2000 is first installed, the Component Services explorer is available only to domain administrators. This is because Component Services places the domain administrators group under the Administrator role in the System Application. The Administrator role is just one of five roles defined within the System Application. Table 2.3 lists all the roles to which users can be assigned. TABLE 2.3
System Application Roles
Role
Permissions
Administrator Any Application
Modifies configurations and components. Contains all usernames utilized for application identity for both library and server applications. Sends messages for queued components on behalf of other users. Has read-only access to Component Services. Contains all usernames utilized for application identity for server applications only.
QC Trusted User Reader Server Application
Creating Applications When deploying a system under COM+ services, one of the first tasks you’ll have to perform is the creation of a new COM+ application. This task is accomplished by clicking the COM+ Applications folder and selecting New/Application from the Action menu. When you select to create a new application, COM+ starts the COM+ Application Install Wizard, as shown in Figure 2.14. This wizard helps you with the basic task of creating a new COM+ application. When you use the wizard, you can choose to create a new application or import one that was exported from another Windows 2000 server. Usually, you’ll be creating a new application. Figure 2.15 shows the screen for choosing to import or create a new application.
Administering COM+ CHAPTER 2
41
2
The new COM+ application Welcome Screen.
FIGURE 2.15 COM+ applications can be created or imported.
The wizard requires only a few pieces of information beginning with a name. In the next step, you’ll give the application a descriptive name (see Figure 2.16). This name can include white spaces. The wizard also prompts you for the identity under which to run the application. As I said earlier, you can use the Interactive User setting for most examples in this book; however, you’ll want to set up a real account for deployed systems. It’s generally best to have the account set up ahead of time and entered under the appropriate roles in the System Application. You can, however, always change these settings later. Figure 2.17 shows the screen for selecting the application identity.
ADMINISTERING COM+
FIGURE 2.14
42
Understanding COM+ Applications PART I
FIGURE 2.16 COM+ applications are given descriptive names.
FIGURE 2.17 Set the COM+ application identity.
When the wizard is complete, COM+ will make the new application. All the features of COM+ are now available to components you install in the new application. Figure 2.18 shows the final screen before the new application is created.
Component Properties COM+ applications are made up of components. Just like computers and applications, components have property settings that you can change. To access the property sheet for any component, simply right-click the component and select Properties from the pop-up menu. The property sheet will then appear.
Administering COM+ CHAPTER 2
43
2
Create the new COM+ application.
The General Tab The first tab on the component property sheet is the General tab (see Figure 2.19). The General tab contains fundamental information about the component, such as the name, description, parent DLL, class identifier, and application identifier.
FIGURE 2.19 The General tab.
The Transaction Tab The Transaction tab on the component property sheet allows you to specify the transactional behavior of the component (see Figure 2.20). The settings found here determine whether a
ADMINISTERING COM+
FIGURE 2.18
44
Understanding COM+ Applications PART I
component can vote in transactions and how it votes when other components are involved. Chapter 7 covers transactions in detail.
FIGURE 2.20 The Transaction tab.
The Security Tab The Security tab on the component property sheet is used primarily to allow access to the functionality of the component based on roles (see Figure 2.21). You’ve already seen several roles associated with the System Application and will learn more about roles in Chapter 8. However, once a role is defined, you must add it to the Security tab of the component to allow access.
FIGURE 2.21 The Security tab.
Administering COM+ CHAPTER 2
45
The Activation Tab The Activation tab on the component property sheet is where you would designate that your component supports object pooling (see Figure 2.22). As we discussed in the previous chapter, however, object pooling requires support for the thread-neutral apartment (TNA) model, which Visual Basic 6.0 doesn’t support. Therefore, this option is always unavailable for VB components.
2 ADMINISTERING COM+
FIGURE 2.22 The Activation tab.
One nice feature of COM+ that’s available to Visual Basic components is object construction. Object construction enables your component to receive a constructor string when it’s first activated by COM+. This string can be anything. It might be a flag indicating that a generic component should behave in a specific way. My favorite use is to provide connection strings and directory paths so that a data source path can be easily changed. The Activation tab has the Enable Just-in-Time Activation (JIT) field set by default. This feature allows COM+ to create and destroy instances of the objects created by the component to efficiently manage resources. I discuss JIT activation in Chapter 4, “COM+ Application Fundamentals.” The Activation tab also allows you to specify that your component should support statistics. Setting this option means that you can view statistics about the performance of the component while it’s running. These statistics are available in the listview of the Component Services explorer for the selected component. Components can be forced to run in the context of their caller by setting the Must Be Activated in Caller’s Context flag. All COM+ objects run inside a context. The context—a new feature of Windows 2000—requires a detailed explanation. I tackle this issue in the next chapter.
46
Understanding COM+ Applications PART I
The Concurrency Tab The Concurrency tab on the component property sheet allows you to specify the synchronization attribute for your component (see Figure 2.23). Synchronization helps ensure that only a single thread flows through an object instance at any time. Visual Basic components don’t require synchronization because they are already single-threaded. However, COM+ might demand that you set synchronization to support transactions of JIT activation. Concurrency and synchronization are discussed in Chapter 4.
FIGURE 2.23 The Concurrency tab.
The Advanced Tab Advanced, the sixth and final tab on the component property sheet, allows you to specify the class that can handle exceptions that occur when a queued component doesn’t receive a message. Normally undelivered messages are sent to the dead-letter queue, but COM+ will attempt to call the exception class, if specified, before delivering unreceived messages to the dead-letter queue. Figure 2.24 shows the Advanced tab.
Installing COM+ Components into an Application After you have created a new COM+ application, you will want to install components in it. Component installation is accomplished by selecting the Components folder beneath the COM+ application and choosing New/Component from the Action menu. This will start the COM Component Install Wizard. Figure 2.25 shows the welcome screen for the wizard.
Administering COM+ CHAPTER 2
47
2
The Advanced tab.
FIGURE 2.25 The new COM+ component Welcome Screen.
Components can be installed in your COM+ application be referencing a DLL, or by examining the System Registry. Generally, it’s better to reference the DLL when installing COM+ components because COM+ can read the type library (TLB) associated with the DLL to return interface information. Selecting to read the System Registry is necessary only if you have previously installed a component from a DLL and now need to add a new class from the same DLL to a different application.
ADMINISTERING COM+
FIGURE 2.24
48
Understanding COM+ Applications PART I
The wizard also allows you to install event classes. Event classes are the foundation of the new loosely-coupled event system in COM+. I discuss the event system in Chapter 9, “COM+ Business Features.” Figure 2.26 shows the screen for selecting how to install the components.
FIGURE 2.26 COM+ supports different installation methods.
When you have elected to install from a DLL, you can use the wizard to locate the file. Once located, the wizard will examine the DLL and identify all class modules within the DLL that can be added to the COM+ application. Figure 2.27 shows a typical DLL examined by the wizard.
FIGURE 2.27 Locate the DLL to install.
After you have identified the component to install, the wizard adds the classes to your COM+ application. You can then use the property sheet to set the attributes of the component. Figure 2.28 shows the final screen before the wizard adds the class to the application.
Administering COM+ CHAPTER 2
49
2
Complete the component installation.
EXERCISE 2.1 Creating a Simple COM+ Application This exercise utilizes the fundamental administrative skills required in COM+. You will create an application and install components in the application. After you have a component under COM+ control, you will build a simple front end to call the component. Step 1 Using the File Explorer, create a new directory called COM+\EXERCISE2-1. Step 2 Start a new ActiveX DLL project in Visual Basic. I will discuss the exact nature of the relationship between ActiveX components and COM+ later, but for now just recognize that COM+ uses ActiveX DLL components exclusively. Step 3 Open the project properties dialog by selecting Project1 Properties from the Visual Basic Project menu. In this dialog, change the name of the project to SimpleObject. While the dialog is open, ensure that the threading model for your component is set to Apartment Threaded. All COM+ components should use apartment threading to allow COM+ to handle the thread pooling for the component. Close the project properties dialog.
ADMINISTERING COM+
FIGURE 2.28
50
Understanding COM+ Applications PART I
Step 4 Select Class1 in the Project Explorer. Change the name of the class to Simple. Step 5 Open the code window for class Simple. In the code window, add a new method to the class by selecting Add Procedure from the Tools menu. Add a new method named Process. Make this method a Public Function. When you have added the new method, modify the function signature to return a String data type. The completed function signature is as follows: Public Function Process() As String End Function
Step 6 The Process method is a trivial routine designed just to allow you to work with applications and components. As such, add the following code to the Process function to return a message to the calling client: Process = “I got your call!”
Step 7 Compile your ActiveX DLL by selecting Make SIMPLEOBJECT.DLL from the File menu. When you have completed the compile, save your work and exit Visual Basic. Step 8 Open the COM+ Explorer. Locate My Computer and expand the treeview until you see the COM+ Applications folder. Click the folder. Then choose New/Application from the Action menu to start the Application Wizard. Step 9 In the first step of the Application Wizard, choose to create an empty application. In the second step of the Application Wizard, name the new application Simple. In the third step of the Application Wizard, set the application identity as Interactive User. Click Next and then Finish to create the application. Step 10 After the application is created, locate it in the COM+ Explorer. Expand the treeview until you find the Components folder. Click the folder and select New/Component from the Action menu to start the Component Wizard. Step 11 In the first step of the Component Wizard, select to Install New Component(s). In the second step of the Component Wizard, use the file dialog to search for and locate the file simpleobject.dll that you created earlier. When you select this file, the object inside the
Administering COM+ CHAPTER 2
51
DLL will be listed in the Add Components dialog. Click Next and then Finish to add the component to your application. You are now ready to call the component from Visual Basic. Step 12 Return to Visual Basic and start a new Standard EXE project. This project will be a front end to the component in COM+. Step 13 Open the references dialog for the new project by selecting References from the Project menu. In the references dialog, set a reference to SimpleObject. Close the references dialog.
Step 15 Open the code window for Form1. In the Command1_Click event, add the following code to create an instance of the SimpleObject component and call the Process method: ‘Create Business Object Dim objSimple As SimpleObject.Simple Set objSimple = New SimpleObject.Simple ‘Call Business Object MsgBox (objSimple.Process)
Step 16 Save your work. Start your Standard EXE project. Step 17 When you get a response from COM+, leave the MsgBox visible and examine the Simple object in the COM+ Explorer. You should see the component ball spinning indicating that it is active. If you close the MsgBox by clicking OK, the animation stops.
ADMINISTERING COM+
Step 14 As a simple example of calling a COM+ component, we will just create an instance of the SimpleObject component. Double-click Form1 in the Project Explorer. Add a CommandButton to Form1 from the toolbox. Change the caption on this button to Process.
2
Designing COM+ Applications
IN THIS CHAPTER • Assessing Functional Requirements • Describing the System
58
• Creating the Paper Prototype
65
54
CHAPTER
3
54
Understanding COM+ Applications PART I
Application design has become a critical topic as the complexity of Windows solutions increases. Historically, Visual Basic has had the reputation of being a rapid prototyping tool, which led to a “design as you code” mentality. As systems became larger, however, this mentality led to significant problems with scalability and maintainability. This chapter will show you a proven methodology for creating COM+ applications successfully the first time. My design solution is a variant of the Rational Unified Process (RUP), which combines many object-based design methodologies into a whole. RUP encourages both text and graphical modeling of the system before beginning the coding process. In its commercial version, RUP is also supported by a set of tools available from Rational Software. These tools help create the models necessary to successfully define a system. I have used, and like to use, many of the Rational products, but they aren’t required to complete your design. You can easily use other tools such as Visio or Microsoft Visual Modeler to create your models. In this chapter, I use only Visual Modeler because it’s available in Microsoft Visual Studio. This chapter uses small examples to help you understand the concepts presented. However, Chapter 16, “Designing the PubsOnLine.com Application,” contains a complete project specification, which contains all the elements discussed here. Also, Chapter 17, “Building the PubsOnLine.com Application,” contains the complete code for the project defined in Chapter 16. These two chapters present a practical application of the process defined here in this chapter.
Assessing Functional Requirements The design of every system begins by recording exactly what’s to be accomplished. Often programmers, and even my customers, scoff at the notion of writing everything down. Even now, many of them believe that a system can be defined verbally in a single meeting. I have been known to turn down such projects rather than suffer through the agony of shifting requirements. The best projects, however, begin with a simple problem statement.
Problem Statement A problem statement is a paragraph that describes exactly why the system is being created. It clearly states the project’s objectives and what problem is to be solved. The problem statement should be free of technical acronyms. State the problem in terms of the business objective, not the technical objective. I have occasionally been in meetings in which the customer’s company president makes a statement such as, “We need a SQL Server database with product information available for our sales people.” Our response is to ask, “What’s the business objective?” After some wrangling, we eventually get an answer such as, “We need to increase order fulfillment time by 25%.” Now we can understand!
Designing COM+ Applications CHAPTER 3
55
Key Principle A problem statement focuses on the business problem to be solved, not the technology to be used.
The point here is that the SQL Server database might not be the best answer. To give the best technical solution, we need to understand the business problem to be solved. Too often, developers have a technology looking for a problem, not the other way around. If a Windows 3.1 solution with Visual Basic 3.0 is the best answer, have the courage to say it. The following problem statement is an example. This typical problem statement defines the problem to solve as well as the business objective behind it: XYZ Books Incorporated has an existing Web site used for selling its books online. Based on comparisons with other book companies, XYZ Books believes that sales from the site are below average. XYZ Books wants to increase online sales by 300%.
Gathering Requirements Once the problem statement is written, you are ready to create a list of functional requirements. The list of requirements allows you to attain the next level of detail in the design. Functional requirements are always a group process. In this process, assemble everyone who has an interest in the project for group meetings. At any organization, a software development effort will have a single person who acts as an advocate. This person, whom we call the champion, is the true customer of the developers. The champion is responsible for securing funding and protecting the project from its enemies. As you begin to assemble the functional requirements for the system, never lose sight of the true customer. Around the champion are many people with an interest in the project. We call these people stakeholders. A stakeholder is anyone in the organization who could derail or delay the development effort. Some stakeholders will be excited about the project and function as secondary advocates. Some will try to expand the scope of the effort to solve problems not contained in
3 DESIGNING COM+ APPLICATIONS
Given the complexity of creating Windows DNA solutions, the task of creating a problem statement seems almost trivial. However, even the simplest statement causes the company to focus. For example, the preceding statement indicates an objective of 300% increase in sales. This statement can’t be made lightly. The exact percentage will have to be approved at a high level of management. This will cause discussion among company management that will attract attention to the project and sharpen everyone’s focus. One benefit of a good design process is that it involves the entire organization and demands buy-in from all quarters.
56
Understanding COM+ Applications PART I
the problem statement. Finally, some stakeholders will be threatened by the project and try at every turn to have it cancelled. The point is that a software development effort can’t truly succeed without the buy-in of every stakeholder at the organization.
Key Principle To the greatest extent possible, all stakeholders must eventually buy in to the development effort.
To identify the functional requirements for the system, work with the champion to identify all stakeholders. These stakeholders are then invited to a series of meetings to discuss the project and its requirements. I refer to these meetings as facilitated sessions because a knowledgeable mediator who can keep the group on track guides the meeting, derives requirements, and presses for buy-in. Facilitating a meeting of stakeholders can be dicey at best. In these meetings, you will have both advocates and enemies. The mediator must be skilled and experienced at handling such groups. There’s no formula for how to handle a group of stakeholders, but my experience is that these meetings often clear the way for a successful project. In the facilitated session, begin by introducing all the stakeholders and explaining to them the purpose of the meeting and the process we will follow. The idea here is to immediately set ground rules to keep the project enemies from openly criticizing the project as a whole. The facilitator must be seen as controlling the meeting. If the session turns into a free-for-all, the project enemies will make the meeting unproductive. After the format and rules are explained, invite the stakeholders to state the functions they want to see in the system. Furthermore, functional requirements should be stated regardless of time or cost. The purpose of this part of the meeting is to extract every possible idea from every stakeholder in the room. Many of the ideas will never get into the project, but we want to make sure that every stakeholder’s idea is heard. One key to getting buy-in is that each person’s idea must be captured and treated with respect by the group. The facilitator must take great care to guide this part of the process. No one should be allowed to criticize an idea at this point, and everyone should be encouraged to state all ideas no matter how wild they might seem. After creating a list of functions, place them before the group on a dry-erase board or large sheets of paper. Now, ask the group to prioritize the list. Prioritization is done by using a simple A-B-C scheme. The group will be asked to vote A, B, or C for each function listed. From this vote, the facilitator will declare each function as A, B, or C based on the following definitions:
Designing COM+ Applications CHAPTER 3
Priority A B C
57
Definition Absolutely required Enhances the product Nice to have but not crucial
Obviously, various stakeholders will have different ideas about what requirements are absolutely essential. However, the process demands that they convince others in the room that the functionality is essential; otherwise, the group will cumulatively vote for a B or even a C. This group ranking is critical for eliminating extraneous features and constraining the scope of the project. We also see that stakeholders are willing to accept the judgment of their colleagues in regard to the feature set. This process leads to buy-in because each stakeholder has a chance to make his case whether he ultimately prevails. As an example, Table 3.1 shows the typical output from a facilitated session with stakeholders. Notice that each function is stated simply with limited detail. TABLE 3.1
Prioritized Requirements
Ranking
Description
Personalization and Membership
A
Search and Navigation Improvements
A
Promotional Enhancements
A
Usage Analysis
B
Online Reviews
C
Users should be able to personalize, create wish lists, and use shopping carts. Users should be able to search by various keys and navigate the site based on these keys. Site should offer coupons and email announcements. We need to understand how promotional activities result in sales. Users should be able to review books online.
Assessing Requirements After the prioritized list of requirements is complete, meet alone with the champion. Ultimately, the champion has veto power over any decisions made by the group. A wise champion will be careful, however. Throwing out the stakeholders’ work will create dissention and a feeling that the sessions were simply pandering and a waste of time. In the end, however, the champion must be comfortable that the list of features can be presented to management and successfully funded.
3 DESIGNING COM+ APPLICATIONS
Function
58
Understanding COM+ Applications PART I
To aid in the assessment of the function list, create a new level of detailed description. To arrive at the next level of detail, the champion is asked to identify domain experts for each feature on the prioritized list. A domain expert is someone highly knowledgeable in the requirements for the function. For example, the champion might identify a salesperson as the domain expert for promotional features. Allowing the champion to identify domain experts helps eliminate project enemies from the process. Everyone had a chance to be heard at the initial meeting, but if isolating a person is required to ensure success, this is where it happens. For each feature rated A or B, define several options for implementing the feature based on interviews with the domain expert. In these interviews, we ask the domain expert to identify the ultimate solution for the problem regardless of cost and time, a middle-of-the-road solution that considers cost and time, and a “bare bones” solution that will work in a pinch. The idea is to give the champion a large menu of options from which she can assemble a system that fits into her priorities, time, and budget. At the end of this process, we produce the first deliverable, or artifact. The artifact is a document capturing all the functional requirements and showing a high-level view of the system. I like to think of this artifact as a restaurant menu. The idea is to allow the champion to see all the features and implementation options gathered throughout the meetings and interviews. Provide rough cost estimates so that a system can be envisioned and presented to management for approval and funding. The process outlined here can take considerable time. For an average Windows DNA project, this can be 40–80 hours. If you could have dedicated access to every stakeholder, you might reasonably assume that you could accomplish the process in two weeks. However, stakeholders are never completely dedicated to the process. Therefore, I find that it typically takes 4–8 weeks before the final artifact is reviewed, approved, and funded. This can easily be the first crisis point for your project. I find that many customers still believe that Windows applications can be created in a matter of weeks, on a shoestring budget, with poorly defined and shifting requirements. In fact, I’ve lost jobs because the customer lost faith in the process and believed it took too long. Perhaps you’ve had this experience and right now you are thinking, “This is all great, but I’ll never be allowed to do it.” I understand completely. The reality of software development remains: Nearly half of all software projects are canceled before they are completed. Why? In my experience, software projects fail because the stakeholders didn’t understand the need for design and lost faith in the process. So your choice is simple: do you want your software project to fail, or do you want to take more time?
Describing the System After the functional requirements are gathered, you are ready to create a text-based model of the system. Designing a system is really a process of creating even more detailed models. This enables the system to be evaluated and changed more easily than if you move directly
Designing COM+ Applications CHAPTER 3
59
from requirements to code. The text-based model of the system is created through a set of use cases. A use case is a description of the set of steps necessary to accomplish a function. A complete set of use case describes at least 80% of the system and is the basis for more detailed modeling.
Identifying Actors and Use Cases Before you can create a use case, you must identify the actors involved in your system. Actors are people or other systems that will interact with your system. The key to identifying an actor is that the person or system must receive something of value from your system. For example, a customer might receive a product from the system, or the company billing system might receive the required information to create an invoice. When defining actors, be careful to define them generically based on role and not based on job title. This is because many people in an organization can fill a role. For example, if all the sales personnel are at a meeting, the company vice president might pick up the phone to take an order, thus becoming a salesperson. Typical actors include customer, salesperson, and manager.
Naming actors and use cases takes practice, but remember that an actor interacts with the system to receive a value. The use case is a functional name of the value received. A simple example is to name an actor as “customer” and the use case as “purchase product.” In this example, the customer interacts with the system and the value received is a product. As I stated earlier, system design is really a set of models used to describe the system. These drawings and descriptions are the blueprints used to create the system. Imagine a set of blueprints for a house or electrical schematics for a computer. In both cases, you can imagine a set of drawings that completely defines the product to build. Each set of drawings also has its own set of symbols that are unique to the profession in which they are used. Software modeling is no different. In our profession, we use the Unified Modeling Language (UML) to represent the elements in the system. UML is a series of symbols that help us create the various artifacts in the design process. UML can be used for simple models such as use cases or more complex models that define the entire system in great detail. I will use UML throughout the rest of the chapter to create various models. Although You will ultimately create a complete text-base set of use cases, the first artifact you create in the modeling process is the use case model. This model is a visual representation of the actors and the use cases. Although this model is extremely simple, I have found that it
3 DESIGNING COM+ APPLICATIONS
When the actors are identified, you can match them with the use cases they affect. When initially identifying use cases, limit them to simple one-line phrases. Later, you will expand the detail in each use case, but for now you are trying to create a system outline based on the actors and use cases.
60
Understanding COM+ Applications PART I
serves as an invaluable graphical overview of the system. To create the use case model, we use the UML symbol for an actor and the UML symbol for a use case. Figure 3.1 shows these symbols.
Actor
Use Case
FIGURE 3.1 The UML symbols for an actor and a use case.
When modeling use case, we use an arrow to indicate how the actor interacts with the system. If the actor initiates the use case, the arrow moves from the actor to the use case. If the use case is initiated by the system itself, the arrow moves from the use case to the actor. Figure 3.2 shows a simple use case model for a customer interacting with a Web site.
Purchase Product Customer
Show Promotions
FIGURE 3.2 A simple use case model.
Documenting the Use Cases Along with the use case model, you must create the text-based documentation mentioned earlier. Documenting the use case provides the underlying detail necessary to fully understand how the actor interacts with the system. Information required for the use case documentation is typically gathered through one-on-one interviews with domain experts and other interested parties. Just like the facilitated sessions I discussed earlier, the interview process requires experience and skill to complete successfully. During the interview process, I typically ask the person to describe the sequence of events they go through to complete a task. For example, you might ask the person to describe how they take and process an order. The person will then explain what forms are filled out, what departments are notified, and other key pieces of information.
Designing COM+ Applications CHAPTER 3
61
The goal for the application architect is to completely understand the process so that it can faithfully be rendered in code. Sometimes, the architect might know key pieces of information based on previous discussions or even his own experience. However, I often find that certain surprises emerge during these interviews. In my experience, all companies have discrepancies between the way they think they operate and how they actually operate. When interviewing personnel for use case documentation, it’s important to document how the business actually operates. In fact, it’s often a good idea to have management personnel present during the interview process so that they can hear directly from the employees how work is actually accomplished. This often leads to a reengineering of the business processes within the company. Interviews lead to discovery; discovery leads to improvement—it’s the improved processes that you want to build into your final software. When you document use cases, use a Microsoft Word template and fill in the required information. In the following sections, I will go over each part of the template. Figure 3.3 shows a completed use case that describes how to log in to a Web site.
3 DESIGNING COM+ APPLICATIONS
FIGURE 3.3 A typical use case document.
Header Section This section has the key identifying information for the use case. Included in this section are the name of the use case, the primary and secondary actors, the domain experts, the revision number, and the revision date. All this information is easily retrieved from the information already captured in the design process. For the use case shown in Figure 3.3, the following information was captured:
62
Understanding COM+ Applications PART I
• Use Case Name: Use Case—Log In • Primary Actor: Customer • Secondary Actor(s): Administrator • Domain Expert(s): Scot Hillier • Revision: 1.00 • Revised Date: 12/20/99
Use Case Purpose This section defines the value received by the actor from the use case. Stating the purpose forces you to justify the reason this use case was created. Identifying the correct number of use cases requires experience. For example, would you create a separate use case for adding, editing, and deleting records in a database, or would you create just one? Answers to these questions depend on the system you are designing. If you can’t clearly state the value received by the actor, you haven’t correctly defined the use case. For the use case shown in Figure 3.3, the following purpose was stated: • use case Purpose: The purpose of this use case is to describe how users log in to the Web site.
Conditions and Rules This section defines the preconditions, postconditions, and business rules associated with the use case. Preconditions must be met before the use case begins. Postconditions are the output, or value, provided to the actor. Business rules are the governing statements that determine how the application will function.
Key Principle Failure to properly identify business rules and conditions is the cause of nearly all cost and schedule overruns.
Throughout the interview process, you must be on guard to properly identify conditions and rules. These conditions and rules are the cause of nearly all middevelopment delays in improperly designed software. How many times have you created a software solution only to have the customer tell you that the business doesn’t work the way the software does? For the use case shown in Figure 3.3, the following information was gathered: • The Use Case Begins When: The customer navigates the browser to the Web site. • Precondition(s): 1) A valid customer account and channel file exist. 2) A valid customer-administration LDAP account exists.
Designing COM+ Applications CHAPTER 3
63
• Postcondition(s): The customer is logged in. • Business Rules: If the customer account has been inactive for 6 months, disable the account.
Scenario List This section describes the various scenarios that can occur to fulfill the use case. A scenario is simply a set of steps that occur in the use case. In all use cases, you have three different types of scenarios: Perfect, Alternate, and Exception. • The Perfect scenario is what developers always consider when building an application— even if they don’t have a design process. The Perfect scenario is the set of steps that occur if there are no problems. This is generally the easiest and best-understood of all the scenarios. • Alternate scenarios represent variations on the Perfect scenario. These sets of steps accomplish the same task, but not in the most straightforward way. In my example, for instance, a user might log in through an HTML form, but if he has logged in before, you can use a cookie to authenticate. The cookie authentication is an Alternate scenario.
In poorly designed systems, Alternate and Exception scenarios are always handled as the code is written. Quite often, this leads to confusing and strange system behavior that leaves users unsatisfied. For the use case shown in Figure 3.3, the following scenarios were defined: • Scenario List: 1) Perfect: First Log In 2) Alternate: Cookie Authentication 3) Exception: Improper username or password
Flow of Events After all the scenarios are defined, document the series of steps for each of them. These steps are contained in this section of the use case documentation. The flow of events is a narrative flow chart that can be easily followed to understand the system behavior. For the use case shown in Figure 3.3, the following steps were identified: • Basic Path: First Log-In The use case begins when the customer navigates to the site. Because the customer has never been to the site before, she is presented with a home page that welcomes her and asks her to log in. The customer clicks the log-in link and is taken to an HTML form. The form is filled out with a valid username and password.
3 DESIGNING COM+ APPLICATIONS
• Exceptions are the set of steps executed when a problem occurs. Every use case must deal gracefully with errors. What happens if the username and password are wrong? What if the credit card isn’t valid?
64
Understanding COM+ Applications PART I
If the username or password is incorrect, an error occurs (see improper user name or password). When authenticated, the system puts a cookie on the customer’s machine so future log in is unnecessary. • Alternate Path: Cookie Authentication If a customer has logged in previously, the installed cookie is used to authenticate her. • Exceptions Any improper login results in an error message and a return to the start page.
Flow Charts The flow of events created for the use case is useful in understanding how value is returned to the actor; however, sometimes a visual representation can be useful as well. To this end, create simple flow charts for each use case. For the use case shown in Figure 3.3, Figure 3.4 shows a flow chart.
Does user have a cookie?
[ No ]
[ Yes ]
Enter User Name and Password
[ No ]
[ No ]
Are User Name and Password Authentic?
Is cookie valid? [ Yes ]
[ Yes ]
User Name Cookies written to client. Logged In
FIGURE 3.4 Use flow charts to help describe the flow of events.
Designing COM+ Applications CHAPTER 3
65
Creating the Paper Prototype After the use cases are complete, you will have a strong description of the system and how it functions. You should have a good understanding of the system flow and the rules by which it will interact with users. At this point, you are ready to create the paper prototype. The paper prototype, also know as the storyboard, is a set of drawings that shows every screen in the system. The objective is to bring the use cases to life and prove that your system will work when built. At first, you will be tempted to create the paper prototype by using Visual InterDev to mock up screens and then show them to the user. Nothing could be worse. When you use a development tool to create the paper prototype, two bad things happen: • Users are reluctant to mark up anything that looks complete. Screen shots from your computer have a professional finish that makes it look like they are difficult to change. This will stifle user input. • After you commit time to create the screens, you will be reluctant to throw them away. As a result, you will be stuck with much of the work whether it’s good or not. I have seen many so-called prototypes end up being the final product because no one wanted to throw them away.
After you convince yourself, take the screens to your users. Place the screens in a stack in front of the users and ask them to use the application. As they “click,” move the screens in the stack showing them how the application works. Make notes directly on the screens where problems arise. Going through the paper prototype with the users produces profound benefits. Perhaps the most important benefit is that it sets the expectations of the users. What they see in the paper prototype is exactly what they will see in the final product. If users never see any screens until the product is complete, they are bound to be dissatisfied. However, if they are involved throughout the process, delivering the software is anticlimactic. This is exactly what you want. Keep modifying the screens until the users are satisfied. You are then ready to define the software that goes behind the screens.
DESIGNING COM+ APPLICATIONS
The correct way to create a paper prototype is with a drawing program like Visio, or better yet, paper and pencil. You want the user to feel that the screens are easily changed and only represent a concept that can be modified. You’ll create a full set of screens as you envision the system. Then take the screens and validate them against the use cases we created. In this process, walk through every scenario in every use case and prove to yourself that they will work with your system.
3
66
Understanding COM+ Applications PART I
System Modeling To define how the software will be written to code the screens, we again return to modeling. This time, however, you will be modeling the actual components that live behind the screens. These models become the input used by the developers to create the system.
Database Model The first model we create is the database model. Database models are perhaps the best understood of all system models. In nearly all projects, even poorly designed ones, some kind of database model will be created. Properly modeling a database is beyond the scope of this book, but most developers are at least familiar with the process of identifying entities and relationships. Entities in database design are similar to classes in object-oriented (OO) design. You can also think of them as nouns. These are the items involved in the business problem. Typical entities include customers, invoices, and products. Don’t confuse entities with actors, which must derive value from the system. Entities are part of the informational structure of the system. Each entity in the database has relationships with other entities. Database design typically uses one-to-many and many-to-many relationships. Developers are generally familiar with these concepts and, in my experience, this is a strength of the programming community. Therefore, I won’t spend time discussing them in detail. Figure 3.5 shows a typical database model.
FIGURE 3.5 Database models show entities and relationships.
Designing COM+ Applications CHAPTER 3
67
Logical Model Although most developers can create a database model, few have actually created a logical model. A logical model represents the software classes in the system. Just as a database model can be used to create a database, the logical model can be used to create COM+ components. Almost anyone can learn to successfully create use cases, but jumping from use cases to a logical model takes a tremendous amount of experience. Often, companies will employ “business analysts” to produce use cases, but the logical model can be created only by a true software architect. The goal of a logical model is to create a completely defined model that contains the name and definition of every class in the application with 80% accuracy. That’s right—the software architect must define every class, every method, and every property without ever writing a single line of code. This is why the software architect must be an experienced developer who understands the use cases completely. So how does someone begin to define every class, method, and property for a large, complex system? The answer is to use a framework. If you approach the design of every system as a unique endeavor, you are destined to fail. Instead, you must have a repeatable methodology for achieving success. To use current trendy terminology, you need a pattern.
As you will see later in this book, we normally build the logical model from the data sources to the Web pages. Beginning with this idea, one of the first things you might do is to define a data class that accesses the Windows 2000 Active Directory to return identifying information for the user. You could say, for example, that you’d like to welcome the user to your site by using their nickname or “friendly name.” Your login could consist of looking for this information. If you find a friendly name, the login is authentic; otherwise it’s not. To define your new data class, again use UML. UML provides symbols for defining classes as well as components such as ActiveX DLLs. The UML-compliant Microsoft Visual Modeler can be used to create logical models. If you created a new class named CData, it would appear in the Visual Modeler as shown in Figure 3.6.
DESIGNING COM+ APPLICATIONS
A pattern is a predefined solution to a problem. Although every software development project has some unique features, most Windows DNA applications have more in common than not. For this reason, you can create a development pattern that leads to success. Essentially, this book is dedicated to developing that pattern. Therefore, you will better understand how to make the leap from use cases to logical model by the time you reach the project in Chapter 16. For now, stick to the simple process defined in the previous use case—that is, define a system that allows you to log in to a Web site.
3
68
Understanding COM+ Applications PART I
CData
FIGURE 3.6 The UML symbol for a class.
Along with the class itself, we will define a method to return the friendly name of the user. Even without writing code, we have enough information to define the method. First, we can decide on a name for our method; we’ll call it GetFriendlyName. Next, we know that the inputs to the function must be the username and password. Finally, the output will be the friendly name as a String. Therefore we could define the method and show it in the UML model of Figure 3.7. CData Public Function_ GetFriendlyName
FIGURE 3.7 Defining methods in UML.
UML classes can show as much information about the class as you want. In addition to function names, you can show input and output parameters, interfaces, and data types. The idea is to provide enough information so that a competent programmer can create the class. All that needs to be done is to fill in the code within the method definitions for each class and the software will be complete. When I present this concept of designing down to the method level, different people have various reactions. Some developers enthusiastically declare that they would love to receive this kind of detail from an architect. Others are suspicious, almost afraid that their job is being taken away. To me, the point is to create great software. I know from experience that the people writing the code are the least likely to perform rigorous design. Instead, the plan needs to be given to the team at the outset. This is the equivalent of a building architect giving blueprints to the general contractor. No one wants the carpenters deciding where the bathrooms go as they build the house. In the end, the logical model forms the foundation of the OO design. Each class must be properly designed, documented, and delivered to the development team. Keep in mind that the goal of design is 80% accuracy. Problems certainly will arise during the development process;
Designing COM+ Applications CHAPTER 3
69
however, my experience is that design is no longer cost-effective when you try to reach beyond the 80% mark.
Three-Tier Diagram One of the most useful ways to present the classes you’ve designed is through a three-tier diagram. The three-tier diagram shows all the classes you’ve designed broken into their associated tier. In this way, developers can see what classes make up data services, business services, and user services. The three-tier diagram doesn’t require any new work on your part; it’s simply a convenient way of showing the required classes. Figure 3.8 shows a typical three-tier diagram. order.asp (from ASP)
contents.asp (from ASP)
CUpdateCart (from Cart)
CPutOrder (from Cart)
CPutCartItem (from Cart)
CDeleteCartItem (from Cart)
3
CMembership (from Membership)
CPutADSIAddress (from Membership)
CGetADSIFriendlyName (from Membership)
CGetBookDetails (from Books)
results.asp (from ASP) CBooks (from Books)
CGetTitlesByTitle (from Books)
FIGURE 3.8 Three-tier diagrams help developers understand a system.
CGetTitlesByPublisher (from books) CGetTitlesByAuthor (from books)
DESIGNING COM+ APPLICATIONS
CPutADSIAAddress (from Membership)
shipping.asp (from ASP)
details.asp (from ASP)
CGetCartDetails (from Cart)
CCart (from Cart)
home.asp (from ASP)
validate.asp (from ASP)
CCreateCart (from Cart)
70
Understanding COM+ Applications PART I
EXERCISE 3.1 Using Visual Modeler The Microsoft Visual Modeler can be used to help design and build COM+ applications. In this exercise, you will use Visual Basic and the Microsoft Visual Modeler to create an application that retrieves information about resources available on a network machine.
Building the New Model Step 1 In the Windows Explorer, create a new directory named COM+/MODELER. Step 2 Start a new Standard EXE project in Visual Basic. Because this project uses the Visual Modeler, you must set up Visual Basic to use round-trip engineering by enabling the Visual Modeler add-ins. Open the Add-In Manager by selecting Add-In Manager from the Add-Ins menu. In the Add-In Manager (see Figure 3.9), activate Visual Modeler Add-In and Visual Modeler Menus Add-In. Visual Modeler expects these add-ins to be present whenever Visual Basic is running. Therefore, check the Load on Startup option for each add-in. Click OK to close the Add-In Manager.
FIGURE 3.9 Enable the Visual Modeler add-ins to load on startup.
Step 3 Open the project properties dialog by selecting Project1 Properties from the Project menu. In the project properties dialog, change the name of the project to FrontEnd. Close the dialog.
Designing COM+ Applications CHAPTER 3
71
Step 4 Select Form1 in Project Explorer. In the properties window, change the name of Form1 to frmClient. Step 5 Add a new ActiveX DLL project to Visual Basic by selecting Add Project from the File menu. This component will be the business object you will use to retrieve information about a host computer. Open the project properties dialog for the ActiveX DLL project. Change the name of the project to MemoryUsage. While the dialog is open, make sure that the threading model is set to apartment threading. Step 6 Select Class1 in the Project Explorer. Change the name of the class to DataClass. Step 7 Save your project into the directory you created earlier.
Step 9 The Visual Modeler add-in presents you with the model selection dialog (see Figure 3.10). Click the New button to build a new model. This will start Visual Modeler.
FIGURE 3.10 Select to create a new model.
3 DESIGNING COM+ APPLICATIONS
Step 8 Visual Modeler works with Visual Basic to build models from code and code from models. This process, round-trip engineering, is used to create a new model from this project. Select the FrontEnd project in the Project Explorer. Create a new model for this project by selecting Visual Modeler and then Reverse Engineering Wizard from the Add-Ins menu.
72
Understanding COM+ Applications PART I
NOTE Sometimes when you reverse engineer a form, Visual Modeler will give an error stating that no project was selected. If this happens, save your work and then reverse engineer the project directly from Visual Modeler by choosing Visual Basic and then Reverse Engineering Wizard from the Tools menu.
Step 10 The first step of the Reverse Engineering Wizard is an introduction screen. Click Next to move to the next step. Step 11 The second step of the wizard (see Figure 3.11) asks you to select which components to reverse engineer. The wizard works with only one project at a time, so it displays only the form from the FrontEnd project, not the class from the ActiveX DLL. Accept the default settings here and click Next.
FIGURE 3.11 Accept the default settings to reverse engineer the FrontEnd project.
Step 12 The third step of the wizard (see Figure 3.12) asks you to assign the form to one of the three tiers in the model. Carefully drag frmClient to the User Services folder and drop it. The Visual Modeler displays the form as a member of the user services layer. Click Next.
Designing COM+ Applications CHAPTER 3
73
FIGURE 3.12 Assign the form to the User Services layer.
Step 14 Immediately save the model to the directory you created earlier. Name the file modeler.mdl. Step 15 Minimize Visual Modeler and return to Visual Basic. Now select the MemoryUsage project from the Project Explorer. Reverse engineer this project by selecting Visual Modeler and then Reverse Engineering Wizard from the Add-Ins menu. When the model selection dialog opens (see Figure 3.13), select to reverse engineer into the same model you built for the FrontEnd project.
FIGURE 3.13 Select to add to the existing model.
3 DESIGNING COM+ APPLICATIONS
Step 13 The wizard now displays a summary of the conversion work. Read the summary and then click Finish to build the model. When the wizard is finished, you will see a component labeled frmClient in the user services layer.
74
Understanding COM+ Applications PART I
Step 16 This time, work your way through the wizard, but make the DataClass object part of the business services layer. When you have both the form and the class in the model, save the model. Step 17 With Visual Modeler, you can create properties, methods, and associations for objects in the model. First, we’ll create an association between the form and the class. On the Visual Modeler toolbar, carefully locate the Unidirectional Association button (shown in the margin next to this paragraph). This button allows you to specify that the form will contain an instance of the class. Step 18 Click the Unidirectional Association button and drag an association from the form to the class. When the line appears showing the association, double-click it to open the Association Specification dialog. Step 19 The Association Specification dialog allows you to establish how code is generated from the relationship. On the General tab (see Figure 3.14), you can name the roles that each component fulfills. In the dialog, role A is the class and role B is the form. Name the role for A as objData. Name the role for B as objFrontEnd.
FIGURE 3.14 Name the roles for the object and form.
Step 20 Click the Visual Basic A tab. This tab designates how property procedures should be created for the component in role A (see Figure 3.15). When you first create the relationship,
Designing COM+ Applications CHAPTER 3
75
properties aren’t automatically created. However, you can change these characteristics. Click the Edit Set button to edit the property procedure characteristics. This opens the Options dialog.
FIGURE 3.15 Use the Edit Set button to affect code generation for the relationship.
FIGURE 3.16 Use the Clone button to create a new set of relationship attributes.
DESIGNING COM+ APPLICATIONS
Step 21 In the Options dialog (see Figure 3.16), you can create new sets of property procedure attributes. Click the Clone button to define a new set of property procedure characteristics. You will be prompted to name the new set. When prompted, name the new set Child. Click OK.
3
76
Understanding COM+ Applications PART I
Step 22 The Child set now is a clone of the default set. In the characteristics list, change the following characteristics: New Generate Get Operator Generate Set Operator
True True True
Figure 3.17 shows the completed set of new attributes.
FIGURE 3.17 Change the relationship attributes after cloning.
Step 23 Changing the characteristics for code generation will create an instance of the class module and generate a set of property procedures. After you change the characteristics for the Child set, click OK to exit the editing dialog. Step 24 Now that you’ve created a new set of characteristics, choose the Child set for the object in role A. Click OK again to exit the specification dialog. Step 25 Right-click the DataClass object in Visual Modeler and select Open Specification. This opens the specification dialog in which you can add new properties and methods (see Figure 3.18). Click the Methods tab.
Designing COM+ Applications CHAPTER 3
77
FIGURE 3.18 The specification dialog allows you to create new methods for a component.
FIGURE 3.19 Close the specification dialog when the method is defined.
Step 27 Save the model.
3 DESIGNING COM+ APPLICATIONS
Step 26 In the list view window of the Methods tab of the specification dialog, right-click and select Insert. This adds a new method template called NewMethod. Change the name of this method to Process by typing directly into the list in which the new method appears. Set the return type of the method to Long by using the drop-down list. Click OK to close the specification dialog. Figure 3.19 shows the completed method definition.
78
Understanding COM+ Applications PART I
Coding the Application Step 28 Now that you’ve added an association and a method, you are ready to generate code. Select to generate code for both the form and the class by choosing Select All from the Edit menu. Then start the Code Generation Wizard by choosing Generate Code from the Tools menu. Step 29 The first step of the wizard is just an introduction screen. Click Next to continue. Step 30 In the second step of the wizard (see Figure 3.20), you are asked to select the classes you want to generate code for. Notice in this dialog that you can’t generate code directly for forms. Visual Modeler generates only new classes. To use Visual Modeler with a form, the form must already exist in a project. Click Next.
FIGURE 3.20 Select the classes to generate code.
Step 31 In the wizard’s third step, you can preview the code it generates. This lets you modify the definitions of properties and methods before generating the code. Click Next. Step 32 The wizard’s fourth step allows you to specify general coding options such as error handling and debugging code (see Figure 3.21). Clear all these check boxes except Save Model and Project Before Generating Code. Click Next.
Designing COM+ Applications CHAPTER 3
79
FIGURE 3.21 Clear the special coding options before generating code.
Step 33 The fifth step is a summary of work to be done by the wizard. Review this screen and then click Finish to generate your code.
Step 35 Close Visual Modeler and return to Visual Basic. When you return to VB, you will see that Visual Modeler has added the Process method as well as some comments that contain information about the model. Also notice that the Project Explorer now contains an entry for the model in the Related Documents folder. Step 36 Although Visual Modeler generates the members for a class, it doesn’t implement the class. You must still write the code yourself. In this exercise, use the GlobalMemoryStatus API call to return information about resource usage on a target machine. In the [General][Declarations] section of DataClass, add the following code to declare the API call and associated structure. You might want to use the Visual Basic API Viewer to retrieve the definition for the API call and structure. Private Declare Sub GlobalMemoryStatus Lib “kernel32” _ (lpBuffer As MEMORYSTATUS) ‘Structure for data Private Type MEMORYSTATUS
DESIGNING COM+ APPLICATIONS
Step 34 When the wizard is finished, close it and save your model.
3
80
Understanding COM+ Applications PART I dwLength As Long dwMemoryLoad As Long dwTotalPhys As Long dwAvailPhys As Long dwTotalPageFile As Long dwAvailPageFile As Long dwTotalVirtual As Long dwAvailVirtual As Long End Type
Step 37 The Process method makes the API call and returns information about memory usage. The GlobalMemoryStatus API can return a lot of different information, but in this exercise, you will return an indicator of the percentage of memory in use. Add the following code to the Process method to retrieve the information and pass it to the calling client: On Error GoTo ProcessErr ‘Variables Dim objMemory As MEMORYSTATUS ‘Get System Data objMemory.dwLength = Len(objMemory) GlobalMemoryStatus objMemory Process = objMemory.dwMemoryLoad Exit Function ProcessErr: App.StartLogging “”, vbLogAuto App.LogEvent Err.Description, vbLogEventTypeError
Creating the Front End Step 38 The front end for this application uses a form to display the available resources for any machine that has the MemoryUsage component installed. Open frmClient in Visual Basic. Figure 3.22 shows how the form is constructed.
Designing COM+ Applications CHAPTER 3
81
FIGURE 3.22 This is the front end for the exercise.
The form uses a single TextBox and a ProgessBar control. If a ProgressBar control isn’t in your toolbox, you must insert it by selecting Microsoft Windows Common Controls 6.0 in the components dialog. Set the design-time properties as follows for the controls on the form: Control Form Label
Setting Memory Usage
Name Caption
lblMachine Machine Name
Name Text
txtMachine
Leave empty
CommandButton
Name Caption
cmdGO GO!
Label
Name Caption
lblLoad Memory Load
ProgressBar
Name
pbrLoad
TextBox
Step 39 You want this form to be able to call the MemoryUsage component on any machine, so we will use late binding to create it. Therefore, add the following code to the [General][Declarations] section: Private objBusiness As Object
Step 40 All the action takes place when the button is clicked. In this event, create an instance based on the name typed into the TextBox and call the object to get a percentage of the memory in use on that machine. The value is then presented in the progress bar. Add the following code to cmdGO_Click to call the business object: Set objBusiness = CreateObject(“MemoryUsage.DataClass”, txtMachine.Text) pbrLoad.Value = objBusiness.Process
3 DESIGNING COM+ APPLICATIONS
Property Caption
82
Understanding COM+ Applications PART I
Step 41 Try running the front end and calling your local computer to see the percentage of memory in use. When you first run this application, you will likely notice that it often returns a value of zero. This is true if you have very little activity on your system. The memory load will change, however, if you analyze the system while performing an intense operation such as a query.
CHAPTER
COM+ Application Fundamentals
4
IN THIS CHAPTER • Understanding Contexts • Object Activation
84
88
• Managing Shared Properties
102
84
Understanding COM+ Applications PART I
The history of business application development on the Windows platform has been one of increasingly complex frameworks and abstractions designed to decrease development times while enhancing performance. I often like to talk about the days before Visual Basic and the effort required to create a Windows application. In the Windows world before 1991, creating a Windows application meant coding a tremendous amount of tedious infrastructure by hand. For example, you had to create all the code necessary to generate and display a window—for each form in the application. The attraction of a tool such as Visual Basic is that the infrastructure code is completed for you. Forms can be treated as entities that already exist—you don’t have to explicitly create them. The beauty of this framework is that developers are free to focus on the business problem and not the operating system. This philosophy reached a significant level of maturity with the release of the Microsoft Transaction Server (MTS). What Visual Basic did for form creation, MTS did for operating system services. Before MTS, if you wanted to create an application that would scale to thousands of users, you had to create your own infrastructure code to manage threads, memory, and database connections. With the release of MTS, developers were again freed to concentrate on the business problem and simply use the services provided by MTS. COM+ is the next evolutionary step for business application developers. COM+ provides the same abstracted access to operating system services introduced by MTS, but completely integrates these features with the operating system itself. MTS was a separate product; COM+ is an integral part of the operating system. In this chapter, we will examine the fundamental concepts and services that constitute COM+ and provide a strong foundation for the development of a distributed system architecture.
Understanding Contexts COM+ has many features and can be described from many different perspectives, but the simplest way to think of COM+ is as a safe and comfortable environment for your objects. Within this safe environment, COM+ provides security, support, and meaning to your objects. To achieve support and security, COM+ is integrated with the operating system to provide a set of concentric containers, each with its own responsibility. There are three levels of concentric containers: processes, apartments, and contexts. A process is essentially an executable running inside the operating system. A process is started, for example, any time you run a Visual Basic standard EXE. COM+, however, has its own process that runs for each COM+ application you define. This process is dllhost.exe. Component Services starts a copy of dllhost.exe for the purpose of loading your Visual Basic DLLs when they are invoked, and there is a one-to-one mapping between COM+ applications that you define and running instances of dllhost.exe. You can actually see how many COM+ applications are running by examining the task manager shown in Figure 4.1.
COM+ Application Fundamentals CHAPTER 4
85
FIGURE 4.1 Each COM+ application you call creates an instance of dllhost.exe.
Processes are responsible for overall resource management, such as managing the thread pool utilized by objects. dllhost.exe provides this type of resource management for COM+ components.
Inside an apartment are contexts, which contain security and transactional information about components. Contexts are new to COM+ but represent a natural evolution from the context wrappers previously employed by MTS. Both contexts and context wrappers contain the same types of information, but context wrappers are an artificial mechanism inserted by MTS to manage components. In COM+, contexts are an integral part of the operating system and exist whether or not you explicitly place your component in a COM+ application. Figure 4.3 shows the relationship between processes, apartments, and contexts.
4 COM+ APPLICATION FUNDAMENTALS
Inside each process are apartments. Apartments are responsible for implementing the threading model for each component. Even though the process manages the thread pool, the apartments manage whether a thread from the pool is allowed access to a component. Controlling the access to a component is critical for synchronization, the management of thread access to an object’s methods for the purpose of preventing collisions between the threads (see Figure 4.2). If threads were allowed unrestricted access, one thread could easily corrupt the values of variable data being used by another. As discussed previously, COM+ supports single-threaded apartments (STA), multi-threaded apartments (MTA), and thread-neutral apartments (TNA). All Visual Basic components are created as STA components.
86
Understanding COM+ Applications PART I Apartment Object Instance
Thread Pool
Apartment coordinates thread access to the object
FIGURE 4.2 Apartments manage threads to ensure synchronization.
Process: DLLHOST.EXE
Single.Threaded Apartment Context Object Context contains secutity and transaction information Apartment manages synchronization Process manages thread pool
FIGURE 4.3 Process, apartments, and contexts work together in COM+.
Inside a context is an object. Because contexts always exist in COM+, created objects can be placed either inside the existing context of the creator or in a brand new context. COM+ decides whether to create a new context based on whether the component is configured or non-configured. Configured and non-configured are new terms for COM+, but they have simple definitions. Configured components are explicitly placed in COM+ applications using the Component Services explorer. Non-configured components aren’t associated with a COM+ application. Configured components are generally created in a new context, whereas non-configured components are generally created in the context of the calling client. Figure 4.4 shows how configured and non-configured components are placed in a context.
COM+ Application Fundamentals CHAPTER 4
87
Non-configured components are created in the same context as the creator Object Creator
non-configured component
Object Creator's Context Configured components are created in a new context within DLLHOST.EXE Object Creator
Proxy
Object Creator's Context
Stub
configured component
New Context created by COM+
FIGURE 4.4 Configured and non-configured components both reside in contexts.
One supposed advantage of having the object’s context as an integral part of the operating system is that you gain many of the benefits of the context without any additional code. If you want to change the transactional behavior, just change the property value in Component Services. If you want to change the way the object is activated, just change another property. Under MTS, if you wanted to take advantage of the context wrapper, you had to explicitly address the context wrapper from within your DLL code. This was done by getting a reference to the ObjectContext from the MTS object library. After setting a reference to the MTS library, the following code would produce an object reference to the context wrapper: Set MyContext = GetObjectContext()
4 COM+ APPLICATION FUNDAMENTALS
In addition to having their own context, configured components in COM+ have their profiling information stored in the COM+ system catalog when they are added to a COM+ application. This information can then be accessed through the property sheet for the component or through a programmatic object model. It’s this profile that makes COM+ programming so convenient. You can easily change several attributes, such as transactional behavior, without re-coding the component.
88
Understanding COM+ Applications PART I
Once you had a reference to the context wrapper, you were expected to notify the context about certain activities within your component. These notifications helped the context wrapper manage resources for your component. The resource management features still exist in COM+, but in theory you no longer have to code directly to the context. As we continue to investigate the features of COM+, we will return to the idea of communicating with the context.
Object Activation Memory and thread management are at the heart of COM+ services because they have the greatest impact on application scalability. Now with the full integration of the context and operating system, taking advantage of these resource management features can be as simple a placing a DLL under the control of component services. Once a COM+ application is defined, COM+ will automatically take care of creating an object instance within a context (known as activating the object) and even destroy the object when a client is finished with it (known as deactivating the object). Activating and deactivating object instances is the fundamental service on which all distributed applications are based. To understand the importance of activation and deactivation, consider the scenario in which a component is installed in a COM+ application and a client wants to access the component. To create an instance of the component, the client will, of course, have to declare a variable. For the sake of argument, assume that the variable is declared in the [General][Declarations] section of a standard module in the client. The application is written to create an instance of the desired component in Sub Main as soon as the program starts. By design, the instance is then maintained by the client until the application terminates. Now imagine that a user starts the application, uses it for a while, and then goes to lunch. Because the instance variable is maintained with application-level scope, the component in COM+ won’t shut down. This means that valuable memory is used by the business services layer to maintain an instance that isn’t in active use. Now imagine that hundreds of users log in to the application and also go to lunch. Complete disaster. Allowing clients to create and maintain instances in the shared business services layer will destroy scaleability because the resources in the middle tier are limited. Instead, an application should create an instance, make a method call, and then destroy the instance. Objects in the middle tier must live for the minimum amount of time necessary to perform a function. Your response to this situation might be to declare the variable with less scope. Perhaps we can declare a locally scoped variable only in the procedures in which the application needs access to the distributed component. This is certainly a better idea, but not the best. Local variables will cause the component in COM+ to be created and destroyed many times, which doesn’t give COM+ a chance to effectively manage memory. The essential problem in the design of the application is that the client is controlling the management of resources in the middle tier
COM+ Application Fundamentals CHAPTER 4
89
through variable scope. The best solution to instance management is to allow COM+ to automatically manage the instances. Directing COM+ to handle the activation and deactivation of your objects requires enabling two settings for each component in the application. One setting establishes COM+ control over activation, the other over deactivation. The activation setting appears in the component’s property page as Enable Just In Time Activation (see Figure 4.5).
FIGURE 4.5 Activation is enabled from the component’s property sheet.
Deactivating the object requires you to enable a different setting for your component. Deactivation generally occurs at the end of a method call. Thus, COM+ activates an object when a client makes a method call and deactivates the object when the method is complete. You can set up deactivation for a method by examining the property sheet for any method and enabling the setting marked Automatically Deactivate This Object When This Method Returns, as shown in Figure 4.6. This setting is often referred to as the Auto Done property.
4 COM+ APPLICATION FUNDAMENTALS
The phrase just-in-time (JIT) activation found on the property sheet refers to COM+ activating an object instance only immediately before processing any client calls. This means that the resources used by the object are claimed only for the minimum amount of time necessary to process the method call. The beauty of this scheme, however, is that the client is unaware that an object instance is created or destroyed. Only COM+ needs to know whether the object has been activated.
90
Understanding COM+ Applications PART I
FIGURE 4.6 Deactivation is enabled from the method’s property sheet.
Although setting the Auto Done property ensures that the middle tier’s memory resources are properly managed, you might be wondering what happens to the client application if it’s still holding an object variable reference to the now defunct object. What happens when the client uses the same instance variable to call the business object again? The answer is simple. COM+ creates a new instance of the desired object, and it is provided to the calling client. Although the new instance is completely different from the original instance, the client is unaware of any differences and happily accepts services from the new instance.
Key Principle When creating clients that work with COM+ components, declare variables at higher levels of scope rather than constantly creating instances and then setting them to Nothing in the client code. Let the context manage the life of the business object for you. This principle goes by the phrase “Create instances early, release them late.”
All of this is made possible through the work of the COM+ context. This is because when a client holds a reference to an object running under COM+, it actually communicates with the context and not directly with the business object. The context can provide the appearance of a persistent business object to the calling client while COM+ recycles the objects behind the scenes. This is done to ensure that clients can’t create instances in the middle tier and then simply hold them forever. The concept of JIT is well thought out and generally would free you from having to write any special code within your COM+ components, if it only worked as designed. Unfortunately, I
COM+ Application Fundamentals CHAPTER 4
91
have discovered that deactivation doesn’t always occur correctly—particularly if your component generates as an unhandled error. According to the COM+ documentation, unhandled errors are supposed to result in deactivation of the object, but this doesn’t happen.
QUICK CHECK 4.1 Investigating Activation 1. Using the files installed from the CD-ROM, locate the directory Project Templates\Chapter 04\Quick Check 4-1. This directory contains a project you can use to investigate the Auto Done property. 2. On your hard drive, create a new directory with the Windows Explorer named COM+\Quick Check 4.1. Copy the contents from the CD-ROM directory into the new directory you just created. 3. Open the compluserrors.vbp project in Visual Basic. This DLL contains methods that complete successfully as well as generate errors. 4. Compile the DLL project and close Visual Basic. 5. Create a new COM+ application in the Component Services explorer named Just in Time. Install the compiled component into the new COM+ application. 6. Open the property sheet for the component and examine the Activation tab. Notice that the component is already set to enable JIT activation (see Figure 4.7).
4 COM+ APPLICATION FUNDAMENTALS
FIGURE 4.7 Activation is already enabled.
92
Understanding COM+ Applications PART I
7. Expand the tree view until you locate the four methods of the component. Open the property sheet for the method HandledNoContext by right-clicking and selecting Properties. On the General tab, enable the Auto Done property. Repeat this for the UnhandledNoContext method. Don’t make changes to the other two methods. Figure 4.8 shows the tree view expanded to reveal the method names.
FIGURE 4.8 Access the properties of the methods.
8. Open the front end for the project in Visual Basic. This project is contained in the frontend.vbp file. In this project, you need to set a reference to the compiled DLL. 9. After you set the reference, run the front-end project, but do not push the buttons yet. Instead, use the Component Services explorer to display the status view for the Components folder, as shown in Figure 4.9.
FIGURE 4.9 Display the component properties.
COM+ Application Fundamentals CHAPTER 4
93
Notice that even though your front end has done nothing, a single instance has been activated. This is somewhat unexpected because JIT activation implies that the object is created just before you need it. 10. Click the button on the front end form labeled Handled Error Using Auto Done Feature. This method simulates a normal method call to the component with no unhandled errors. 11. Running the method causes the object to deactivate. That’s good! Now the object is no longer consuming resources. Click the button again. The method will run indicating that a new object was activated, and then COM+ will deactivate the object again. This is the preferred behavior. 12. Now click the button labeled Unhandled Error Using Auto Done Feature. This button simulates an unhandled error occurring within the method call. Notice that the object instance remains activated, completely defeating the Auto Done feature. This demonstration shows the danger of generating unhandled errors within COM+ components. You should keep this project available because I will reference it later in my discussion.
Communicating with the Context Although the property settings in the Component Services explorer provide a convenient way to control activation, as we have seen the results can sometimes be incorrect. For this reason, we might want to control the activation and deactivation more directly. This can be done by communicating directly with the object context from our component code. We accomplish this in COM+ in much the same way as with MTS, shown earlier.
FIGURE 4.10 Set a reference to the COM+ Services Type Library.
4 COM+ APPLICATION FUNDAMENTALS
To communicate with the context, we must first set a reference to the COM+ Services Type Library. As with all object model references in Visual Basic, we set it with the References dialog. The reference should be set from within the ActiveX DLL project that will become your business object. Figure 4.10 shows the references dialog box in Visual Basic.
94
Understanding COM+ Applications PART I
Retrieving a reference to the context is done with the COM+ API call GetObjectContext(). This function returns a reference that’s similar to any object reference held and managed in Visual Basic. Therefore, you should simply declare a variable as the appropriate type and fill it with the context reference. The following code shows how to retrieve the context for any business object: Dim objContext As COMSVCSLib.ObjectContext Set objContext = GetObjectContext()
Retrieving the context is always done inside the component associated with COM+. No other part of the application has any use for the context. A component with a reference to its context should never attempt to pass that reference to another object because one component can’t use the context for another component. The context returned by GetObjectContext() applies only to the business object that called the function. Also, components should destroy the object variable carrying the context after they finish using it. This destruction might be an explicit release achieved by setting the variable to the VB keyword Nothing or an implicit release occurring as the result of a variable losing scope. Generally, a COM+ component retrieves a reference to its context and releases that reference all within a single method call. Therefore, each method of the business object repeats the same simple code at the beginning and end of the function. The following code shows a typical template for a component method: Public Function MyFunction() As Boolean On Error GoTo MyFunctionErr ‘Get Object Context Dim objContext As COMSVCSLib.ObjectContext Set objContext = GetObjectContext() ‘Place Code Body Here! ‘Tell COM+ we are done objContext.SetComplete MyFunctionExit: Exit Function MyFunctionErr: ‘Tell COM+ we failed objContext.SetAbort Debug.Print Err.Description App.StartLogging App.Path & “\error.log”, vbLogToFile
COM+ Application Fundamentals CHAPTER 4
95
App.LogEvent Err.Description, vbLogEventTypeError Resume MyFunctionExit End Function
NOTE Because the context code is redundant and must exist in every method, I have included a special add-in on the CD-ROM that you can use to replace the standard Visual Basic procedure dialog box with one that includes the ability to add COM+ code to a function. I find this utility useful in creating all kinds of standard method structures, including error handling and property procedures. Although no exercise in this book assumes that you have the enhanced procedure dialog, you might want to install it to save work. Figure 4.11 shows the Enhanced Procedure dialog.
FIGURE 4.11 The primary reason for referencing the context is to manually control activation or—as you’ll see later—to vote in a transaction. By using the context, a business object can notify COM+ that the current object instance is ready for deactivation. Manually controlling activation and deactivation is accomplished through the SetComplete and SetAbort context methods. The SetComplete method of the context explicitly notifies COM+ that the state of the business object is such that it can be freely deactivated. COM+ can then reuse the resources dedicated to the current instance. If the object causes an error, the SetAbort method tells COM+ that the business object can be deactivated, but that all work performed by the business object has failed. Both SetComplete and SetAbort allow COM+ to reuse the currently occupied resources, but SetAbort is specifically used by COM+ to roll back any transactions that this object supported. Transactions are covered in detail in Chapter 7, “COM+ Transactions,” but for now recognize that both of these methods simply enable activation and deactivation.
4 COM+ APPLICATION FUNDAMENTALS
This dialog box writes template COM+ code for you.
96
Understanding COM+ Applications PART I
At this point, we should pause to summarize the options available for activation control. As a COM+ developer, you can choose either to rely on the automatic activation and deactivation supported by COM+ property settings, or control the process manually with SetComplete and SetAbort. Officially, SetComplete and SetAbort exist only for backward compatibility with MTS components. However, we are going to find that the issue becomes more complicated when your components are involved in transactions. Furthermore, regardless of your implementation, unhandled errors will always prevent deactivation. At this point, you might want to return to Quick Check 4.1 and try out the method calls that use SetComplete to see how they behave.
CAUTION Unhandled errors in COM+ components prevent proper deactivation.
State Management Whether you choose to manage activation manually or through the use of the Auto Done feature, it stands to reason that the client can’t rely on the values of any variables within the component to be persistent across calls. The actual instance provided by COM+ to a client will be different each time the client calls a method. This is why developers are always discussing stateless objects in COM+. Without object instance persistence, storing state in the object is futile.
Key Principle Because COM+ objects must constantly be recycled, they shouldn’t store applications’ state.
Because state can’t be kept in the business objects, we must move the stateful information out of the business object and into another tier. This is accomplished by moving the stateful data into either the database or onto the client machine. Where state is stored generally depends on what type of information you store. In a typical e-commerce application, session identifiers are often kept on the client as cookies, whereas more detailed information, such as shopping cart contents, are kept in the database. The stateless nature of COM+ requires that we construct components to have only methods— no properties. Furthermore, this limitation implies that all data used by a component must be received as arguments to the methods and that each method must execute a complete
COM+ Application Fundamentals CHAPTER 4
97
transaction unto itself. All these design requirements are dictated by COM+’s activation/deactivation features.
Key Principle If you create a method in a component intended for use under COM+, be sure to pass all arguments by value through the ByVal keyword. Because ByVal arguments are passed as a copy of the original data, they are much more efficient in distributed applications.
QUICK CHECK 4.2 Investigating Object State 1. By using the files installed from the CD-ROM, locate the directory Project Templates\Chapter 04\Quick Check 4.2. This directory contains a project you can use to investigate state management. 2. On your hard drive, create a new directory with the Windows Explorer named COM+\Quick Check 4.2. Copy the contents from the CD-ROM directory into the new directory you just created. 3. Open the project named stateful.vbp in Visual Basic. This DLL contains a class module named Customer. The Customer class contains only a single property for the customer’s name. 4. Compile the DLL project and close Visual Basic.
6. Expand the tree view until you locate the two methods for the Name property. One method is Property Get; the other is Property Let. Figure 4.12 shows how they appear in the Component Services explorer. 7. Locate the file frontend.hta. HTA files are special files that use Dynamic HTML (DHTML) but don’t run in a browser. Instead, they run inside a window. These file types are excellent for intranet applications because they don’t have the same security restrictions as a browser. If you double-click the file, it will run as shown in Figure 4.13.
4 COM+ APPLICATION FUNDAMENTALS
5. Create a new COM+ application in the Component Services explorer named State. Install the compiled component into the new COM+ application.
98
Understanding COM+ Applications PART I
FIGURE 4.12 Access the Name properties.
FIGURE 4.13 An HTA front end.
8. This front end will allow you to set and return a value for the Name property. Try it out. You will find that initially everything seems just fine. You should be able to save state within the object. 9. Use the Component Services explorer to enable the Auto Done feature for Property Let and Property Get. This will allow COM+ to deactivate the object between calls to better manage resources. 10. Close the front end and restart the application. Try to save the customer name again. What happens? This time you shouldn’t be able to maintain state in the object.
When it comes to managing state, the only way you can keep stateful information in a COM+ component is to prevent it from being deactivated. However, preventing deactivation means that precious resources are being used to maintain the stateful component. This doesn’t mean that you should never create a stateful component, but you must have strong reasons for doing so. The problem with COM+, however, is that the Auto Done feature isn’t enabled by default. This means that objects aren’t properly deactivated unless you take positive steps to ensure it. In this case, ignorance alone can result in an application that doesn’t scale well.
COM+ Application Fundamentals CHAPTER 4
99
The ObjectControl Interface When first explained, all this creating and destroying can seem a little confusing. After all, we can’t really see the resource recycling. COM+, however, offers you a way to gain notification in your business object when it’s activated or deactivated. This additional control comes in the form of a special interface known as ObjectControl. The ObjectControl interface has three methods: CanBePooled, Activate, and Deactivate. The CanBePooled method notifies COM+ if your object can do true object instance pooling. If your object returns True when COM+ calls this method, COM+ will use object instance pooling to manage your business object. If you remember, however, earlier in this book I stated emphatically that Visual Basic components don’t support object instance pooling. Instead, COM+ simply creates and destroys instances with each client call. So what good is the CanBePooled method? Microsoft has provided CanBePooled for forward compatibility. Microsoft has promised true object instance pooling for Visual Basic components under version 7.0. Objects that implement the CanBePooled method will easily take advantage of pooling without rewriting when Visual Basic supports it. For now, CanBePooled is optional, and returning True from the method won’t do anything.
NOTE Even though returning True from the CanBePooled method currently has no effect on your components, you should be careful about adding this method thoughtlessly to your classes. Visual Basic doesn’t currently support object pooling because the apartment threading model is ill suited to handle the concurrency issues raised by pooling. To successfully pool, an object must support the thread-neutral apartment model (TNA).
COM+ APPLICATION FUNDAMENTALS
The Activate and Deactivate methods are much more useful and interesting than the CanBePooled method. Activate and Deactivate are called by COM+ whenever an object is taken out of or returned to the object pool. The Activate method is called whenever an object is removed from the object pool and assigned to a client. Deactivate occurs when the object is returned to the pool. However, because Visual Basic doesn’t really support pooling, these methods currently fire when an object is created or destroyed. This means that Activate and Deactivate are essentially identical to Initialize and Terminate. Once VB implements true pooling, the Initialize and Terminate events will no longer fire for each client call as they do now. Objects will call Initialize only when they are started the first time and Terminate only when the complete application is shut down. Under those circumstances, Activate and Deactivate become critical substitutes for Initialize and Terminate.
4
100
Understanding COM+ Applications PART I
By using these methods, you can perform special work when your object is activated or deactivated as well as track the life of the object. Activation and deactivation are tracked on a perclient basis. Therefore, the Activate and Deactivate events will always fire in pairs for a given client.
QUICK CHECK 4.3 The ObjectControl Interface 1. Using the files installed from the CD-ROM, locate the directory Project Templates\Chapter 04\Quick Check 4.3. This directory contains a project you can use to investigate the ObjectControl interface. 2. On your hard drive, create a new directory with the Windows Explorer named COM+\Quick Check 4.3. Copy the contents from the CD-ROM directory into the new directory you just created. 3. Open the project named pool.vbp in Visual Basic. In the Pool project, locate the class module named Test and open its code window. The code window should be empty except for an Option Explicit statement. 4. Class Test will implement the ObjectControl interface to receive Activate and Deactivate notifications from COM+. In the [General][Declarations] section of class Test, add the following code to use the ObjectControl interface: Implements COMSVCSLib.ObjectControl
5. To implement the ObjectControl interface, select it from the object box in the code window. When you do, the procedure box will display the three methods: Activate, CanBePooled, and Deactivate. Add these three methods to class Test. 6. The CanBePooled method simply returns a Boolean value indicating whether the object supports pooling. Because Visual Basic components don’t support the TNA threading model, we simply return False from this method: ObjectControl_CanBePooled = False
7. When the Activate and Deactivate methods are called, we simply use the logging capability of the App object to write the event out to a log file. In this way, we can keep track of the life of an instance. Add code to both the Activate and Deactivate methods to write to a log file. The following code shows the completed methods after you add the code: Private Sub ObjectControl_Activate() App.StartLogging App.Path & “\pool.log”, vbLogToFile App.LogEvent “COM+ Test Object Activated!” End Sub
COM+ Application Fundamentals CHAPTER 4
101
Private Sub ObjectControl_Deactivate() App.StartLogging App.Path & “\pool.log”, vbLogToFile App.LogEvent “COM+ Test Object Deactivated!” End Sub
8. This exercise shows how the ObjectContext affects the life cycle of an instance. To do this, add a method to the class that won’t use the Auto Done feature. This will prevent COM+ from deactivating the object. Add the following code to class Test: Public Function KeepAlive() As String ‘This function does not ‘release the business object KeepAlive = “Help! I can’t deactivate!” End Function
9. When creating methods that allow deactivation, you will use the Auto Done feature. Add the following code to create a method that we will use to allow deactivation: Public Function Release() As String ‘This function uses Auto Done Release = “I’m deactivating! Check the log file!”
End Function
10. Compile the DLL project and close Visual Basic. 11. Create a new COM+ application in the Component Services explorer named Pool. Install the compiled component into the new COM+ application. 12. Expand the tree view until you locate the Release method. By using the property sheet, enable the Auto Done feature for this method.
4
13. After you set up the package and component, run the frontend.hta file by double-clicking it. This will allow you to call the methods of the component.
COM+ APPLICATION FUNDAMENTALS
14. Start by calling the KeepAlive method. You should get a message box. At this point, locate and open the log file pool.log. This file will contain a single entry indicating that the Activate method has fired, but the Deactivate method hasn’t. This means that the object is still alive and using resources. This is bad. 15. Now call the Release method. When you receive a return value, open the pool.log file again. This time, notice that both Activate and Deactivate fired. This means that the object instance existed for the minimum amount of time necessary to process your request. This is good.
102
Understanding COM+ Applications PART I
Managing Shared Properties Although I’ve gone to great length to explain the pitfalls of stateful components in a distributed application, sometimes you simply require the ability to retain state in the middle tier. For these times, COM+ provides a facility for maintaining state across the entire application known as the Shared Property Manager (SPM). The Shared Property Manager is a separate facility of COM+ for use with stateful information in the business layer. The Shared Property Manager allows you to create property groups that can subsequently contain individual property data. By using this hierarchical scheme, developers can store and share state information within components in the same COM+ application. The Shared Property Manager creates a sort of global variable that all clients can easily access by using a specific application. The Shared Property Manager consists of three objects in a hierarchy: SharedPropertyGroupManager, SharedPropertyGroup, and SharedProperty. Figure 4.14 shows the SPM object model. SharedPropertyGroupManager SharedPropertyGroups SharedProperty
FIGURE 4.14 The Shared Property Manager can be used to maintain application state.
SharedPropertyGroupManager The topmost object in the hierarchy, SharedPropertyGroupManager, is considered a resource dispenser. Just like the resource dispensers for ODBC and OLEDB, SharedPropertyGroupManager allows resources to be shared among many clients. In this case, the clients share data. SharedPropertyGroupManager properly manages concurrency issues allowing for locking data when it’s being changed by a client. To handle these concurrency issues properly, components that want to share data must be placed within the same package. Never make a call from one package to another and attempt to share state.
SharedPropertyGroup is created through the use of the CreatePropertyGroup method of the object. This object is used to define a group of shared data. This object doesn’t represent the actual shared data, but rather a logical grouping of related data. SharedPropertyGroup
SharedPropertyGroupManager
COM+ Application Fundamentals CHAPTER 4
103
SharedProperty The SharedProperty object actually contains the shared data. This object is returned from the CreateProperty method of the SharedPropertyGroup object. Once this object is created, you can use it to read and write data shared by objects in the same package. Because no calling client knows for sure whether another client has already created this property, each call to SharedProperty is treated as though it were the first call. In this way, the CreateProperty method of SharedPropertyGroup is always executed. The second argument of the CreateProperty method is a Boolean that will be True if SharedProperty already exists. Components use this returned value to determine whether the value of SharedProperty should be initialized or updated.
QUICK CHECK 4.4 The Shared Property Manager 1. By using the files installed from the CD-ROM, locate the directory Project Templates\Chapter 04\Quick Check 4.4. This directory contains a project you can use to investigate the SPM. 2. On your hard drive, create a new directory with the Windows Explorer named COM+\Quick Check 4.4. Copy the contents from the CD-ROM directory into the new directory you just created.
Public Function GetUserNumber() As String ‘Variables Dim blnExists As Boolean ‘***Start Adding Code Here!*** ‘Return Value GetUserNumber = “You are client no. “ & objProperty.Value End Function
4. Within this function, you will add the code to create a shared property. Add your code into the method at the point where the comment Start Adding Code Here! designates.
4 COM+ APPLICATION FUNDAMENTALS
3. Open the project named sharedproperty.vbp in Visual Basic. This DLL contains a class module named Count. This class contains a single method called GetUserNumber. This method will use a global variable to track the number of people who use the application. The following code shows the function definition as it exists when you open the project:
104
Understanding COM+ Applications PART I
This code creates a shared property. Start by adding the following code to create a SharedPropertyGroupManager object: Dim objManager As COMSVCSLib.SharedPropertyGroupManager Set objManager = New COMSVCSLib.SharedPropertyGroupManager
5. Once SharedPropertyGroupManager is created, you can create SharedPropertyGroup. This is done by calling the CreatePropertyGroup method. In this method, you can specify arguments that determine the nature of the locking. You can also specify when the shared property values are destroyed. Add the following code to lock the property whenever it is accessed and destroy the values when the package is shut down: Dim objGroup As COMSVCSLib.SharedPropertyGroup Set objGroup = objManager.CreatePropertyGroup(“Users”, _ LockSetGet, Process, blnExists)
6. Once the property group exists, you can use it to create the property. The SharedProperty object is always created as though it were the very first time. The CreateProperty method returns a True value to the second argument if the property already exists. In this way, no client has to worry about whether another client has already created the property. Add the following code to create the new property and set its value: Dim objProperty As COMSVCSLib.SharedProperty Set objProperty = objGroup.CreateProperty(“Number”, blnExists) ‘Set Property If Not blnExists Then objProperty.Value = 0 objProperty.Value = objProperty.Value + 1
7. Compile the DLL project and close Visual Basic. 8. Create a new COM+ application in the Component Services explorer named Shared. Install the compiled component into the new COM+ application. 9. Expand the tree view until you locate the GetUserNumber method. By using the property sheet for the method, set Enable the Auto Done feature. 10. Now locate and run the file frontend.hta. This file will access the Shared property and increment it each time the file is run. Run several copies to view how the property is incremented. Figure 4.15 shows the results.
COM+ Application Fundamentals CHAPTER 4
105
FIGURE 4.15 These pages count the users of the application.
EXERCISE 4.1 A Simple Tiered Application Now that I’ve presented the fundamental concepts necessary to utilize COM+ applications, you can begin to use them. In this exercise, you will create a simple application that allows you to purchase a product through a Web site. We will build considerably on the ideas of e-commerce throughout the book, but this exercise is designed to whet your appetite.
Creating the COM+ Application Step 1 By using the files installed from the CD-ROM, locate the directory Project Templates\Chapter 04\Exercise 4.1. This directory contains some partially completed project files.
Step 3 Open the project named taker.vbp in Visual Basic. This project is a COM+ component that uses the SPM to provide a unique customer ID as well as a method to write completed orders to a text file. Step 4 Locate the GetCustomerID function. In this function, add the following code to generate the Customer ID for our online store:
COM+ APPLICATION FUNDAMENTALS
Step 2 On your hard drive, create a new directory with the Windows Explorer named COM+\Exercise 4.1. Copy the contents from the CD-ROM directory into the new directory you just created.
4
106
Understanding COM+ Applications PART I Dim objManager As COMSVCSLib.SharedPropertyGroupManager Set objManager = New COMSVCSLib.SharedPropertyGroupManager Dim objGroup As COMSVCSLib.SharedPropertyGroup Set objGroup = objManager.CreatePropertyGroup _ (“Customers”, LockSetGet, Process, blnExists) Dim objProperty As COMSVCSLib.SharedProperty Set objProperty = objGroup.CreateProperty(“Number”, blnExists) ‘Set Property If Not blnExists Then objProperty.Value = 0 objProperty.Value = objProperty.Value + 1 ‘Return Value GetCustomerID = objProperty.Value
Step 5 After an order is taken, it will be written out to a text file for fulfillment. Add the following code to the WriteOut method to create the final text file: With App .StartLogging App.Path & “\orders.log”, vbLogToFile .LogEvent Now .LogEvent lngCustomer .LogEvent lngQuantity End With
Step 6 Compile the completed DLL. Add the component to a new COM+ application named Simple Orders. In the Component Services explorer, enable the Auto Done feature for both the GetCustomerID and WriteOut methods.
Creating the Web Front End Throughout the book, I use Visual InterDev to create Web sites for our COM+ applications. In most of the exercises, I assume that you know how to properly create a Web project in Visual InterDev. For those who might need help, I create this project in detail. Step 7 Start Visual InterDev 6.0 and select to create a new Web project. Choose to create the project in the directory COM+\Exercise 4-1. Give the new project the name SimpleOrders. When you select to create a new Web site, Visual InterDev starts the Web Project Wizard.
COM+ Application Fundamentals CHAPTER 4
107
Step 8 In the first step of the wizard, you must select the server on which the project is to be built. You can choose any server that you have rights on, but I generally assume that you are building on the local machine. In this case, you should simply specify the server name as localhost (see Figure 4.16).
FIGURE 4.16 Select the server on which the Web site will be built.
Step 9 In step 2 of the wizard, select to create a new Web application. Visual InterDev will suggest a default name (see Figure 4.17). Accept the name SimpleOrders.
4 COM+ APPLICATION FUNDAMENTALS
FIGURE 4.17 Give the new Web application a name.
108
Understanding COM+ Applications PART I
Step 10 The next two wizard steps ask if you want to apply a layout or a theme. Layouts supply navigational features to your site automatically. Themes provide graphics you can use with the site. In this project, don’t select either a layout or a theme. Just click the Finish button and Visual InterDev will create the site. Step 11 After the new Web project is created, add the files default.asp, cart.asp, order.asp, and toolbar.htm to the project. These Web pages work together to create and manage a simple shopping cart for the project. Step 12 Open the file default.asp in Visual InterDev. This page is a frameset that acts as a host for the other pages. Because the frameset is always loaded in the browser, this project uses the frameset page to remember the contents of the shopping cart. To remember the contents, we will use client-side JavaScript variables contained in the default.asp page. We will write out the initial values in ASP code. This interesting technique uses ASP to create JavaScript code. Add the following code to default.asp in the area identified within the template: Response.Write Response.Write Response.Write Response.Write
“” & vbCrLf “var customerID = “ & lngCustomerID & “;” & vbCrLf “var quantity = 0;” & vbCrLf “” & vbCrLf
Step 13 Quantities in the cart are increased or decreased from the toolbar.htm page. This page uses client-side JavaScript to access the variables defined in default.asp. After the quantities are adjusted, you can place your order using this page. Add the following JavaScript functions to the toolbar.htm page where indicated by the template: function increase(){ var myParent = document.frames.parent myParent.quantity++; myParent.frames(“Cart”).navigate(“cart.asp”); } function decrease(){ var myParent = document.frames.parent myParent.quantity—; if(myParent.quantity