Access 2002 Development Stephen Forte, Thomas Howe, Kurt Wall, Paul Kimmel, Russ Mullen
Unleashed
Access 2002 Development Unleashed Copyright ©2002 by Sams 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 authors assume no responsibility for errors or omissions. Nor is any liability assumed for damages resulting from the use of the information contained herein.
EXECUTIVE EDITOR Rosemarie Graham
ACQUISITIONS EDITOR Angela Kozlowski
DEVELOPMENT EDITOR Kevin Howard
MANAGING EDITOR Charlotte Clapp
PROJECT EDITOR
International Standard Book Number: 0-672-32120-3
Leah Kirkpatrick
Library of Congress Catalog Card Number: 00-139197
COPY EDITOR Mike Dietsch
Printed in the United States of America
INDEXER
First Printing: September 2001 04
03
02
01
4
Cheryl Landes 3
2
1
PROOFREADER
Trademarks
Plan-It Publishing
All terms mentioned in this book that are known to be trademarks or service marks have been appropriately capitalized. Sams 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.
TECHNICAL EDITORS
Warning and Disclaimer
TEAM COORDINATOR
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 authors 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.
Lynne Williams
Jason Merrill Pete Klein Keith Giddeon
MEDIA DEVELOPER Dan Scherf
INTERIOR DESIGNER Gary Adair
COVER DESIGNER Aren Howell
PAGE LAYOUT Ayanna Lacey
Contents at a Glance Introduction 1
PART I
Database Design Unleashed
1
What’s New for Developers in Access 2002 7
2
Planning the Development Process 15
3
Database Design and Normalization 45
4
Advanced Queries 59
5
The Microsoft Jet Database Engine 4.0 99
PART II
Data Access
6
Introduction to ActiveX Data Objects 119
7
Advanced ADO 147
PART III
User Interfaces Unleashed
8
Advanced Form Design 179
9
Enhancing Forms with ActiveX Controls 203
10
Part IV
Reporting Unleashed 241
VBA Unleashed
11
Creating Objects with Class Modules 287
12
Debugging Access Applications 317
13
Professional Error Handling 337
14
Application Optimization 369
Part V
Access Client Server
15
Introducing Access Data Projects and the Visual Tools 413
16
Developing Access Front-Ends to Microsoft SQL Server 435
17
Access 2002 Front-Ends to Oracle 461
Part VI
Interoperability
18
Using ActiveX Automation 505
19
Integrating with Microsoft Office 529
20
Using Visual Basic with Access 571
Part VII
Multiuser Issues
21
Multiple Users and Database Locking 617
22
Security 635
PART VIII
Web Publishing with Access 2002
23
Configuring a Web Site for Web Publishing 669
24
Web Enabling Access 2002 with Office Web Components 701
25
Using Data Access Pages 715
26
Web Publishing with Access 2002 and Active Server Pages 731 Index 773
Contents Introduction
PART I
1
Database Design Unleashed
5
1
What’s New for Developers in Access 2002 7 User Interface Changes............................................................................8 Changes to the VBE ................................................................................9 Compatibility with Access 2000 Databases ..........................................10 Database Conversion Error Logging ....................................................11 Offline Data Access Pages ....................................................................11 Improved Integration with SQL Server 2000 ........................................12 Extended Property Support ..............................................................12 Batch Updates ..................................................................................12 Password Security for Access Projects ............................................13 Other Access 2002 Features ..................................................................13 PivotChart and PivotTable Data Views ............................................13 XML Support....................................................................................13 Linked Table Wizard ........................................................................13 ANSI-92 Query Mode sans ADO ....................................................13 Summary ................................................................................................14
2
Planning the Development Process 15 Gathering Requirements ........................................................................17 Why Are Requirements So Important? ............................................17 Finding the Real Problem ................................................................18 Investigation......................................................................................19 Process Diagrams ............................................................................20 Identify the Scope of the Project......................................................21 Writing Down Requirements............................................................21 Architecture............................................................................................24 Development Planning ..........................................................................24 Delivery Strategy ..............................................................................25 Standards ..........................................................................................26 Construction ..........................................................................................28 Divide and Conquer: Construction Logistics ..................................29 Builds and Releases..........................................................................30 Creating a Detailed Design ..............................................................34 Reviewing the Design ......................................................................35 Implementation ................................................................................36 Code Review ....................................................................................36
vi
Access 2002 Development UNLEASHED Testing ..............................................................................................36 Defect Tracking ................................................................................38 Version Control ................................................................................42 Summary ................................................................................................43 3
Database Design and Normalization 45 The Relational Design Theory ..............................................................48 The Benefits of Using the Relational Model ..................................48 Tables and Uniqueness ....................................................................49 Foreign Keys and Domains ..............................................................50 Relationships ....................................................................................51 Data Normalization ..........................................................................54 Data Integrity Rules..........................................................................57 Summary ................................................................................................58
4
Advanced Queries 59 Using the Query Object ........................................................................60 Creating Queries in Access....................................................................62 Using the Query Design Window ....................................................62 Using the Table Pane ........................................................................66 Using the Query Grid ......................................................................72 Creating Advanced Queries ..................................................................74 Mastering Totals Queries ......................................................................75 Counting Records With Count ..........................................................76 Calculating Averages with Avg ........................................................77 Using Min and Max ............................................................................78 Using First and Last ......................................................................78 Validating Data With StDev and Var ................................................78 Creating Custom Aggregation Queries with Expression ................79 Understanding the Where Clause ......................................................80 Mastering Crosstab Queries ..................................................................83 Mastering Parameter Queries ................................................................87 Creating Parameter Queries in the Query Design Window ............87 Using Parameterized Queries in Code ............................................89 Executing a Query Using a Parameter Collection ..........................90 Mastering Pass-Through Queries ..........................................................91 Mastering Data Definition Queries........................................................93 Creating a New Table ......................................................................94 Defining Field Properties ................................................................95 Altering a Table ................................................................................96 Creating an Index ............................................................................96 Removing a Table ............................................................................97 Summary ................................................................................................97
CONTENTS 5
PART II 6
The Microsoft Jet Database Engine 99 The History of Microsoft Jet ..............................................................100 Jet 1.0..............................................................................................100 Jet 1.1..............................................................................................100 Jet 2.0..............................................................................................101 Jet 2.5..............................................................................................101 Jet 3.0..............................................................................................101 Jet 3.5..............................................................................................101 Jet 3.51............................................................................................101 Jet 4.0..............................................................................................102 Future Versions of Microsoft Jet ....................................................102 Using Jet 4.0 Features in Your Applications........................................103 Native OLE DB Provider ..............................................................103 Row Level Locking ........................................................................103 Full Unicode Support ....................................................................103 Jet Data Types ................................................................................107 Enhanced AutoNumber Capabilities ..............................................109 Searchable Memo Fields ................................................................110 Connection Control/Passive Shutdown ..........................................110 New SQL Grammar........................................................................110 Summary ..............................................................................................116
Data Access
117
Introduction to ActiveX Data Objects 119 History of Data Access ........................................................................120 Proprietary APIs ............................................................................120 Open Database Connectivity (ODBC) ..........................................120 Microsoft Jet/Data Access Objects (DAO) ....................................120 Remote Data Objects (RDO) and ODBCDirect ............................120 Microsoft’s Universal Data Access Initiative ......................................121 ActiveX Data Objects (ADO)..............................................................122 ADO 1.0 ........................................................................................122 ADO 1.5 ........................................................................................122 ADO 2.0 ........................................................................................122 ADO 2.1 ........................................................................................123 ADO 2.5 ........................................................................................124 ADO 2.6: Where We’re at Today ..................................................124 The ADO Object Model ......................................................................125 Connection Object..........................................................................126 Executing a SQL Statement off a Connection Object ..................129 ADO Recordset Object..................................................................130
vii
viii
Access 2002 Development UNLEASHED Using a Recordset with Command and Parameter Objects ............134 Using a Record Object ..................................................................137 Executing an Action Query via a Command..................................138 Field and Property Objects ..........................................................139 Using the Stream Object ................................................................140 Managing Errors with the Error Object ........................................141 Moving from DAO to ADO ................................................................142 Converting from Prior Versions of Access ....................................142 Should I Convert to ADO? ............................................................143 The ADO Object Model Compared to DAO ......................................145 Summary ..............................................................................................146 7
PART III 8
Advanced ADO 147 Using the OLE DB Provider for Jet in Access 2002 ..........................148 CurrentProject.Connection ........................................................151 Using Microsoft Data Links to Connect to a Database ................152 Accessing Non-Relational Data with ADO ........................................157 The Jet User Roster ........................................................................157 Creatable Recordsets ......................................................................158 Data Shaping ..................................................................................159 Advanced Data Manipulation with ADO ............................................162 Modifying Data in a Recordset ......................................................162 Persisted Recordsets ......................................................................165 Data Definition with ADOX ................................................................167 The Catalog Object ........................................................................167 Creating a Database........................................................................168 Creating Tables and Fields ............................................................169 Creating Relationships in ADOX ..................................................172 Creating Queries in ADOX ............................................................173 Summary ..............................................................................................176
User Interfaces Unleashed
177
Advanced Form Design 179 Form Properties....................................................................................180 Data Properties ..............................................................................181 Format Properties ..........................................................................182 Other Properties..............................................................................184 Useful Properties Not Found in the Properties Window................186 Events ............................................................................................187 Access Form Controls..........................................................................189 The Combo Box Control ..................................................................189 List Boxes ......................................................................................192 The Multi-Select List Box Control ................................................193
CONTENTS Subforms ........................................................................................194 Built-In Tab Control ......................................................................195 Option Group..................................................................................195 Pop-up Menus ................................................................................196 Hyperlinks ......................................................................................196 Creating PivotTable and PivotChart Views..........................................197 Creating a PivotTable View ............................................................197 Converting Between PivotCharts and PivotTables ........................201 Summary ..............................................................................................202 9
Enhancing Forms with ActiveX Controls 203 How to Use ActiveX Controls ............................................................204 Types of ActiveX Controls ............................................................204 Where Can You Get ActiveX Controls? ........................................205 Are ActiveX Controls Safe? ..........................................................205 Can I Use and Distribute ActiveX Controls in My Application? ................................................................................206 Using ActiveX Controls ......................................................................206 Installing an ActiveX Control ........................................................206 Registering an ActiveX Control ....................................................207 Adding an ActiveX Control to a Form ..........................................207 Setting the ActiveX Control Properties ..........................................208 Writing Code to Execute Methods or Respond to Events ............209 21 ActiveX Controls ............................................................................210 Animation Control ..........................................................................212 Calendar Control............................................................................213 Common Dialog Control ..................................................................214 DateTimePicker Control ................................................................215 FlatScrollBar Control ..................................................................217 ImageCombo Control ........................................................................218 ImageList Control ..........................................................................219 ListView Control............................................................................221 MAPISession Control ......................................................................222 MAPIMessages Control ....................................................................223 MonthView Control ..........................................................................224 ProgressBar Control ......................................................................226 RichText Control............................................................................227 Slider Control................................................................................228 StatusBar Control ..........................................................................229 SysInfo Control..............................................................................231 TabStrip Control............................................................................232 Toolbar Control..............................................................................233 TreeView Control............................................................................234
ix
x
Access 2002 Development UNLEASHED Control................................................................................235 Control ........................................................................236 Distributing ActiveX Controls ............................................................238 Summary ..............................................................................................239 UpDown
WebBrowser
10
Reporting Unleashed 241 Approaching Reports ..........................................................................242 Understanding the Architecture of Access Reports ............................242 Building a Single Table Report Using the Report Wizard ..................244 Customizing Reports............................................................................247 Changing the Recordsource in a Report ........................................247 Changing the Grouping Structure in a Report ..............................248 Implementing Grouping in a Report ..............................................250 Using Functions in a Report ..........................................................250 Working with Subreports ....................................................................256 Creating a Simple Subreport ..........................................................257 Creating Simple Mailing Labels..........................................................259 Publishing a Report..............................................................................262 Exploring the Methods for Publishing Reports..............................263 Modifying a Report at Runtime ..........................................................266 Filtering and Sorting ......................................................................266 GroupKeepTogether ........................................................................267 HasData ..........................................................................................267 Report Events (Runtime)................................................................268 Section Properties..........................................................................269 Section Properties (Design Time) ..................................................270 Section Properties (Runtime) ..........................................................272 Building Reports Programmatically ....................................................274 Creating the RecordSource ............................................................275 Creating the Report Object ............................................................276 Creating Sections............................................................................278 Tips and Tricks ....................................................................................279 Make a Biweekly Grouping ..........................................................279 Hide Repeating Data ......................................................................279 Group Data Alphabetically ............................................................279 Make Numbered Lists ....................................................................280 Create Empty Lines Every n Spaces ..............................................280 Reset Page Number for New Groups ............................................281 Draw Vertical Lines ........................................................................281 Move Page Numbers for Even-Odd Pages ....................................282 Identify the User Printing the Report ............................................282 Align Pages for Binding ................................................................282
CONTENTS Calculate Page Totals......................................................................283 Fine Control Manipulation ............................................................284 Summary ..............................................................................................284
PART IV 11
VBA Unleashed
285
Creating Objects with Class Modules 287 Exploring the Benefits of Using Objects ............................................289 Hide Complex Functionality ..........................................................289 Use of Microsoft’s IntelliSense Technology ..................................289 Organize Code ................................................................................290 Allow Viewing Objects in the Object Browser ..............................290 Create Multiple Instances of the Object ........................................290 Make Code Easy to Update and Maintain ....................................291 Limit Access to Code ....................................................................291 Make Code Easily Portable ............................................................291 Reviewing Objects, Properties, and Methods......................................291 Creating Classes ..................................................................................292 Inserting a Class Module................................................................292 Creating Properties ..............................................................................292 Using Public Fields ........................................................................293 Using Property Procedures to Modify Fields ................................293 Public Variable or Property Procedures..........................................297 Creating Enumerated Data Types ..................................................297 Creating Methods ................................................................................299 Using Methods................................................................................300 Creating Events....................................................................................300 Using Events ..................................................................................300 Firing the Initialize and Terminate Events ....................................302 Using Objects ......................................................................................302 Creating an Object Variable............................................................302 Assigning an Object Variable to an Object ....................................303 Using the Object ............................................................................303 Releasing the Object ......................................................................303 Creating Multiple Instances of an Object............................................304 Examining More Object Examples......................................................304 Text File Object ..............................................................................304 MyTimer Class ................................................................................306 Sound Object ..................................................................................307 Letter Object ..................................................................................308 Outlook Object ..............................................................................310 Implementing an Error Handler Object ..............................................311 Using Objects with VBA Collections..................................................312
xi
xii
Access 2002 Development UNLEASHED Creating VBA Collections..............................................................313 VBA Collection’s Properties and Methods ....................................313 Summary ..............................................................................................316 12
Debugging Access Applications 317 Eliminating Logic Errors ....................................................................318 Working with the Visual Basic Development Environment (IDE)......318 The Project Explorer ......................................................................319 The Code Window ..........................................................................320 The Properties Window ..................................................................320 The Immediate Window ................................................................321 The Locals Window........................................................................321 The Watch Window ........................................................................321 The Object Browser........................................................................321 The Call Stack Window..................................................................322 Working with the Debug Object ..........................................................322 Debug.Print ....................................................................................323 Debug.Assert ..................................................................................324 Using the Immediate Window ............................................................324 Evaluating Variables ......................................................................324 Changing the Value of Variables ....................................................324 Evaluating Built-in Functions ........................................................324 Running Custom Subprocedures ....................................................324 Tips for Using the Immediate Window ..........................................325 Using the Debugger ............................................................................326 Setting Breakpoints ........................................................................326 Stepping Through Code..................................................................327 Using Microsoft IntelliSense While Debugging ............................329 Using the Locals Window ..............................................................329 Using the Watch Window ..............................................................329 Viewing the Call Stack ..................................................................330 Using Conditional Compilation ..........................................................331 Writing Solid Code ........................................................................332 Application Testing..............................................................................335 Practice Debugging Techniques ..........................................................335 Summary ..............................................................................................336
13
Professional Error Handling 337 Eliminating Syntax Errors ..................................................................338 Eliminating Logic Errors ....................................................................341 Eliminating Runtime Errors ................................................................341 A Simple Error Handler ................................................................341 The Err Object ..............................................................................344
CONTENTS Responding to Errors......................................................................346 The Resume Statements ..................................................................348 Getting Additional Error Information ............................................348 A Comprehensive Error Handler....................................................351 Errors in Various Applications ............................................................364 Error Handling With Nested Procedures ............................................365 Advanced Error Topics ........................................................................365 Error Event Procedures ..................................................................366 On Error GoTo 0............................................................................366 On Error Resume Next ..................................................................366 AccessError Method ......................................................................367 Useful Error Functions ..................................................................367 Settings Error Trapping Options ....................................................367 Summary ..............................................................................................368 14
Application Optimization 369 Strengthening the Foundation: Hardware and Windows Optimization......................................................................................371 Installing the Application for Optimal Performance ..........................373 Optimizing the Configuration of the Jet Database Engine..................374 Safely Changing the Jet Settings....................................................375 Tools to Measure Performance ............................................................381 Looking Behind the Scenes ................................................................383 Optimizing the Database from the Start ..............................................384 Designing Data Tables for Performance ........................................385 Normalizing Data to Enhance Performance ..................................385 Creating Indexes to Speed Queries ................................................386 Establish Relationships Early to Improve Performance ................386 Boosting Query Performance ..............................................................387 Evaluating the Type of Resultset for Optimum Performance ........390 Getting Forms to Run Faster ..............................................................395 In the Beginning… ........................................................................395 Getting Faster Images ....................................................................395 The Basic, Fast Form......................................................................396 Get the Reports Printed Faster ......................................................399 Writing Fast Code................................................................................400 How Code Uses Memory ..............................................................401 Maintaining Your Modules ............................................................401 Compiling and Decompiling Code ................................................401 Coding Tips and Hints ........................................................................402 Use Option Explicit ......................................................................402 Choose Variable Sizes with Care....................................................402 Save Stack Space with String Variables ........................................402
xiii
xiv
Access 2002 Development UNLEASHED Specific Object Type Declarations ................................................403 Toggle True and False ....................................................................403 Len() Instead of Empty String ......................................................404 True and False Evaluations Instead of Zero ..................................404 Fast Object References ..................................................................404 Fast Array Uses ..............................................................................405 Use Constants When Possible ........................................................406 The Proper Use of Bookmarks ......................................................406 Close and Destroy ..........................................................................407 Use SQL Instead of DAO ..............................................................407 Use the Index Number of Collections............................................407 Making Faster Loops......................................................................408 Ban IIF() from Code ....................................................................409 Arranging the Select Case ............................................................409 Use .Execute, Not RunSQL ............................................................409 Use QueryTimer() ..........................................................................409 Test the Efficiency of Transactions ................................................409 Control Refreshes ..........................................................................409 Reference ActiveX and Use Early Binding....................................410 Upsize to Client/Server ..................................................................410 Bread and Circuses ........................................................................410 Summary ..............................................................................................410
PART V 15
Access Client Server
411
Introducing Access Data Projects and the Visual Tools 413 Introducing Access Data Projects ........................................................414 The Pros and Cons of ADPs ..........................................................414 Using ADPs..........................................................................................415 Creating an ADP ............................................................................415 The New Database Container ........................................................417 Working with ADPs and Existing SQL Server Databases ..................419 Working with SQL Server Tables ..................................................419 SQL Server Queries........................................................................421 Stored Procedures ..........................................................................422 Database Diagrams ........................................................................423 Forms, Pages, Reports, Macros, and Modules ..............................424 Administering Your SQL Server via an Access ............................424 Reconnecting to the SQL Server Database ....................................425 Creating a Project Based on a New Database ....................................428 Creating Tables ..............................................................................428 Creating Relationships via a Diagram............................................430 Creating Views................................................................................431
CONTENTS Creating Stored Procedures ............................................................432 Creating the Access Application ....................................................433 Creating—ADE Files ....................................................................433 Summary ..............................................................................................434 16
Developing Access Front-Ends to Microsoft SQL Server 435 Client/Server Architecture: OLE DB Versus ODBC ..........................436 Setting Up Your SQL Server Front-End Connection ..........................436 Setting Up an ODBC Data Source (DSN) ....................................437 Linking Tables ................................................................................438 Stored Procedures and SQL Pass-Through Queries............................440 Basing Access Reports on Stored Procedures via PassThrough Queries ..........................................................................442 Reporting Against SQL Server in Access 2002 ..................................443 Advanced Features: Providing Parameters for the Stored Procedure at Runtime ..................................................................444 Additional Filtering of a Report at Runtime ..................................445 Using Forms in Your Application ........................................................448 Bound Forms ..................................................................................448 Unbound Forms ..............................................................................448 Advanced Features of the SQL Server OLE DB Provider..................450 Next Recordset ..............................................................................451 Executing Commands with Parameters ..............................................452 The Long Way ................................................................................453 Using Create Parameters ..............................................................454 Using Refresh ................................................................................456 Handling Return Values..................................................................457 Not Using a Command Object ..........................................................459 Using a Connection Class ..................................................................459 Using the Connection Class in Your Applications ........................460 Summary ..............................................................................................460
17
Access 2002 Front-Ends to Oracle 461 Accessing Oracle Data with Access ....................................................462 Table Linking..................................................................................462 SQL Pass-Through Queries (ODBC) ............................................465 Using Wildcards/Position Markers ................................................468 Functions in Oracle Versus Access ......................................................470 Strings ............................................................................................470 Mathematical Calculations in Oracle ............................................477 Date Calculations in Oracle............................................................479 Understanding Views and Stored Procedures......................................482 Creating a View ..............................................................................483 Connections to Oracle Through ADO............................................484
xv
xvi
Access 2002 Development UNLEASHED Creating Stored Procedures ............................................................487 Calling a Stored Procedure ............................................................489 Creating an Unbound Interface to Oracle............................................491 Building an Unbound Interface ......................................................491 Summary ..............................................................................................502
PART VI 18
Interoperability
503
Using ActiveX Automation 505 What Is ActiveX Automation? ............................................................506 Why Use Automation? ........................................................................506 Distinguishing Automation Server Versus Automation Client ............506 Determining Automation Resource Requirements ..............................507 Understanding the Big Picture ............................................................507 Creating and Setting a Reference to Another Application ..................507 Setting a Reference to Another Application ..................................507 Reviewing Objects, Properties, and Methods ................................508 Understanding Object Models........................................................509 Using the Object Browser ..............................................................509 Creating an Object Variable............................................................511 Referencing an Application That Is Already Running ..................512 Assigning an Object Variable to an Application..................................512 Creating an Instance of the Application ..............................................513 Using GetObject and the New Keyword Together ..........................513 Using Early Versus Late Binding ..................................................514 Using the CreateObject Function..................................................515 Using the Automation Object’s Properties and Methods ....................517 Setting an Object’s Properties ........................................................517 Setting an Object’s Methods ..........................................................517 Releasing the Automation Object ........................................................517 Putting It All Together ........................................................................518 Closing the Automation Server Application........................................519 Using the UserControl Property to Determine How an Application Was Opened ..................................................................520 Using WithEvents to Expose Events of the Automation Server ........520 Making WithEvents Work ..............................................................522 Using the Automation Tips and Techniques ........................................523 Set References, Use Early Binding, and the New Keyword............524 Use an Existing Application If It Is Already Open ........................524 Turn ScreenUpdating Off ..............................................................524 Give the Users Feedback ................................................................525 Have the Automation Server Run the Code ..................................525 Use the With/End With Construct..................................................526
CONTENTS Release Object Variables ................................................................526 Do Not Display Dialog Boxes and Message Boxes ......................527 Use Error Handling ........................................................................527 Summary ..............................................................................................527 19
Integrating with Microsoft Office 529 Why Integrate with Microsoft Office? ................................................531 Using Word ....................................................................................531 Using Excel ....................................................................................532 Using PowerPoint ..........................................................................532 Using Outlook ................................................................................532 Using Graph....................................................................................532 Use the Right Tool ..............................................................................533 Using the Macro Recorder to Write Code ..........................................533 Using Auto Macros ..............................................................................535 Microsoft Forms ..................................................................................536 Object Browser ....................................................................................537 Class Arguments for Office Applications ............................................537 Automation Example ..........................................................................538 Automating Word ................................................................................540 The Word Object Model ................................................................540 Using Word Templates ..................................................................542 Inserting Data in Word Documents ................................................543 Word Automation Code Examples ................................................546 Word Fields ....................................................................................552 Document Summary Information ..................................................553 Other Word Features ......................................................................555 Automating Excel ................................................................................555 Excel Object Model........................................................................555 Excel Automation Code Examples ................................................556 Automating PowerPoint ......................................................................559 The PowerPoint Object Model ......................................................559 PowerPoint Automation Code Examples ......................................560 Automating Outlook ............................................................................562 The Outlook Object Model ............................................................562 Adding and Displaying Outlook Folders ......................................564 Adding a New Task and Displaying Task Items ............................564 Creating an Email Message with an Attachment ..........................564 Creating Outlook Items ..................................................................565 Displaying Default Outlook Folders ..............................................566 Display an Outlook Public Folder..................................................566 Finding an Outlook Item ................................................................567 Filtering Outlook Items ..................................................................567
xvii
xviii
Access 2002 Development UNLEASHED Automating Graph ..............................................................................567 Graph Object Model ......................................................................567 Creating Graphs..............................................................................568 Summary ..............................................................................................569 20
PART VII 21
Using Visual Basic with Access 571 Creating ActiveX Code Components ..................................................572 What Is an ActiveX Code Component? ........................................573 What Is the Difference Between an ActiveX EXE and an ActiveX DLL? ........................................................................574 Creating an ActiveX Code Component ..........................................574 Compiling the DLL ........................................................................578 Using the cSound ActiveX Component ..........................................579 Distributing ActiveX Components ................................................581 The Error Handling Component ....................................................591 Global Error Handling Data ..........................................................592 The cError Component..................................................................593 Creating ActiveX Controls ..................................................................593 Types of ActiveX Controls ............................................................593 ActiveX Control Attributes ............................................................593 Creating a Design-Time ActiveX Control......................................594 Creating a Runtime ActiveX Control ............................................607 Summary ..............................................................................................614
Multiuser Issues
615
Multiple Users and Database Locking 617 Understanding Multiuser Issues ..........................................................618 Reviewing Jet’s Multiuser Design ......................................................619 Understanding Jet’s Multiuser Locking ..............................................619 The Database Mode........................................................................620 The Locking Scheme......................................................................621 Lock Granularity ............................................................................622 Selecting the Proper Architecture ........................................................623 Working With Locks ............................................................................623 Testing the Existence and Type of a Lock ....................................623 Responding to Locking Errors ......................................................627 Using Transactions ........................................................................629 Optimizing Multiuser Applications ....................................................631 Indexing Tables ..............................................................................631 Partitioning the Application............................................................631 Oracle/SQL Server Locking ................................................................632 Summary ..............................................................................................633
CONTENTS 22
PART VIII 23
Security 635 Elements of Security............................................................................636 Database Password Security ..........................................................636 Workgroup-Based Security ............................................................637 Workgroup Creation ............................................................................638 Users and Groups ................................................................................641 Understanding Default User and Group Settings ..........................642 Creating Users ................................................................................643 Setting/Changing User Passwords..................................................643 Creating Groups..............................................................................644 Assigning Users to Groups ............................................................645 Distinguishing Between Default and Special Users and Groups..........................................................................................646 Understanding Permissions ............................................................646 Implementing Security Using Startup Options....................................649 Security Concerns with Replication ....................................................650 Security for Split Databases ................................................................651 With OwnerAccess Option ..............................................................653 Security for Client/Server ....................................................................653 Managing Users..............................................................................654 Enumerating Groups and Users and List Membership ..................655 Identifying Current Users with ADOX ..........................................657 Identifying Users With Blank Passwords ......................................658 Setting/Clearing Passwords ............................................................660 Managing Group Object Ownership ..............................................660 Managing Multiple Apps................................................................661 Implications When Using SQL ......................................................662 Securing a Database Step by Step ......................................................663 Common Security Errors ....................................................................664 Summary ..............................................................................................665
Web Publishing with Access 2002
667
Configuring a Web Site for Web Publishing 669 Development Versus Production Environment ....................................670 Choosing Your Platform ......................................................................671 Personal Web Server and Peer Web Services ................................672 Internet Information Server ............................................................672 What Is the Option Pack? ....................................................................673 Setting Up Your Web Server ................................................................675 Installation ......................................................................................675 NT Option Pack for Windows 95/98..............................................675 Microsoft Transaction Server 2.0 ..................................................680
xix
xx
Access 2002 Development UNLEASHED Managing and Configuring Your Web Server......................................682 Personal Web Manager ..................................................................682 Microsoft Management Console ....................................................684 Securing Your Web Applications ........................................................692 What Is the Difference Between a Site and a Virtual Directory?........693 What Is IUSER? ............................................................................695 File System Type ............................................................................696 Directory Structures and Required Permissions ............................696 ASP/HTML—Placement and Permissions ....................................697 Databases—Placement and Permissions ........................................697 Summary ..............................................................................................699 24
Web Enabling Access 2002 with Office Web Components 701 What Are the Office XP Web Components? ......................................702 What Do the Office Web Components Do? ..................................702 What Are the License Requirements for Using Web Components?................................................................................703 Using the Office Spreadsheet Control................................................703 Getting Started................................................................................703 Using the Control in Access ..........................................................705 Using the Office Chart Control ..........................................................707 Getting Started................................................................................708 Using the Control in Access ..........................................................708 Using the Office PivotTable Control..................................................711 Getting Started................................................................................711 Summary ..............................................................................................713
25
Using Data Access Pages 715 What Is a Data Access Page? ........................................................716 Data Access Pages Architecture and Requirements ......................716 Creating Your First Data Access Page ................................................717 Viewing a Data Access Page ..........................................................721 Implementing Interactive Drill-Downs................................................722 Incorporating the Office Web Components with DAPs ......................724 Adding an Excel Spreadsheet Web Component ............................725 Adding a Chart Web Component ..................................................726 Scripting Data Access Pages................................................................726 Changing the DAP’s DataSource at Runtime ................................728 Summary ..............................................................................................729
26
Web Publishing with Access 2002 and Active Server Pages 731 Using Active Server Pages ..................................................................732 Understanding Active Server Pages ....................................................733
CONTENTS Active Server Pages Versus CGI ....................................................734 Obtaining Active Server Pages ......................................................734 Getting Started with Active Server Pages............................................734 Understanding the ASP Code ........................................................738 Understanding the Limitations of Exporting ASP Pages ..............739 Active Server Pages 101 ......................................................................739 The Active Server Page Engine......................................................739 Server-Side Scripting......................................................................740 The Application and Session Objects ............................................747 Using the Response and Request Objects ......................................749 The Global.asa File ........................................................................750 Examples of Active Server Page Objects ......................................752 Using ADO in Your Active Server Page Applications ..................753 Real-Life Example: Establishing a Self-Maintaining Membership-Based Web Page ..........................................................754 Access 2002 Web Publishing with XML ............................................763 Understanding the Basics of XML ................................................764 Creating XML Programmatically ..................................................766 Creating Charts with the Chart Control ..............................................770 Summary ..............................................................................................772 Index
773
xxi
About the Authors Stephen Forte runs the New York City consulting firm, The Aurora Development Group (www.auroradev.com), which specializes in Microsoft Database and Web technology. He has authored and co-authored several books, including Microsoft Jet Database Programmer’s Guide (Microsoft Press), Access 97 Unleashed, Second Edition, and Microsoft Access 2000 Development Unleashed (Sams Publishing). He has written several magazine articles and is a contributing editor of Access/VB Advisor. Stephen also serves as president of the NYC Access and VB Developers group (www.nycaccessvb. com) and travels around the world speaking at Microsoft Developer Conferences. Tom Howe graduated from Northwestern School of Law in 1982 and has been a practicing attorney ever since. Having tired of the practice of law, he decided to join the most dynamic profession in the world—software development. So now he spend most of his time developing software and speaking at developer conferences. Tom specializes in application development using Microsoft Access, Visual Basic, Outlook, Exchange, and SQL Server. Tom is a regular speaker at TechEd, Advisor, Informannt and other developer conferences around the world. Kurt Wall has been using and programming with Access and Visual Basic since 1994. In no particular order, he enjoys coffee, cooking, coding, staying up late, and sleeping even later, the latter of which makes any day job a challenge. When he gets tired of computers, he reads the occasional novel, historical fiction, political theory, American history, and cookbooks, and dreams of going to culinary school. Computers and cooking have nothing to do with his cum laude degree in American history from the University of Utah. A working stiff for nine years, Kurt is now a freelance writer, editor, and consultant. While in the Land of Cubicles, Kurt has been Caldera Systems’ technical publications manager, an enterprise application technician (pager slave) for Qwest, an Informix and Visual Basic programmer with Virtual Solutions, an EDI administrator (pager slave) for First Health Solutions, a lowly help desk grunt for First Health Solutions, and a network administrator for the Utah Division of State History. Kurt is the author of Linux Programming Unleashed (first and second editions), and Linux Programming by Example. He is currently coauthoring Red Hat Linux Network and System Administration and Red Hat Linux Weekend Crash Course. Kurt has also contributed chapters to The Informix Handbook, The Linux Bible, forthcoming titles on Linux clustering, Linux Performance Tuning and Capacity Planning, UNIX Unleashed, and too many Caldera OpenLinux user guides, manuals, and white papers to count.
Kurt is also the technical editor for all or part of Practical Linux, Red Hat Administrator’s Handbook, Linux Security Toolkit, Sams Teach Yourself KDE 1.1 in 24 Hours, Sams Teach Yourself Linux in 24 Hours, 2nd Ed., Linux: The Complete Reference, 4th Ed., Linux Database Bible, KDE 2.0 Development, Caldera OpenLinux Secrets, Linux Administrator’s Bible, Caldera OpenLinux Bible, an upcoming book on Linux performance tuning and capacity planning, and other titles. Kurt is the vice president of the Salt Lake Linux Users Group, former president of the Informix on Linux SIG of the International Informix Users Group, and former maintainer of the Informix on Linux FAQ. Having survived Marine Corps boot camp, Kurt has an extreme dislike for talking about himself in the third person. Paul Kimmel is the author of many books on Access programming and Visual Basic programming. Paul is a freelance contributing author to the CodeGuru Newsletter at www.codeguru.com and is available for development work at pkimmel@softconcepts. com. Russ Mullen has been using and programming with Access and Visual Basic for more years than he cares to remember. He has technically edited a number of books both on Access and Visual Basic. He enjoys getting up very early in the morning and coding with coffee in hand long before the sun rises; then, retiring early to prepare for the next day’s work. In recent years he has been doing Web site design including databases. He is always available for Web site or database development work at
[email protected].
Dedication In memoriam, Michael Parrish Pruyn. —Kurt Wall My contributions to this work are dedicated to David Benavides, Sr—a good, decent, and honorable man. Thank you for being responsible. —Paul Kimmel In memory of my father, Enos Ross Mullen. —Russ Mullen
Acknowledgments Above all, I thank God for giving me the desire to write and blessing with me the opportunities to do so. Once again, I’d like to thank my editor, Angela Kozlowski. Some people sparkle; count yourself lucky to meet someone who does. At the end of the day, you only have your people, so thanks to Ashleigh, Zane, Dad, Rick, Amy, Morgan, Isaac, Marty, the whole El Paso gang, and the Dallas Santa. —Kurt Wall Special thanks to Angela Kozlowski, Sondra Scott, and Leah Kirkpatrick at Sams. These wonderful and talented people could teach software developers a thing or two about project management. Thank you for all of the wonderful opportunities to write and work with you. It is truly my pleasure. A thank you to co-conspirators on other fronts, including Michael Standen in Ottawa and Frank Arndt in Michigan for putting up with my often-times distracted behavior. Thanks for making it possible for me to multi-task. As always I would like to thank my family. They are my first line of defense and best supporters. I would like to thank each of them by name. Thank you to Lori Kimmel; Alex Kimmel; Noah Kimmel; Douglas MacDonald and Trevor MacDonald; Jacqueline, David, Nicholas, and Robert Benavides; David, Cindi, Ben, Patti, and Becky Kimmel; Dan and Angie Kimmel; Richard, Kathy, Rich, Tim, and Johnny Hemenway; James and Sarah Kimmel; Jennifer and Brent Ladd; Gerald and Deb Kimmel; Dick and Diane Bourbonais; Pauline Blumenthal; Rick, Lori, Daniel, Jennifer, Gillie, and Annie
Bourbonais; Frank and Clinton Bourbonais; Tom, Shelley, Kendra (and Josh), Kynice, and Tommy Bogan. Thank you, and God bless and keep you all. —Paul Kimmel Special thanks to Angela Kozlowski, Sondra Scott, and Leah Kirkpatrick at Sams for all their help and understanding. Without their help the chapters I authored would have been impossible to complete. I would also like to thank the technical editor for all the help and insight given during the review stage of each chapter. —Russ Mullen
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 Executive Editor for Sams, I welcome your comments. You can 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.
E-mail:
[email protected]
Mail:
Sams Publishing 800 East 96st Street Indianapolis, IN 46240 USA
Introduction Why Read This Access Development Book? Earlier this evening, I sat in the Salt Lake Roasting Company, a gourmet coffee roaster in Salt Lake City, and, over several cups of hot, fresh, delightfully aromatic Costa Rican coffee, scribbled the notes for this introduction. It occurred to me that selecting an Access development book is much like choosing your next pound of coffee beans: Without some sort of guide, one Access book looks pretty much like the next save for differences in their tables of contents and covers, just as two pounds of coffee from different regions of the world appear seem indistinguishable but for slight variations in their aroma and appearance. This book is different from the typical Access books sitting right next to it on the bookshelf. Some of the reasons are • This book is written by Access developers for Access developers. So many computer books these days are written by professional trainers and writers. The authors who wrote this book have the same job as you—to make Access solutions for their users. We share our real-world experience and knowledge throughout this book. We focus on the features of Access development that you will need to use, rather than droning endlessly on about every button and tab of every dialog box. Whether you write Access applications professionally, are making a transition from Visual Basic or another development environment for database access, are evaluating Microsoft Access as a front-end to SQL Server, Oracle, Informix, or Sybase, or are simply an experienced, technically savvy Access end user, this book is for you. • This book is the only Access book to have extensive coverage of working with Oracle. The first time I had to make an Access front-end to Oracle, I was totally disappointed to find that there was absolutely no literature on the topic. James Ralston’s experience with Oracle and Access is distilled into a complete chapter on using Access with Oracle. Moreover, you will find two chapters devoted entirely to using Microsoft Access with SQL Server and many parts of other chapters that address using Access with SQL Server.
2
Access 2002 Development UNLEASHED
• We have the best coverage of using Access on the Internet. The Internet’s popularity and growth not only caught every major segment of the IT industry, including Microsoft, by surprise, it totally changed the face of software development. While most Access books still treat the Internet as an afterthought, this book, like Microsoft Access itself, puts the Internet on par with other development environments. Indeed, if the Internet is the next development platform, Access is the database for creating and running data-driven applications. This book brings six years of real-world experience of using Access and the Internet to you, if only to help you avoid the same blunders and mistakes the authors made! The book you hold in your hands also benefits from the expertise of a Windows 2000/Windows NT expert, showing you how to build a Web server from scratch and how to develop on Windows 95 with Personal Web Server. The material in this book covers the range of Access-based Internet development, from XML, ASP, DAPs, and Microsoft Office Web Components to all the latest development trends. • We do not ignore the design, planning, and “human” side of Access development. Most studies show that the coding, table design, maintenance, and so on is only about 55 percent of a software project. So most computer books ignore the other side of development—the design side. Tom Howe is not only an Access developer, he is a professional lawyer with his own practice. With this legal and academic background, Tom is in a unique position to talk about the “human” side of software development, the importance of design, writing specifications, and project plans. • This book has been completely rewritten from the ground up—a completely fresh approach to the latest version of the product by experienced developers. Tom, James, and I have been working closely with Microsoft and the Access Development team all through the beta development cycle. Few other books can make both those claims. We also tested all the code examples on the full Release version of Office XP that you have, not like some other books that are rushed to the market.
What You Can Learn from This Book Part I of this book, “Database Design Unleashed,” shows you important concepts from a perspective of experience. These chapters will help you evaluate and modify your current design and planning skills to include business object modeling and the latest Jet engine capabilities.
INTRODUCTION
In Part II, “Data Access,” you will find out everything that you really need to know about using the new data access method: ActiveX Data Objects (ADO). We show you how to make the transition from DAO to ADO and ADOX and show you the parts of ADO and ADOX that you will need to use and work with on a daily basis. Anyone doing Access development knows that using Access effectively requires the use of forms and reports. Part III, “User Interfaces Unleashed,” shows you ways to program your application’s interface with powerful technologies, such as ActiveX controls and components. In Part IV, “VBA Unleashed,” you will see the importance of the powerful programming environment behind Access: Visual Basic for Applications (VBA). You will learn invaluable techniques and have ready-to-run sample code right on the CD-ROM to plug into your applications. Part V, “Access Client Server,” teaches you how to use Access in a client/server environment. Access Data Projects, introduced in Access 2000, are devoted client/server development. In Part VI, “Interoperability,” you will learn how to use Access with other products, including Microsoft Office. In addition, a whole chapter will try to answer the question “Which tool to use, Access or VB?” The material in Part VII, “Multiuser Issues,” shows you how to exploit Access’s rowlevel locking, replication, and security enhancements. Because so many Access applications are multiuser, this is one of the most important parts of the book. “Web Publishing with Access 2002,” Part VIII, digs deeply into using Access 2002 on the Internet. Since Access 2002 has embraced the Internet, we decided to really drill down into the topic with coverage on how to create dynamic Web sites powered by Access 2002 and a review of the new tools in Office 2002 that make Internet development easier. Appendix A, “References for Further Reading,” directs you to books and online sites where you’ll find valuable information to supplement what you learn in this book. This book started one rainy morning in a London laundromat with Tom and me cranking out code and an outline. We wanted to give something to the Access developer community that you could use, but something that came from our personal experiences. We then recruited James, who is equally dedicated to that vision. The result is in your hands; let us know what you think. We did it for you.
3
4
Access 2002 Development UNLEASHED
Conventions Used in This Book The following conventions are used in this book: • Code lines, commands, statements, variables, and any text you type or see on the screen appears in a computer typeface. • Placeholders in syntax descriptions appear in an italic computer typeface. Replace the placeholder with the actual filename, parameter, or whatever element it represents. • Italics highlight technical terms when they first appear in the text and are being defined. • A special 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 in the book, given the book’s limited margin width. If you see ➥ before a line of code, remember that you should interpret that “line” as part of the line immediately before it. • As a part of the Unleashed series, this book also contains notes, tips, and cautions to help you spot important or useful information more quickly. Some of these are helpful shortcuts to help you work more efficiently.
Database Design Unleashed
PART
I IN THIS PART 1 What’s New for Developers in Access 2002 2 Planning the Development Process 3 Database Design and Normalization 4 Advanced Queries 5 The Microsoft Jet Database Engine 4.0
CHAPTER 1
What’s New for Developers in Access 2002 IN THIS CHAPTER • User Interface Changes • Changes to the VBE
8
9
• Compatibility With Access 2000 Databases 10 • Database Conversion Error Logging 11 • Offline Data Access Pages
11
• Improved Integration with SQL Server 2000 12 • Other Access 2002 Features
13
8
Database Design Unleashed PART I
There is an old saying that says from a tiny acorn, a mighty oak tree grows. If this could be said of a software product, it would never be more apt than for Microsoft Access. Those who remember Access 1.0 recall an application with a file size limit of 128MB, no transaction capability, no real programming capability, static toolbars, a lack of referential integrity, and agonizingly slow performance. Despite those shortcomings, Access quickly became the most popular desktop database product because of its easy to use tools for building user interfaces, dynasets, and the visual query builder. With almost every update, Access has continuously evolved into a powerful and useful productivity tool and development platform. Access users and developers have seen constant improvement. The underlying database engine, Jet, now at release 4.0, supports transaction processing, referential integrity, replication capabilities, better concurrency management, increased speed, and greater stability. Its developer tools have evolved from simple macros to a full-blown VBA development environment almost identical to Visual Studio 6.0. The interface tools have improved also. Third-party tools and ActiveX controls expanded the design options available to developers. With Access 95 and 97, developers gained the ability to create multiple instances of forms. Access 97 also enabled developers to use Access’s Active Server Pages, thereby extending Access’s reach to the Internet. The improvements in Access 2002 are evolutionary, not revolutionary like the dramatic changes from Access 97 to Access 2000. Nevertheless, Access 2002 offers a friendlier, more productive, and more efficient development than ever. This chapter highlights Access 2002’s most significant enhancements and new features and, hopefully, entices you to read deeper into the book to learn how to use them in your own projects.
User Interface Changes Changes to Access 2002’s user interface are subtle. For example, it retains the Outlookstyle interface introduced in Access 2000, but its overall appearance seems simpler, cleaner, and more appealing. You can still create logical groups of tables, queries, forms, and reports using shortcuts to the actual objects. The “Orders and Sales” group, shown in Figure 1.1, shows this grouping capability and Access 2002’s more refined appearance. The streamlined menus remain, by default showing only the most commonly used options. Complete menus are available with a single click. Access’s renowned wizards for creating and editing objects have been enhanced and extended in Access 2002.
What’s New for Developers in Access 2002 CHAPTER 1
FIGURE 1.1
Changes to the VBE Access developers should be prepared for small, but thoughtful, changes to the VBE (Visual Basic Environment). Access 2002’s rich, highly customizable development environment, first introduced in Access 2000, has undergone few changes in its overall appearance. Similarly, Access 2002 introduces no earth-shaking functionality changes relative to Access 2000, but the smaller changes discussed in the next few paragraphs do suggest that Microsoft’s Access programming team thought about lowly Access developers while creating the product. Access developers will appreciate the new undo/redo capabilities. Access 2002 has finally implemented multiple levels of undo/redo when you are working in design view. This extended undo/redo feature applies to any Access database object and also to views, stored procedures, and functions in an Access Project. Another notable change in the VBE simplifies working with subforms and subreports. While working on a container report or form in Design view, simply double-click the subreport or subform or select Design View on the View menu and the subreport or subform will open in its own window. Putting subforms and subreports in their own design windows saves a few flicks of the wrist, makes the VBE a bit more intuitive and developer friendly, and is simply more convenient. Figure 1.2 shows the Customer Orders Subform1 in its own window in Design view.
1 WHAT’S NEW FOR DEVELOPERS IN ACCESS 2002
Everything related to orders and sales is in one convenient place.
9
10
Database Design Unleashed PART I
FIGURE 1.2 Modifying subforms is easier than ever with Access 2002.
You might also notice, while designing subforms and subreports, that a single click on the scrollbar no longer abruptly moves the focus from the top to the bottom or from one side to the other. Scrolling in Design view, especially in subforms and subreports, is much easier because the scrollbar moves in smaller increments than it did in earlier versions of Access. Again, this is a small enhancement, but one that is sure to reduce hair loss for Access developers.
Compatibility With Access 2000 Databases Developers and users upgrading to Access 2002 will appreciate a feature Microsoft calls round-tripping. Round-tripping refers to opening an Access 2000 database using Access 2002, modifying data, and then closing the database without ever having to convert the database file format. Compatibility between the Access 2000 and 2002 database file formats makes it easier for users to share data. From a developer’s perspective, it reduces the likelihood of data corruption or loss during database conversions. It also eliminates, at least in the short term, data conversion requirements from project plans, making the development project that much simpler. The title bar in Figure 1.1 shows that Access 2002 has opened the Access 2000 version of the Northwind database.
What’s New for Developers in Access 2002 CHAPTER 1
Inevitably, you or your development team will be compelled to convert a database to Access 2002’s format and will probably encounter conversion errors of one sort or another. Historically, Access developers have written custom code to catch and record conversion errors and to save the ostensibly “bad” data for later analysis. Access 2002 might nullify the need for such painstaking precautions. When importing or converting a database created with any version of Access back to Access 95, if Access 2002 encounters a data conversion error, it creates and populates a special table named Conversion Errors in the new Access database file. The data stored in the Conversion Errors table will help you identify and resolve the data conversion problem. The Conversion Errors table has three columns: Object Type, Object Name, and Error Description. Object Type identifies the type of database object (a report, query, table, and so forth) involved in the error. If the error was more general or did not apply to any particular database object, this field will have the value “Database.” Object Name contains the name of the object in which the error occurred. Unfortunately, if the error occurs in a module that is being compiled during the conversion process, the module’s name is not stored in the table. The Error Description column describes the error in greater detail.
Offline Data Access Pages Access 2000 introduced Data Access Pages to the Access user and development community. Data Access Pages (DAPs, henceforth) are simply Web pages, tied to an Access database backend, that present data stored in the database. Access 2002 extends DAPs by adding support for offline data access. Offline DAPs (ODAPs) function like the Windows Briefcase. Download data to your laptop Friday afternoon before leaving work. Update it over the weekend. Monday morning, plug the laptop into the network and use Internet Explorer’s Synchronize function to upload the modified data. The DAP in Figure 1.3 uses HTML intrinsics and COM components for its functionality. DAPs also have a rich object model and support Visual Basic Scripting Edition, JavaScript, and Office 2000 Web components. This support enables you, or your clients, to leverage existing Web development skills and make a smooth transition to Access 2002.
1 WHAT’S NEW FOR DEVELOPERS IN ACCESS 2002
Database Conversion Error Logging
11
12
Database Design Unleashed PART I
FIGURE 1.3 Access data and functionality can be used via a Web browser.
Improved Integration with SQL Server 2000 Access 2002 includes several new features that improve its usefulness as a front-end for Microsoft SQL Server 2000. Access now includes extended property support, batch update capability, and password security for Access Projects.
Extended Property Support Using extended SQL database properties within a Microsoft Access Project enables your Access Project to use SQL database validation rules, predefined text formatting, subdatasheets, input masks, and more. Extended properties can be used with many databases objects, including tables, fields, views, and stored procedures. Extended property support makes it easy to convert an Access database application into an Access Project using Microsoft SQL Server as the database backend.
Batch Updates Batch updates simply enable all data entry to be submitted to Microsoft SQL Server in a single operation when a user moves to a record, closes a form, or pushes a button. In fact, batch updates enable you to save or rollback multiple record changes using a single command.
What’s New for Developers in Access 2002 CHAPTER 1
Password Security for Access Projects Microsoft has also created new tools to create and manage the server-side objects from the Design view of the client. Other common administrative tasks, such as security, backup, and replication, can also be managed from Access 2002.
Other Access 2002 Features The features discussed in this section are primarily features intended for end users rather than developers, but some Access developers might find them useful, so they are mentioned here for completeness’ sake.
PivotChart and PivotTable Data Views Microsoft introduces PivotChart and PivotData views in Access 2002. You can use PivotChart and PivotTable views with most database objects, including forms, tables, views, stored procedures, and queries. PivotTable and PivotChart views include new events, making it easier to write code behind PivotChart and PivotTable forms. Finally, PivotTable and PivotChart views can be saved as both online and offline Data Access Pages.
XML Support Access 2002 includes support for XML, Extensible Markup Language, which is rapidly becoming the preferred method for data interchange between applications and businesses. Data from Jet or SQL Server database can be exported as XML simply by selecting the Export option from the File menu. Queries can also query data in XML format stored in a variety of applications. Figure 1.4 shows part of the Sales by Category report saved as XML data.
Linked Table Wizard Less experienced Access developers will appreciate Access 2002’s Linked Table Wizard, which makes it much simpler to link Access tables to SQL Server databases.
ANSI-92 Query Mode sans ADO Access 2000 introduced more ANSI-compliant SQL syntax and, if you used ADO (ActiveX Data Objects), you could use the ANSI-92 query mode. Access 2002 removes this restriction. That is, queries can now use ANSI-92 query mode without having to use ADO.
1 WHAT’S NEW FOR DEVELOPERS IN ACCESS 2002
If your Access Project is connected to a Microsoft SQL Server database, you can change the Project’s login password directly from the Database Utilities menu.
13
14
Database Design Unleashed PART I
FIGURE 1.4 Reports and tables can be saved as XML data.
Summary Microsoft Access 2002 polishes and fine-tunes the dramatic changes made in Access 2000. The Outlook-style interface is cleaner and the many wizards are more helpful than ever, but Access’s overall appearance is largely the same. Indeed, Access 2002 is a developer’s release, containing features that Access developers have been requesting for years. Database conversion error logging will make data conversion simpler to troubleshoot. DAPs have been improved to support disconnected recordsets and are easily resynchronized using Internet Explorer. Access 2002 represents another milestone on the road to full interoperability with SQL Server 2000 because it now supports password security for Access Projects, can perform batch updates, and also supports SQL extended properties. Access 2002 also includes a new batch of tools for creating and managing the server-side database objects from the Design view at the client. Some of Access 2002’s new features do cater to end users, of course, including XML support, the new PivotChart and PivotTable data view, a wizard that simplifies linking Access tables to SQL Server databases, and, as you just read, the freedom to use SQL-92 without having to use ADO. As observed at the beginning of the chapter, Microsoft Access 2002 continues the steady, upward trend in usability, power, features, and developer-friendliness.
CHAPTER 2
Planning the Development Process IN THIS CHAPTER • Gathering Requirements • Architecture
24
• Development Planning • Construction
17
28
24
16
Database Design Unleashed PART I
This chapter focuses on the development process rather than the nuts and bolts of VBA, queries, forms, and reports. The development process is a general term referring to the methods or techniques developers use to transform a need (“We need a simpler, faster way to track and process employee expense reports.”) into an application that fills that need. Just as a road map shows you how to get from one place to another, successfully completing any nontrivial development project depends on following a proven and repeatable development process that enables a development team (even a team of one) to progress from identifying a problem to providing a software product that solves the problem. Mastery of Access 2002’s development environment, in-depth knowledge of database design, and star-quality SQL programming skills—all of which are useful and important—matter little if you do not understand the problem you need to solve. This chapter discusses the central issues and activities that determine the success or failure of the development process. By the time you finish reading this chapter, you will be equipped with the basic tools necessary to enable you to create an effective development process of your own, based on proven methods. However, what you will learn in this chapter is only a starting point. Comprehensive coverage of the software development cycle would easily consume the entire book. The appendix includes references for further study. The development process consists of four phases: • Requirements • Architecture • Development planning • Construction During the requirements phase, you gather information and analyze the users’ real needs. During the architecture phase, you create the top-level design, determine the technology requirements, such as the server and client hardware and the software components, most appropriate for solving the problem at hand, and choose the development tools that are best suited for the project. Development planning, the third phase, is the period during which the design team creates a comprehensive plan describing the entire project. Development plans, even for small projects, answer the following questions: • What is the problem or need the project addresses? • What solution is being proposed? • How will the solution be implemented? • How long will it take? • How many people are needed? • How much will it cost?
Planning the Development Process CHAPTER 2
17
The final development phase is the construction phase, during which the project is created. Construction includes ordering and installing hardware, modifying network configurations, installing the necessary software, and, of course, writing and testing code. Figure 2.1 depicts the four phases of the development process from gathering requirements through construction of the application. It also shows some of the software releases created during the construction phase. This chapter details each of these areas. FIGURE 2.1 The development process.
Requirements
2
Time
Development Plan Construction
V1.0 Prototype 1
V1.0 Alpha 1
V1.0 Beta 1 V1.0 Beta 2 Version 1.0 RC1 Version 1.0
Gathering Requirements Gathering and analyzing requirements is the single most important activity in delivering a successful application. Conversely, many project failures result from inadequate or incorrect requirements.
Why Are Requirements So Important? Requirements are vital because they directly determine how the resulting application works. Requirements also control how long a project takes to complete, how many developers it will take to complete it, and how much the completed application will cost. If nothing else, if the development team does not understand what users want and the details of the business requirement the application is supposed to address, the developers will create the wrong application. Of course, the business need and the end users’ desires must also be clearly articulated.
PLANNING THE DEVELOPMENT PROCESS
Architecture
18
Database Design Unleashed PART I
Clearly understood requirements also affect a project’s completion time. Requirements that are well-researched and analyzed at the beginning of a project, before a single line of code gets written, reduce the number of unanticipated changes that lead to rework later. A general rule of thumb is that the cost to make a requirements change to an application goes up five to ten times at each major step in the development process. For example, if resolving a problem identified during the requirements phase takes one hour, it could take ten hours, or more, to fix during the construction phase. Similarly, adding functionality to a module that has already been tested and integrated into the rest of the application might take closer to fifty hours to implement correctly. A program bug not detected until the application has been deployed will probably take closer to 100 hours to resolve. Why so long? Consider the process involved. First, the requirements need to be updated. Next, the design has to be modified and the relevant code must be analyzed to assess where changes are needed. After making the necessary changes, the new feature or the bug fix must be tested against the existing modules, queries, forms, and reports. The application itself must be re-tested to ensure that the changes did what was anticipated and did not create new problems. Finally, the revised application must be re-deployed to each of the end users. Of course, these factors are software industry averages, not absolutes. Depending on the changes made, the financial cost and time delay might be more or less than these averages. If the error causes damage to your customer’s business, for example, the cost could be astronomical.
Finding the Real Problem Begin the requirements-gathering process with the perceived scope of the application. The perceived scope refers to your customer’s understanding of her business problem and the software product she believes will solve that problem. The customer’s perception of the problem might or might not be correct or complete.
Note An Employee Expense Reporting example will be used throughout this chapter to illustrate concepts of the development process.
For example, the customer might want a system for employees to enter and print expense reports. After some analysis, you might find that the real need is to automate the entry, distribution, approval, and processing of the entire expense-report process. Ferreting out
Planning the Development Process CHAPTER 2
19
differences like this is one of the challenges. Sometimes, customers want a solution that is too small to solve the problem. Other times, customers want a solution that is too big and complex. To understand how the desired application interacts with other parts of the business, it is vital to use the requirements gathering process to investigate the expected project scope.
Investigation To find the problem that really needs to be solved and to accurately determine the requirements, you have to put on a trench coat and become a business process detective. Here are a few tips for your sleuthing:
• Many business processes have two faces: the official way and the actual way. You need to understand both how a process is supposed to work and the way it really works. • Keep an open mind and listen carefully. Put aside your (and the clients’) first vision of the problem and the solution until they are verified through interviews and analysis. Table 2.1 lists examples of the types of requirements about which to ask while conducting your requirements investigation. The first step in your investigation is to identify all the stakeholders. A stakeholder is a person, group, or department with an interest in the process or the application. Managers, supervisors, and lead employees responsible for every key department involved in the process are stakeholders. Users of the current process are always stakeholders: they will be users of the new application you are developing. Some groups of stakeholders will be so large that you will need to select representatives to speak for the group. As the investigation proceeds, you might discover additional stakeholders to include. An additional benefit of involving stakeholders in gathering requirements is that involvement increases their feelings of ownership in the new system. You will see greater cooperation and acceptance during application deployment. Consider the expense report example. Interview a few representative users, perhaps one who rarely has any expenses, a second who travels constantly, and one or two average users. To obtain another perspective, you might interview one or two people in the payroll department who process those printed expense forms and receipts every month. Ask lots of questions, listen well, and take copious notes. Ask how the current process works
PLANNING THE DEVELOPMENT PROCESS
• Never rely on any one person for key information about how the current process works. Talk to as many people as possible or practical who are involved with the current process, especially end users, the people who will use the new solution and whose insight into the process most benefits the company.
2
Database Design Unleashed PART I
and what they like and dislike about it. Ask how they wish it worked. These notes will enable you to put together an accurate picture of the current process and business rules. Analyze the current process and document any error prone, slow, or redundant steps. Remember to document all the likes, dislikes, wishes, and dreams you heard during the interviews.
Process Diagrams
An example of a process diagram of a travel and expense report.
Need for Travel
1 Fills out: 1. Travel Request 2. Cash Advance
Cash
5
6
Travels
Fills out Expense Report
Requests
Check Expense Report with Receipts
2
Manager
FIGURE 2.2
Employee
Process diagrams are a terrific way to describe how a business process works. They clarify the interactions among the key individuals, groups, or departments involved in a process. They aid understanding because visual illustrations are frequently clearer than textual descriptions. After diagramming and analyzing the current process and the needs of the stakeholders, a second process diagram can be drawn to represent the revised process. Figure 2.2 shows the process diagram of the expense report example.
No
Approve Request?
7 Yes Approved Cash Advance Request
No
Approve Expenses ?
Yes
Accounting
3
Approved Travel Request
Cash Advance Rules
Authorization Limits
Travel Rules
4 Makes Travel Arrangements
Approved Expense Report with Receipts 8
Processes Cash Advance
Travel Agency Business Rules
20
20th of month
Processes Expense Report
Reservations and Tickets
Error Prone
Expense Report Rules
Delay
Each process stakeholder is represented by a layer. Figure 2.2 shows four stakeholders: Employee, Manager, Accounting, and Travel Agency. Individual steps or activities in the process, represented by rectangles, progress the move from left to right. In Figure 2.2, the first activity, numbered 1, is filling out a travel request form and a cash advance form. These steps process inputs from the left and produce outputs to the right. In Figure 2.2, the output of the first step is the requests, which might be approved or rejected. Diamonds represent decisions, such as approving the travel request made within the process. Vertical arrows into a process represent the influence of internal business rules or external regulations and other constraints. Constraints shown in Figure 2.2 include rules controlling cash advances and a manager’s maximum approval authority. Because
Planning the Development Process CHAPTER 2
21
the horizontal axis of the diagram represents time, any delays and time-consuming activities are identified easily. Process diagrams are fairly straightforward to create and easy for stakeholders to understand. After they see the diagrams drawn out, many stakeholders will be shocked at the complexity and convolution of their current processes. If you begin your process diagramming as early as possible, you can revise them during stakeholder interviews. Process diagrams are excellent tools to help structure and guide these interviews. Each stakeholder interviewed will further clarify and detail the overall process.
Tip Process diagrams should begin life not on a PC, but on a large sheet of paper. Designing on paper can be done more quickly and is more interactive. It is also less intimidating and easier to read. One trick to minimizing the inevitable erasing and reorganizing is to use sticky notes as the process blocks. After the diagrams have stabilized, then draw the process diagram using either the Microsoft Word 2000 drawing tools or Visio.
Identify the Scope of the Project Work with the customer to determine the appropriate scope for the application. Remember, this should be a long-term scope, not just centered on this phase of the project. In the expense report example, the developers and decision makers came to an agreement on the project scope. They agreed that the application should eventually automate the cash advances, travel requests, and the entire expense reporting process, from the employee’s creation of a travel request to Accounting’s receipt of the balance due/owed request. They decided to ignore the accounting systems and the actual travel booking process because they are outside the application’s scope.
Writing Down Requirements Written requirements are one of the best methods of communication between the developer and customer. Written requirements reduce misunderstandings because they state unambiguously what the application will provide. The writing need not result in a
2 PLANNING THE DEVELOPMENT PROCESS
You might find it useful to create a hierarchy of process diagrams. The one top-level diagram will describe the big picture, whose process steps will be rather large in scope. Sub-processes can then be detailed on their own process diagrams. This hierarchical approach often simplifies the diagrams and makes them easier to understand.
22
Database Design Unleashed PART I
formal, unwieldy document. There are many effective ways to communicate requirements: sample reports, forms, process diagrams, or drawings. There is no magic to writing requirements. The most important measure is that the customer can read and understand them. Ask the following questions about each requirement: • Does it describe what is needed, rather than how to implement it? • Can it be verified after implementation? • Is it unambiguous? • Does it completely describe the need? • Is it consistent with the other requirements? Requirements serve as part of the work contract. Like a contract, both the development team leader and the customer should sign it. This document is the baseline against which the project will be measured and the basis for proceeding with the application development. From this point forward, carefully consider how requirement changes will impact the planned budget and schedule. Remember to revise the budget, schedule, and any related requirements or design documentation when changes are made. Table 2.1 shows examples of many kinds of requirements you should consider using. Tip Create a database of all the requirements. For each requirement, include an identification number, type, description, date, source, benefit, how to verify the requirement after implementation, priority, and more.
TABLE 2.1
Requirement Types
Type of Requirements
Description
Example
Functional
These requirements describe functions or features that are needed, plus the business rules that apply.
The user will be able to set the priority of the customer to Critical High Medium Low
Planning the Development Process CHAPTER 2 TABLE 2.1
23
continued
Description
Example
Performance
Performance requirements include • Speed • Response time • Capacity • Database size
The inventory database will support up to 20 users across the corporate LAN with a mean order status response time of 200ms.
Security
Security requirements limit usage and access to application features and data.
All users must log in to the application. Every user will be a member of only one of the following security groups: User Administrator Manager
Scalability
Scalability concerns the capability to expand the quantity of data, users, sites, or frequency of data collection.
The application must support the current 50 users and an additional 50 added over the next two years.
Extensibility
Extensibility requirements detail the capability to add features to the application in future releases.
The application will be designed and implemented to allow addition of customer invoicing.
Configurability
Configurability is the measure of how easily software parameters can be modified by the customer without requiring the development team to make the changes.
The Administrators will have the capability to update the insurance rates annually.
Compatibility
Compatibility is the ability to be installed and operational in various hardware/software environments, and to interact with other software applications.
The software product will be installed on Win95, Win98 and Win NT 4.0 Workstation with a minimum of 8MB memory and 200MB hard drive available.
Availability
Availability is the measure of how many hours, or what percentage of time, a software product is available to perform the work for which it was developed.
The database administrator will reserve from 10:00 to 11:00 p.m. for backup and maintenance of the backend database.
2 PLANNING THE DEVELOPMENT PROCESS
Type of Requirements
24
Database Design Unleashed PART I TABLE 2.1
continued
Type of Requirements
Description
Example
Usability
Usability, or ease of use, is the measure of how well-trained users are able the system.
The application will include online Help that will cover 90% of the features.
Ease of learning
Ease of learning is the measure of how easily and quickly users are able to learn to use the system.
One day of training will be sufficient for users to become proficient before initial use of the application.
Architecture After analyzing the written requirements, choose the appropriate architecture, technologies, and development tools. Should the client application use Excel, Access, or VB? Should it be Web-based and use ASP and XML? Is a two-tier architecture acceptable, or would n-tier be more appropriate? Will the backend database be Jet/MDB, SQL/MSDE, SQL Server, or Oracle? These are important questions that will each have a large impact on the final product. An accurate budget or schedule cannot be produced until these decisions are made.
Development Planning Development planning refers to deciding how to construct the application. Should all features and functionality be implemented in one comprehensive version 1.0 release, or should you defer some of the features for later versions? Whatever method you choose, you will need a roadmap with a budget and schedule before proceeding. You might have created a preliminary project plan to get the necessary approvals to get this far in the project. That preliminary version was based on the anticipated requirements and scope, and it included only rough estimates of schedule and budget. If you had a preliminary project plan, this is the time to revise it. If not, this is the time to write one. With the Requirements phase complete, you now have enough information to create an accurate task list, resource list, schedule, and budget.
Planning the Development Process CHAPTER 2
25
Tip Developers should always track their actual time. The best way to improve your project estimating skills is to compare your original estimates with the actual time required.
Delivery Strategy
Consider again the expense report example. During the design meetings, developers and decision-makers agreed that version 1.0 should focus on automating the creation, approval, distribution, and status-checking of expense reports. The next release, version 2.0, would add automating the creation, approval, distribution, and status checking of travel and cash advance request process. Figure 2.3 shows the top-level development process steps and an example of possible releases. Figure 2.4 shows a revised process diagram identifying the process steps each release addresses.
FIGURE 2.3 A delivery strategy example.
Requirements Architecture Development Plan
Time
Construction Phase 1
Prototype 1 V1.0 Alpha 1 V1.0 Beta 1 Version 1.0 RC1 Version 1.0 RC2 Version 1.0
Construction Phase 2
V2.0 Beta 1 V2.0 Beta 1a Version 2.0 RC1 Version 2.0
2 PLANNING THE DEVELOPMENT PROCESS
A delivery strategy specifies what will be released and when. Avoid the urge to include every idea and cool feature into one huge release. Rather, plan on several incremental releases. Doing so reduces the strain on the development team and enables the customer to validate the application as it progresses.
Database Design Unleashed PART I
Manager
The revised process diagram incorporates the delivery strategy.
Employee
FIGURE 2.4
Need for Travel
1 Fills out: 1. Travel Request 2. Cash Advance
Cash
5
6
Travels
Fills out Expense Report
Requests
2 No
Approve Request?
Check Expense Report with Receipts
7 Yes Approved Cash Advance Request
No
Approve Expenses ?
Yes
Accounting
3
Travel Agency
26
8
Processes Cash Advance
Approved Travel Request
4 Makes Travel Arrangements
Approved Expense Report with Receipts
20th of month
Processes Expense Report
Reservations and Tickets
Phase 2 - Version 2.0 Travel Request & Cash Advance: 1. Creation 3. Distribution 2. Approval 4. Status
Phase 1 - Version 1.0 Expense Report: 1. Creation 3. Distribution 2. Approval 4. Status
Standards Without standardization between developers, applications become very difficult to maintain and reuse. Rule #1: Standards make a big difference. Rule #2: The standard itself makes little difference. Translation: Consistency between developers is the primary goal of standardization. Whether everyone does it the “best” way is a secondary benefit. Caution Avoid the temptation to argue about what is “best”—just pick a good method, get everyone to use it, and stick with it.
The most common types of standards concern an application’s interface and naming and coding conventions.
Planning the Development Process CHAPTER 2
27
Interface Professional applications always have a consistent appearance and functionality. If some forms use a Cancel button to exit and others use a Quit button, users will quickly get confused, and training and support costs will increase. If one developer likes the look of each field in its own sunken box with data in bold type, while another designs forms with labels with bold type and flat text boxes, the application will look thrown together. Make these interface decisions early in the development process and have all the developers follow them before each decides to do his or her own thing.
2 Rather than spend a lot of time writing an official looking document, just create an Access database (MDB) with a set of forms and reports that includes examples of all the common uses of controls. This can be a growing, evolving example of your preferred user interface styles. Better yet, include the code behind the forms to handle navigation and other common functionalities. These forms will serve as your standard templates.
Here are some types of style issues to cover in your standard: • Form layout (for example, how you arrange controls on the form, form size, and proportions) • Field grouping (for example, sunken frames versus simple lines) • Use of colors, fonts, font size, and bold/italic typestyle for fields and labels • Button names and behaviors (for example, Cancel, Close, or Quit?) • Indication to user whether forms are read-only or can be edited • Dialog wording (for example, terse or verbose)
Naming Standards Naming standards make reading and reviewing the code much easier. They also greatly simplify maintenance tasks later on. The following example uses a datatype, prefixnaming standard. The code is easy to read and understand. dblLodgingTotal = Double(intNights) * dblRate
PLANNING THE DEVELOPMENT PROCESS
Tip
28
Database Design Unleashed PART I
However, the next example, although functionally identical to the first one, leaves everyone, including the developer, in the dark. x = Text7 * Text12
These are key parts of most naming standards: • Object prefixes (for example, txt, cbo, lst . . .) • Datatype prefixes (for example, sgl, int, str . . .) • Standard base names (for example, use Acct or Account) • Standard abbreviations (for example, stat = status)
Coding Standards Like naming standards, consistently applied coding conventions ease code maintenance and make code easier to read and understand. The following are examples of the issues you might want to cover in your coding standard: • Comment header blocks • Comments in code • Indentation • Size of subs and functions (for example, maximum of 60 lines) • Use of “Option Explicit” Tip Several naming standards are published and available for Access/VBA/Office/VB development. The two most common are the Reddick and Leszynski naming conventions. One advantage of these common standards is that new developers hired by your company might already be familiar with the standard. Also, books, technical articles, and conference materials tend to follow these naming conventions. Again, which one is “best” is much less important than selecting one and using it consistently.
Construction Several techniques are available to you for improving your team’s effectiveness during the construction phase of the project. This section discusses how to divide development tasks between developers and encourages you to test thoroughly and track all defects found along the way.
Planning the Development Process CHAPTER 2
29
Divide and Conquer: Construction Logistics There are many ways to approach the construction phase. You could start by implementing the most difficult or risky parts first, implement the easy parts first, or build the forms first and finish with the reports. The method recommended here is to create a solid foundation and build upward. This foundation consists of the table design, the most class modules and functions, and simple first attempts at the “core” forms. The goal is to establish a basic functioning core upon which each developer can build. For the forms, you want to spend the time necessary to design and build one or two as solidly as possible. These can be used as design templates for subsequent forms.
While creating the development foundation, invest the time and effort to create and test reusable components. The initial effort spent at the beginning will pay off quickly and repeatedly later in the project.
The development team must work together while building the foundation. At the outset of the construction phase, the most important design decisions are worked out and all the interfaces are defined. After completing the foundation, then split the team into smaller groups or assign task to individual developers. Two effective ways to divide the implementation among teams is to do so by Access objects or by application objects. If assigning tasks by Access objects, one team focuses on the forms, another on the reports, and, perhaps, a third coding business rules and providing support routines. If you select a division of duties based on application functionality, especially if the overall architecture is object-oriented, one team would develop the Expense Report objects—including the class modules, tables, forms, and reports—and another team would develop the Approval objects. Figure 2.5 shows the process that each team follows during the construction phase. It takes place at several levels of the development process. At a high level, the diagram illustrates the entire construction phase as development progresses from the detailed design to the final application testing. At a lower level, Figure 2.5 also represents how an individual developer might spend an afternoon developing a particular feature. Throughout the construction phase of a project, there are usually several software releases. These often include a prototype to confirm the graphical user interface (GUI) design; several alpha releases to solicit early user feedback; one or two beta releases to allow users to test the application in real, day-to-day operations; and, finally, the official Version 1.0 release distributed to all the users.
PLANNING THE DEVELOPMENT PROCESS
Tip
2
Database Design Unleashed PART I
FIGURE 2.5 Requirements & Architecture
Steps in the construction phase.
Requirements or Architecture Issues
Detailed Design Design Issues Design Review
Implementation Implementation Issues Review
Testing
Software
30
Builds and Releases As the complexity of the application and the project increases, it will become more and more important to track carefully the various builds and releases of your application. Periodically, create a build by integrating the most recent changes and additions from each developer. A build is a new version of the application, including the front-end MDB, related DLLs, EXEs, and back-end data files. Many builds will be created throughout the development process for internal use by the development team. Only a few of these are actually given to any of the users. By doing this every day or two during development, every developer has access to the latest modifications. A release is a build deployed outside the development team. This is usually distributed to one or more of the end users. Table 2.2 shows a project with 178 builds, but only sixteen releases. TABLE 2.2
Release Example
Release
Build
Prototype 1 Prototype 2 V1.0 Alpha 1
12
V1.0 Alpha 2
27
V1.0 Beta 1
42
V1.0 Beta 2
56
Planning the Development Process CHAPTER 2 TABLE 2.2
31
continued
Build
Version 1.0 RC1
88
Version 1.0 RC2
89
Version 1.0
89
Version 1.1 RC1
93
Version 1.1
93
Version 1.2 RC1
97
Version 1.2 RC2
98
Version 1.2
98
Version 2.0
135
Version 3.0
178
As you can see in Table 2.2, there are several types of releases issued throughout the development process. During the concept or requirements phases, one or more prototype releases enable users to evaluate the proposed GUI. After a few key features are working, alpha releases given to a few users provides valuable early feedback that reduces later work. When the application is nearly feature-complete, one or two beta versions for users to test and really put to use will improve the quality of the final product. Most of these releases are done for every major version release (big changes) and minor revision (smaller changes). Release candidates (RC1, RC2, for example) include fixes resulting from betas and, when used, provide further user and deployment testing prior to an official version release for widespread distribution. Figure 2.6 illustrates the process of creating a build. Note The number of builds is not a cause for concern. A large number of builds is not a sign of poor development. It is a sign of careful development. Rather than integrating dozens of large changes all at once, frequent builds allow fewer smaller changes to constantly to be integrated.
2 PLANNING THE DEVELOPMENT PROCESS
Release
32
Database Design Unleashed PART I
FIGURE 2.6 Creating a build. Current Build of Application
Integrate Changes and Additions
New Build of Application
Test
Changes from Developer #1 Changes from Developer #2 Changes from Developer #3
Implementation Issues
Creating a new build (see Figure 2.6) starts by collecting and integrating the changes and additions from all the developers. Sometimes, integration is as easy as importing a new report into the front-end MDB. More often, though, adding a new form or module to the application will require some changes to one or more calling forms to provide a way to use the new functionality. This might require two of the developers to sit down together to successfully integrate their changes. After everyone’s changes and additions are integrated into the current build, you can update the release/build name displayed by the application.
Tip Include the current release name and build number on the application’s start-up form and also on your “about” form opened from the Help menu. This makes it easy to determine in which release a defect is found. For example: “Version 1.0 Build 89 — 05/02/2001”.
This is also an ideal time to make an archival copy of the entire build. Should something happen to the development environment before the next build, the last build would be the most recent reference point. Frequent backups are also good computing practice. This copy should include the front-end and back-end MDBs, as well as any other files that are being changed from build to build. Consider storing the backup offsite, to preserve the substantial resources and time invested in the project.
Planning the Development Process CHAPTER 2
33
Integration testing should be done after every new build is created to ensure that the various parts work together as planned. After the build is proven to work acceptably well, the entire development team must upgrade in order to base its work on the most current version. If possible, take advantage of the features of a source code repository tool, such as Microsoft Visual SourceSafe or PVCS. Such tools provide automated methods for creating and tracking changes to individual files, and to larger builds and releases made during the project lifecycle. It will also reduce problems that can occur when changes are made by multiple developers.
2 If you do not use some sort of source code control, then proper archival procedures are even more important.
To create a release, take a successful build and make an installation package. This might be as simple as zipping up the front-end MDB, or as complex as using the Office 2000 Developer’s Edition installation tool to create a professional installation script. In either case, the release should be tested on several representative PCs to verify that it will work cleanly. Figure 2.7 illustrates the release process.
FIGURE 2.7 Creating a release.
Create Installation Package
Installation Testing
Distribute and Install
User Training
Write Release Notes and Write/Update All User Documentation
After testing is completed successfully, distribute the release to users for installation. Include a short Release Notes document with each release. At a minimum, list any new features, changes, and known problems. Even if the users never look at this Release Notes document, a Release Notes document gives developers a reference point for remembering what has changed from release to release. Remember to update your user documentation whenever the application is revised. Out-of-date documentation is worse than no documentation at all. Also, it is important that the release be given to end users working on as many different hardware and networking configurations as possible.
PLANNING THE DEVELOPMENT PROCESS
Caution
34
Database Design Unleashed PART I
Weeding out problems in this area are best identified very early in the release testing process. Figure 2.8 illustrates a complete build and release cycle. FIGURE 2.8 A build and release cycle example.
Add features & make changes Create a new Build Create a new Release for users
e.g., Build 41 e.g., Beta 1.0 - Build 42
Get feedback from users Add features & make changes Create a new Build
e.g., Build 43 Additional Builds
Add features & make changes Create a new Build Create a new Release for users
e.g., Build 55 e.g., Beta 2.0 - Build 56
Get feedback from users
Many builds, and an occasional release, will be created throughout the life of the project. Figure 2.8 illustrates a single pass through the build and release cycle. Every build offers an opportunity for all developers and testers, and perhaps even users, to test the application and to submit problems and ideas to the rest of the team. These are often called defects or issues. Depending on their priority relative to continuing development, these defects might be addressed by developers in time for an upcoming build, or they might be deferred until later.
Creating a Detailed Design A detailed design gives you the chance to document how the application’s features are to be implemented, particularly complicated or complex ones. The detailed design should cover at least class modules, form navigation, tough algorithms, and unusual automation
Planning the Development Process CHAPTER 2
35
techniques. Recording your design decisions, and how you implement them, aids you and others later, when changes or additions need to be made. Hold one or more design reviews until the design is ironed out. Tip
Public Sub ProcessAllUpdates() ‘ Comments : Get the updated mail from the MAPI Inbox, ‘ unattatch it and update the current database. ‘ Parameters : <none> ‘ Returns : <none> ‘ Created : Tuesday, July 27, 1999 11:44 PM by Joe Developer ‘ Pseudo Code: ‘ -------------------------------------------------------‘ Sub ProcessUpdates() ‘ UpdateCount = 0 ‘ UnattatchAllUpdates() ‘ Open a recordset from tblDownloadReceivedResults ‘ For each
in Recordset ‘ ProcessOneUpdate() ‘ If Successful Then ‘ Delete Update file ‘ Increment(UpdateCount) ‘ Next ‘ --------------------------------------------------------
Reviewing the Design Design reviews simply involve asking someone else to go over the design problem and your proposed solution. These reviews might range from an informal “Hey Stephanie, will you look at this for me?” to a formal meeting with a presentation and review by several team members. The value of an external review is that a fresh set of eyeballs might see a solution you overlooked or identify a flaw in your solution. In the process of explaining the design to someone else, you will often see an additional problem you neglected or an even better solution. Another developer will often find something you’ve overlooked. This is an ideal time to find design problems—before you invest extensive time coding and testing the application.
2 PLANNING THE DEVELOPMENT PROCESS
A great way to document non-trivial algorithms is to include pseudocode comments in the sub or function. Pseudocode is simplified VBA code included as comments to describe the overall process you are implementing in the following code. The exact syntax is unimportant; you are simply describing, in general terms, the algorithm that is implemented in VBA. The following example shows the use of pseudocode in a sub header.
36
Database Design Unleashed PART I
Implementation Implementation is the one step of the development process that clients, users, and inexperienced developers think of when they visualize how software is developed. This is when the forms and reports are built, and the code gets written. Most of the other chapters of this book discuss the challenges you face here.
Code Review Code (or implementation) reviews have the same purpose as design reviews: getting a fresh set of eyeballs on your code. Peer reviews should examine each of the forms, reports, and queries, as well as all the code itself. Like the design reviews, just by explaining what you did and how it works, you will invariably notice something you missed. Someone else looking at your work will often see something you have overlooked dozens of times. You or your reviewer might find a problem with your implementation, design, architecture, or perhaps with the requirements. Remember that the earlier in the development process that problems are found, the easier and cheaper it is to fix them. Code reviews are also beneficial as a way to train developers. To this end, ask senior developers to review code written by junior team members. Another valuable benefit is that developers get a better understanding each other’s areas of the specialty. Tip Consistent use of coding and naming standards will make code reviews much easier and quicker. This also helps to avoid lengthy debates and arguments between developers over whose style and naming is better.
Tip If you are an independent developer, not part of a multideveloper team, find a partner and review each other’s code. The time and energy will quickly pay off for both of you. User groups can be a huge benefit here.
Testing Testing involves verifying basic functionality to catch bugs, and also ensuring that the application meets the agreed upon requirements. There are several kinds of testing to
Planning the Development Process CHAPTER 2
37
perform throughout the development process: unit, application, configuration, and installation testing. Part of the design plan will include a test plan that identifies, at least in general, overall testing procedures.
Unit Testing
What should you test? Testing a subroutine, function, or class module should cover all the input parameters by trying the range of expected and unexpected values, including boundary conditions (values immediately above, equal to, and below the range, and values of 0, null, or empty, depending on the datatype). When testing a new form, make sure that every control is tested. Check, among other things, data validation, locked fields, tab order, inserting new records, style consistency, and form navigation.
Application Testing Application testing (often called system testing or integration testing) is done on the overall application after all the features have been integrated. There are several purposes for performing application testing. The most important is to confirm that all the requirements have been met. The second purpose is to determine how ready for release the application is. The following are some examples of the kinds of tests you need to perform: • Test the behavior when tables are empty. • Test with different video resolutions. • Test with the Windows display settings font size set to both Small Fonts and Large Fonts. • Test with a couple of different Windows display color schemes. • Test printing to several different printers (particularly the brand and model the users have). • Test with the Windows taskbar Auto Hide option turned on and off. • Test that “What’s this?” help, ToolTips, and status bar text match their associated fields.
2 PLANNING THE DEVELOPMENT PROCESS
Unit testing refers to testing an individual feature or object, such as a key query, a form, or a report. Before you begin implementation of a feature or object, spend some time deciding how you’re going to test it. Run unit tests as each feature is completed to verify that they work as intended and are ready for integration into the rest of the application. A typical rule of thumb is to allocate about 20 percent of total development time to unit testing. For example, if it took you seven hours of detailed design time to develop the algorithm and three hours to code and debug it, estimate two hours of time to test it.
38
Database Design Unleashed PART I
• Test the tab order on each form. • Verify that all keyboard shortcuts are unique on each form. • Test the use of default keys (Enter and Esc) on all forms. • Test style consistency between all forms and reports (Style Standard).
Installation and Configuration Testing Installation and configuration testing evaluates how well the application behaves when it meets the real world. PCs in the real world are seldom like the developers’ machines. They have different software installed with different amounts of memory, use strange printers, even stranger video cards, and are used in an unpredictable variety and combination of ways. This variety of configurations affects how easily an application can be installed, and how the application operates after installation. If possible, test on the worst-case environments. For larger projects, consider using a company that specializes in this kind of testing. Many offer labs brimming with equipment and software, both new and old.
Tip Test the installation and operation on a clean PC as well as a dirty one. Clean PCs only have an operating system and required software installed on a newly formatted disk (just like a brand-new computer). A dirty PC is one on which multiple versions of many applications have been installed over a period of time. Testing on both kinds of PCs is the best way to find unexpected dependencies on DLLs, registry settings, templates, and other supporting files. Diskimaging software can be very useful in quickly re-creating various configurations for testing purposes.
Defect Tracking A defect is any bug, flaw, error, or problem related to an application. It might be a defect in a document, a tool, or in the implementation of the application. Defects might be found at any time during or after development, and all defects should be reported and tracked. Any of the following activities might expose defects: • Design and Implementation Reviews—Defects discovered during reviews range from disregarding standards to design errors.
Planning the Development Process CHAPTER 2
39
• Document Reviews—During these reviews, many types of potential defects can be discovered. The requirements document might be missing or contain inadequate requirements. The design documentation might not address all the requirements, or one or more of them might be wrong. • Testing—Coding defects are the most common type of defect discovered during testing. Also, documentation defects can be found because the tests should be developed based on the documentation.
• Error Handler—If you are using automated error reporting, such as described in Chapter 13 “Professional Error Handling,” possible defects can be received by e-mail or obtained from the error log at the customer’s site. • Post-Release Rollout—Defects unfortunately surface after a release is rolled out and in widespread use. No matter what the source of the possible defect or who reports it, it must be documented. Collect all defects in one place. Defects scattered through various memos, scraps of paper, and e-mail might be lost or forgotten. You can use a commercially available defect-tracking tool, create your own Access database, or log defects in a three-ring notebook. However you document the defects, you need a process to ensure that possible defects are addressed. Note that addressing does not necessarily mean fixing it. You might decide not to fix some defects based on their frequency or severity. More on this in a moment. Put every defect through the same process from discovery to final resolution. 1. As soon as possible after a defect is discovered, enter the details into your tracking system. Table 2.3 shows a list of suggested information to collect. Tables 2.4 through 2.8 further describe some of the defect information. 2. The development team periodically reviews all unaddressed defects assigning a priority to each. This decision is based on the severity, frequency, and reproducibility of each defect. It is then assigned to one of the developers for resolution. 3. The developer either fixes the defect or determines that it is not a problem, or it updates the resolution description and status. If the defect is fixed the resolution status is changed to “fixed.” 4. If possible, a different team member verifies all fixed defects, and the resolution status is updated to “verified.”
2 PLANNING THE DEVELOPMENT PROCESS
• Customer Support/Help Desk—During beta testing or after deployment, defects reported by the customer will come in through the developer or staff who supports the released product. Any enhancement ideas should also be included in the defecttracking system to assure they will not be forgotten.
40
Database Design Unleashed PART I TABLE 2.3
Defect Information
Data Field
Description
Unique identifier
Using sequential numbers will work. If multiple people enter defects, make sure that they are all are unique.
Description of defect
Describe the behavior of the potential defect, including error codes and steps to repeat the problem.
Found by
Name of person reporting defect.
Found when
Date and time of discovery.
Expected results
What had been expected to happen?
Found where
Create a list of documents and software items to report defects against (for example, requirements document, architecture document, form name, report name, module name).
Version
Document the version of the document or MDB (e.g., Beta 2.1 of software, Build 36, the 6/29/1999 version of the Requirements Document, and so on.)
Software and hardware configuration
List any pertinent configuration information such as display resolution and color depth, amount of memory, available disk space, operating system, other currently executing software, and so on.
Severity
How big a problem is this defect? See Table 2.4.
Frequency
How often is the defect encountered? See Table 2.5.
Reproducibility
How easily can the defect be reproduced? See Table 2.6.
Priority
How important is it to fix this defect? See Table 2.7.
Assigned to
Which developer is going to address this?
Resolution Status
What is the status of the defect? See Table 2.8.
Resolution Description
How was it “Fixed”? Why was it “Deferred” or “Not a Problem”?
TABLE 2.4
Severity of Defect
Severity
Criteria
Critical
There is a loss of functionality, or data is lost.
Serious
A feature does not work as expected, or there is a loss of usability.
Medium
Causes a non-critical aspect of the application to fail with no data loss.
Low
A cosmetic problem or an enhancement request.
Planning the Development Process CHAPTER 2 TABLE 2.5
41
Frequency of Occurrence
Frequency
Criteria
Common
A user could easily encounter the defect with normal use at least once per use. (For example, when closing the main form.)
Occasional
The user is unlikely to encounter the defect every time he or she uses the product, but will probably encounter it sometime. (For example, only when users print a two-page invoice.)
Seldom
A small fraction of the users will ever encounter this defect.
TABLE 2.6
Reproducibility of Defect
Reproducibility
Description
Always
Can always reproduce defect.
Intermittent
Can usually reproduce defect, but not always.
Once
Observed defect once, no further testing for repeatability performed.
Non-repeatable
Observed defect once, unable to repeat it.
TABLE 2.7
Priority of Defect Repair
Priority
Description
Critical
Must be fixed.
High
Should be fixed if at all possible.
Medium
Fix if time is available.
Postpone
Don’t bother fixing it at this time.
TABLE 2.8
Resolution of Defect
Resolution
Description
Unaddressed
New and not reviewed yet.
Not a Problem
Works as designed.
Deferred
Will not fix it at this time.
Fixed
Problem has been fixed and is awaiting verification.
Verified
Fix has been tested, and the defect is resolved.
PLANNING THE DEVELOPMENT PROCESS
(For example, only with a certain video card.)
2
42
Database Design Unleashed PART I
Tip You can improve your development process by looking for the root cause of defects. By determining how and where the defect was introduced, you might learn ways to avoid similar problems in the future. Common root causes are design errors, coding errors, missing requirements, ambiguous requirements, or developer- or customer-training deficiencies.
Version Control The section “Builds and Releases,” earlier in this chapter, suggests using some type of source code repository or version-control software. Why? The most common reason is to synchronize changes. If the development team includes more than one developer, eventually two developers will simultaneously change the same object. Perhaps they will both open a form at the same time, and one will add a field while the other is fixing a function. First one, and then the other, will save their changes back to the “master” MDB. The second one to save will win—overwriting the changes the first developer had just saved. With any luck, the first developer will retest his work and notice that his change has disappeared; otherwise, the problem will simply show up again later. There’s no work like rework! However, this kind of problem is solved by monitoring and controlling who is allowed to make changes to an object. Another reason to implement version control is to identify and re-create a prior working version. There will be times when you will need to verify that a problem exists in an earlier version. Restoring a prior version is also useful when planned changes don’t work as expected, and you want to undo them. These problems apply to development teams of any size. There are several techniques and tools that can address these version-control problems. Probably the best solution is to purchase a commercial tool designed for the job. The most popular is Microsoft’s Visual SourceSafe because it is tightly integrated with Microsoft’s development tools, including Access 2002. The most important elements source code tools provide: • Tracking changes to files and providing the ability to roll back changes to a specific point • Maintaining a version history • Limiting access to specifically identified personnel • Automated version numbering
Planning the Development Process CHAPTER 2
43
• The ability to maintain multiple code branches, such as a “release,” “stable,” and “development” code branches
Caution Access is different from many other development tools because it saves all its objects in a single MDB file. Many commercial version control tools only track individual files. This limitation forces developers to check in and out the entire MDB! This is not very useful in an Access development environment, so make sure any tool you evaluate has support for Microsoft Access at the object level.
This chapter took a galloping survey of some of the methods, issues, and techniques for planning and managing your development process. Oddly, the actual coding is only a small part of it. Always invest the time needed to gather and understand the user’s real requirements. Plan your development approach, and write a project plan to help focus your development efforts on meeting the requirements, budget, and schedule. Hold design and code reviews and track every build, version, and defect throughout the development process. To the degree you successfully incorporate these ideas into your development projects, you can count on the successful completion of projects that come your way.
PLANNING THE DEVELOPMENT PROCESS
Summary
2
CHAPTER 3
Database Design and Normalization
IN THIS CHAPTER • The Relational Design Theory
48
46
Database Design Unleashed PART I
Access applications are database applications, an obvious statement that can get lost in the details of designing a dialog box or crafting the perfect form. To develop smarter, faster, more efficient database applications, you need to understand the concept of database normalization, this chapter’s topic. Relational database management systems, or RDBMSes, such as Microsoft Access, implement a theory of data management and manipulation called, strangely enough, relational theory, pioneered by Dr. E.F. Codd at IBM during the 1970s. This chapter introduces you to just enough relational theory to enable you to design Access databases that take advantage of the way relational database operations work. Note Critics of Microsoft Access argue it does not conform to all of Dr. Codd’s 13 rules defining a relational database and so cannot be called relational. Predictably, Access’ supporters argue it is fully conformant. From a practical standpoint, it behaves like relational database. You may judge for yourself whether it is truly conformant.
Codd’s Rules The following table lists the 13 rules Codd declared to which a database system much conform in order to be considered a true relational database management system. Rule
Description
The Foundation Principle
Any RDBMS must be able to manage databases entirely through its relational capabilities. If a database system depends on a record-by-record data manipulation tools, it is not truly relational.
Information
All data in a relational database is represented explicitly as values in tables. Data cannot be stored in any other way.
Guaranteed Access
Every data element must be accessible logically through the use of a combination of its primary key value, table name, and column name.
Missing Information
Null values are supported explicitly. Nulls represent missing or inapplicable information.
Database Design and Normalization CHAPTER 3
System Catalog
The database description or “catalog” exists at the logical level as tabular values. The relational language (SQL) must be able to set the database design in the same manner in which it acts on data stored in the structure.
Comprehensive Language
An RDBMS must support a clearly defined data-manipulation language (SQL) that comprehensively supports data manipulation and definition, view definition, integrity constraints, transactional boundaries, and authorization.
View Updatability
All views that can be updated by the system. In a true RDBMS, most (although not all) views would be updatable.
Set Level Updates
An RDBMS must do more than just be able to retrieve data sets. It has to be capable of inserting, updating, and deleting data as a relational set.
Whenever possible, application software must be independent of changes made to the base tables. For example, no code should be rewritten when tables are combined into a view.
Integrity Independence
Data integrity must be definable in a relational language and stored in the catalog. Data integrity constraints can be built into applications. However, this approach is foreign to the relational model. In the relational model, the integrity should be inherent in the database design. continues
AND
Logical Data Independence
DATABASE DESIGN
Data must be physically independent of the application program. The underlying RDBMS program or “optimizer” should be able to track physical changes in the data. For example, an RDBMS’s application programs should not have to change when an index is added to or deleted from a table.
3 NORMALIZATION
Physical Data Independence
47
48
Database Design Unleashed PART I
Distribution Independence
RDBMS capabilities will not be limited due to the distribution of its components in separate databases.
Nonsubversion
If an RDBMS has a single-record-at-a-time language, that language cannot be used to bypass the integrity rules or constraints of the relational language. Thus, not only must an RDBMS be governed by relational rules, but these rules must be primary laws.
The Relational Design Theory The relational design theory developed by Dr. Codd consists of the following categories: • Tables and uniqueness • Foreign keys and domains • Relationships • Data normalization • Integrity rules
The Benefits of Using the Relational Model Using the relational design theory, you gain the benefits of years of research into the best way to manage data. Some of the benefits you can achieve by following the relational model are • Ensuring data integrity. • Storing data storage efficiently. • Giving your database application tremendous room for growth. • Creating a database that behaves predictably because it conforms to these welltested rules. • Enabling other database designers to understand your database because it follows the rules. • Ensuring that database schema changes are easy to implement • Improving the speed of data access. I know this ties in with efficiency; however, the mention of the word speed is important.
Database Design and Normalization CHAPTER 3
49
Tables and Uniqueness When you create database applications, each table represents an entity or process in the real world. Tables can represent people, events, financial transactions, and physical items such as products. Relational theory requires that all data is stored in a table consisting of unique rows and columns. The way to guarantee uniqueness for each rule is to set a primary key for each row. A primary key is a field or group of fields that uniquely identifies that row. If the primary key consists of multiple fields, it is called a composite key. The primary key must be unique—that is, it must appear in one and only one row. Access allows you to designate a field as a primary key by setting it as a Key value in table design view. Access will then check to see if the data in that field is unique and does not allow duplicates. Sometimes it can be hard to come up with a unique value for each row while following the business rules in your application. For example, suppose you are creating a contact management system to track your contacts. Your initial database design might resemble the table shown in Figure 3.1.
A common rule of database design is to keep the key as simple as possible and to choose the key from data that is the most unique and least likely to change. A person’s name might change due to marriage, divorce, and so on. Phone numbers and e-mail addresses
AND
As you develop your contact management system, you might select ContactName, ContactEmail, or one of the ContactPhone fields as the key. Possible key fields are commonly referred to as candidate keys because, during the initial database design period, they might be used as primary keys, but the final decision has not been made.
NORMALIZATION
A table storing contact information.
3 DATABASE DESIGN
FIGURE 3.1
50
Database Design Unleashed PART I
change all the time. A good key would be a Social Security number, but what if your contact lives outside the United States? In this situation, Access allows you to create an AutoNumber field to use as a primary key. An AutoNumber is a numeric value that Access maintains and automatically increments each time you add a new record to a table. However, an AutoNumber is not the same as a record number. In record number–based database products, record numbers are recalculated as records are added or deleted. In Microsoft Access, a record’s AutoNumber remains the same as records are added or deleted (except in an unusual circumstance discussed in Chapter 5, “The Microsoft Jet Database Engine 4.0”). AutoNumber values are not reused in the same table after a record is deleted. There are two types of AutoNumber values: • Integers • ReplicationID or GUID (used in Replication). Note You can manipulate a Jet AutoNumber in a few ways. You can set the AutoNumber increment value, reset the starting seed, and start counting backward. See Chapter 5 for more information.
Foreign Keys and Domains When one table’s primary key is used in another table, it is called a foreign key because it is foreign to the second table. Foreign keys are used to relate records from two (or more) tables, a topic discussed in the section titled Relationships later in the chapter. Figure 3.2 illustrates a table using foreign keys. FIGURE 3.2 A table with two foreign keys.
Figure 3.2 shows the Contacts table with two foreign keys, ContactID and PhoneID. ContactID is the primary key of the tblContactName table (not shown) and PhoneID is the primary key of the tblContactPhone table (not shown).
Database Design and Normalization CHAPTER 3
51
When you use foreign keys, they will always be in the same domain. A domain is the pool of possible values from which a column’s value is drawn. For example, in the United States, the domain of ZIP codes consists of all valid ZIP codes. Another example might be a university’s student ID numbers. If the student ID system is based on Social Security numbers, the domain consists of all valid Social Security numbers available to the system.
Relationships When you create primary keys and foreign keys, you are defining relationships. Relationships refer to how the records in one table connect to the records in another table. Access supports three different types of relationships: • One-to-one relationships • One-to-many relationships • Many-to-many relationships To set relationships in Microsoft Access, press the Relationships button on the toolbar or select Tools, Relationships from the menu to bring up the Relationships window.
A one-to-one relationship.
Figure 3.3 shows a one-to-one relationship because each record in the table tblContacts relates to, at most, one related record in tblContactEmail. One-to-one relationships are the least common types of relationships because most databases include related information in one table. For security reasons, however, you might choose to break out information into two tables. Financial transactions often involve many one-to-one relationships.
AND
FIGURE 3.3
DATABASE DESIGN
Two tables have a one-to-one relationship if, for each row in one table, there is at most one related record in the related table. Figure 3.3 shows an example of a one-to-one relationship.
NORMALIZATION
One-to-One Relationships
3
52
Database Design Unleashed PART I
One-to-Many Relationships The most common type of relationship is the one-to-many relationship. A one-to-many relationship occurs when a table has zero or many related records (sometimes called child records) in another table. A typical example occurs in a customer order database, because one customer can have many orders. Similarly, in your contact database, one contact (the “one” side of the relationship) might have several phone numbers (the “many” side). To express the relationship in terms of keys, each contact has a unique ID which is the primary key in one table. This primary key would appear as a foreign key in each related record in a table of telephone numbers. Figure 3.4 illustrates a one-to-many relationship. FIGURE 3.4 A one-to-many relationship.
The ContactID field is tblContacts’ primary key and a foreign key in tblContactPhone. ContactID 2 appears twice in tblContactPhone, meaning that there are two related records in tblContactPhone. Figure 3.4 includes the contents of the table to make the relationships clearer.
Many-to-Many Relationships Given two tables, tblAlpha and tblBeta, a many-to-many relationship occurs when one or more rows in tblAlpha relate to zero or more rows in tblBeta, and one or more rows in tblBeta relates to zero or more rows in tblAlpha.
Database Design and Normalization CHAPTER 3
53
Many-to-many relationships are problematic because it is difficult to select unique records from one table using existing relationships. Suppose you have three contacts (stored in tblAlpha) who use any one of three fax numbers (stored in tblBeta). If you want to send one of those contacts a fax, it is not immediately clear which fax number to use. Conversely, if you receive a fax from one of those three numbers that lists the sender’s fax number but not the sender’s name, you will not immediately know which of the three sent the fax. Unfortunately, Access does not have a way to resolve many-to-many relationships between two tables. The only way to do so is to create a so-called “linking” table. A linking table is a table that contains the primary keys of both tables as foreign keys. Figure 3.5 shows a many-to-many relationship between tblContacts and tblContactType through the linking table tblContactInfo. tblContacts contains all the contacts in your database. tblContactType lists all the types of contact information: Fax, Email, Phone, and Pager. tblContactInfo is the linking table. It contains a reference to a contact (ContactID), a contact type (ContactTypeID), and the contact information itself (ContactInfo), so you can locate either a specific telephone number using a contact’s name or a specific contact name using a particular telephone number.
AND
A many-to-many relationship using a linking table.
DATABASE DESIGN
FIGURE 3.5
NORMALIZATION
Moreover, if your contact adds a new type of communication (like a Web address) to the list, you simply add “Web Address” to the lookup table (tblContactType), and then add the new linking record to tblContactInfo. This is the most flexible way to build a contact management system because it avoids repeating fields (Phone1, Phone2, and so forth), blank fields, and having to add new fields to a table when you add another communication type to the list. A common naming convention when using a linking table this way is to use the “trel” prefix to identify a linking table. In this case, the tblContactInfo would be named trelContactInfo.
3
54
Database Design Unleashed PART I
Data Normalization Data normalization describes the process of designing a database (or modifying an existing database design) and organizing data to take best advantage of relational database principles. Codd defined six levels of normalization that he described as normal forms. The first three, known as First, Second, and Third Normal Form, have the most impact on database design decisions. As you read through the next few paragraphs, keep the following somewhat whimsical but useful summation of Codd’s first three laws in mind: “The values in a row are dependent on the key, the whole key, and nothing but the key, so help me Codd.”
First Normal Form First Normal Form requires that all columns (fields) in a table contain atomic values. That is, each field should contain one value, not a list of values or any repeating groups of data. Many flat file “databases” store data in this fashion, which makes searching quite difficult. Note The term flat file database refers to files, almost always text files but sometimes binary, containing some type of data. They are called ”flat” because they lack any structure or hierarchical arrangement suggesting the relationship between one record and the next. Flat files are often database dumps.
Figure 3.6 shows an example of a table that is not in First Normal Form. FIGURE 3.6 A table not in First Normal Form.
The ContactInfo column violates First Normal Form because it contains multiple pieces of information. Putting the contact type (Fax, Voice, Email) in its own column (ContactType), making separate records for each contact number in the ContactInfo column, creating the ContactInfoID column, and making ContactID the table’s primary key results in Figure 3.7. The table shown in Figure 3.7 is in First Normal Form because each column contains a single, discrete piece of information.
Database Design and Normalization CHAPTER 3
55
FIGURE 3.7 A Table in First Normal Form.
Second Normal Form A table in Second Normal Form is one in First Normal Form and in which every non-key field is fully dependent on the entire primary key. That is, any column in a table that is not the primary key or part of a composite primary key must depend on the primary key or all parts of a composite primary key for its meaning or interpretation. tblContact is not in Second Normal Form. The primary key is a composite consisting of ContactID, ContactInfoID, and ContactInfo. ContactName does depend on ContactID, but not on ContactInfoID or ContactInfo.
AND
A Table in Second Normal Form.
DATABASE DESIGN
FIGURE 3.8
3 NORMALIZATION
To put this table in Second Normal Form, put ContactInfo, ContactInfoID, and ContactType in a separate table. Next, use ContactID as a foreign key in the new table, creating a one-to-many relationship. The result is shown in Figure 3.8. Now both tables are in Second Normal Form because the columns in each table depend on their respective table’s primary keys.
56
Database Design Unleashed PART I
Third Normal Form A table is in Third Normal Form when it is in Second Normal Form and when no nonkey column depends on the primary key. tblContactOld in Figure 3.8 contains a field dependent on another non-key field, so it is not in Third Normal Form. If you do not see it right away, look at it for a few moments before continuing with the next paragraph. If you missed it, the dependent column is ContactType. Why? Given the ContactID and ContactInfoID, you can use a query to obtain the ContactType. The solution is to create a third table named tblContactType using the ContactType descriptions, and use tblContactType’s primary key (ContactTypeID, in this case) as a foreign key in tblContactOld. The result is shown in Figure 3.9. FIGURE 3.9 Tables in Third Normal Form.
All three tables are now in Third Normal Form.
Real-World Benefits of Normalization Why bother to normalize data? The original table in the previous example (Figure 3.6), listed the contact types and information in an array of values, making searching for the contents of a fax number very difficult. In addition, when one of your contacts’ phone number changes or gets a new form of communication method, like a cellular phone, updating the data is difficult and easily botched. First Normal Form improved the
Database Design and Normalization CHAPTER 3
57
situation and gave you more flexibility because it created separate records for each contact’s voice number, fax number, e-mail address, and so forth. First Normal Form, shown in Figure 3.7, only partly solves the problem. Contact data is difficult to manage because the same information is repeated many times and because storing the same name 10 times wastes disk space. Second Normal Form, in Figure 3.8, is almost, but not quite there. It eliminates most of the wasted disk space and repetitious information, but limits your flexibility. Third Normal Form allows you to add and remove contact types from a single table without requiring any changes to the structure of other tables. The tables in Figure 3.9 give you the most flexibility and use the least amount of disk space.
Data Integrity Rules
A cascading delete has the same effect for deleting a primary key. Cascading deletes ensure that deleting a record from a “one” table also deletes all related records from the “many” table(s). This feature has a downside, however. If you delete a customer and cascading deletes were set, all the “many” invoices would be deleted. If you do not have deletes set, the deletion would not be allowed in the “one” table until you deleted all the
AND
Suppose you have a lookup table for states. New York is in this table with a primary key of NY and a description of New York. Imagine that New York City broke away and formed its own state (before you laugh, it almost happened in 1789!) When you change your NY value to NNY (for “New New York”), the values of NY in all the child tables will be changed to NNY. If cascading updates were not set, you would need to add a record to the lookup table for NY1, update all the records in the child table, and then delete the NY record from the lookup table.
DATABASE DESIGN
A cascading update ensures that when you update a record’s primary key value on the “one” side of a one-to-many relationship, the change will be reflected in all records on the “many” side. The change, that is, will cascade through all related records.
3 NORMALIZATION
When normalizing a set of tables, you should also consider data integrity rules. Data integrity rules, sometimes called constraints, are rules, often enforced by the database engine itself, that ensure the consistency of your data. For example, to revisit the contact database example a final time, if you delete a contact from the main table (tblContact), you want to make sure that related records in other tables are also deleted. Deleting only a related record, on the other hand, should not delete other related records or, certainly, the primary contact information. Most data integrity rules in an Access 2002 database are determined by the relationships you define. In addition, Access lets you specify cascading updates and deletes when defining relationships.
58
Database Design Unleashed PART I
records in the “many” table, to avoid leaving any orphans. Orphaned records are records not related to an existing primary key. As a result, they are not directly accessible and constitute wasted disk space.
Summary As a relational database, Access 2002 implements a proven database model. Applying the relational model to your database designs will enable you to take full advantage of relational database advantages. A normalized database is a key element of a properly designed relational database. A database design that eliminates redundant data in any single table, places tightly related datasets into individual tables, keeps unrelated datasets separated in their own tables, and establishes clear relations between tables will enable you fully to exploit the relational database model Access 2002 implements.
CHAPTER 4
Advanced Queries
IN THIS CHAPTER • Using the Query Object
60
• Creating Queries in Access
62
• Creating Advanced Queries • Mastering Totals Queries
74
75
• Mastering Crosstab Queries • Mastering Parameter Queries
83 87
• Mastering Pass-Through Queries • Mastering Data Definition Queries
91 93
60
Database Design Unleashed PART I
The workhorses of any Access database are its queries. Queries come in a variety of forms and types. They can be a permanent part of the database or constructed on the fly. They can simply retrieve records from the database or they can update existing records, add new ones, and delete old ones. You can create queries directly using Structured Query Language (SQL), or you can build them by using the query design window (previously known as the QBE or Query By Example grid), a graphical user interface for query construction. An Access query might know exactly what it is supposed to do when it runs, or it can ask questions beforehand. Queries can work with data that resides in an MDB file, spreadsheets, another desktop database product, client/server databases, such as Microsoft SQL Server or Oracle, or any combination. Queries can even create, delete, or modify database objects. Because queries are the most common way to interact with your data, this chapter reviews query terminology, illustrates basic join queries, and then explores advanced Access 2002 queries.
Using the Query Object Access 2002 queries are database objects just like tables, reports, and forms. In most cases, the query object is the starting point for modifying or deleting existing queries and for creating new ones. They reside inside Database window’s query container. For more convenient access to frequently used queries, you can create shortcuts to them in custom groups. To view a database’s existing queries, click the Queries object in the Groups Window of the Database container. To view a query’s properties, right click a query object and select Properties. This shows a properties sheet resembling the one shown in Figure 4.1. FIGURE 4.1 A query’s Properties sheet displays valuable query characteristics.
One of the most useful pieces of information the Properties sheet shows is a description of the query. A good description will help you understand (or remember!) what the query does if you have to revisit it later. Similarly, other developers will find the description useful when they need to work on your query. This is a very helpful property, so
Advanced Queries CHAPTER 4
61
consistently take a few moments to describe a query when you first create it and to update the description as the query changes. Note Of course, you can also click the Properties icon on the toolbar or select Properties from the View menu. Rather than constantly and tediously listing such alternatives, this chapter uses right clicks whenever possible and assumes you know what the alternatives are.
Other useful information the Properties window shows includes its type (Select, Action, Parameter, Crosstab, or SQL), its creation and last modification dates (updated automatically), its owner (by default, the person who created it), and whether to show the query in the Database window. The owner and hidden status have implications for security, discussed in depth in Chapter 22, “Security.” Tip The standard method to keep users from seeing a query, or any other Access 2000 database object, is to prefix its name with USYS, as in USYS_myquery. You can view hidden objects during development or maintenance; select Tools, Options from the menu bar, click the View tab in the resulting dialog box, and then place a check in the Hidden checkbox.
Caution
The final field a query’s Properties sheet displays is whether it is replicable—that is, whether it is subject to the database’s replication scheme, if any. Replication status is important because it controls if, or when, it will be modified by another, presumably more current, version during replication. The Replicable checkbox shown at the bottom of Figure 4.1 is disabled, meaning that the database is not set up for replication.
ADVANCED QUERIES
Microsoft uses the object prefix MSYS to hide database objects. Never allow users to tamper with these system tables because doing so could corrupt the database. Likewise, developers should not use hidden objects because Microsoft does not promise to maintain them from one version to another.
4
62
Database Design Unleashed PART I
Creating Queries in Access As mentioned in the previous section, most interaction with Access queries starts with the query object. The friendly graphical interface facilitates the mechanics of working with queries but does little to aid in understanding queries. Before examining advanced query features and usage, this section quickly reviews common query terminology and how to construct basic queries.
Using the Query Design Window Access’s query design window makes it easy to create queries. The query design window is a graphical tool enabling you to control almost every part of a query. All data sources, whether native tables, linked tables, or even other select queries, can be displayed on the query design window and manipulated in exactly the same way. The query design window shows the relationships between the tables and queries (tables and queries look the same in the query design window), sorting and grouping instructions, and, naturally, the selection criteria all. Figure 4.2 shows a query in the query design window. FIGURE 4.2 The query design window offers a nearly complete graphical tool for query management.
The query design window is divided into two parts. The top portion is the table pane, which shows all the data sources the query uses, the relationships between the sources, if any, and the type of relation (one-to-one, one-to-many). The bottom portion shows the query properties, such selection criteria, sort order, or whether a field in the selection criteria should appear in the query result. To see a detailed list of a query’s properties, right-click anywhere in the table pane window to display the shortcut menu and then choose Properties. Each property is described in Table 4.1. The text following the table expands on the brief property descriptions.
Advanced Queries CHAPTER 4 TABLE 4.1
63
Query Properties
Property
Description Optional explanation of the query’s design or purpose.
Default View
Specifies the initial view of the query result form. New in Access 2002.
Output All Fields
Controls the output of all fields used in the query.
Top Values
Limits the number of records selected to a specified value based on the output sort order.
Unique Values
Returns records containing unique values in a given field.
Unique Records
Selects only records with unique values in all fields.
Run Permissions
Enables users to execute a query against data otherwise restricted based on the permissions assigned to their username or group.
Source Database
Specifies the database containing the field being queried. The default setting is the current database.
Source Connect Str
Contains the name of the application that created the external source database.
Record Locks
Determines how the query handles contention issues for the records the query affects. Options are No Locks, All Records, or Edited Record.
Recordset Type
Defines the type of recordset the query creates. Options are Dynaset, Dynaset (Inconsistent Updates), or a Snapshot.
ODBC Timeout
Sets the time limit, in seconds, after which an ODBC query will time out.
Filter
Defines a subset of the records to display, temporarily hiding others.
Order By
Controls the order in which the query recordset is displayed.
Max Records
Specifies the maximum number of records the query returns.
Orientation
Sets the order of the query result to the normal reading order for a language. New in Access 2002.
Subdatasheet Name
Creates a query resultset with drill-down capabilities.
Link Child Fields
Names a field on a subdatasheet, preferably a key, matching a field on the main query.
Link Master Fields
Names a query field, preferably a key, matching a field on the subdatasheet. This field must show in the query result in order for the subdatasheet to work.
4 ADVANCED QUERIES
Description
64
Database Design Unleashed PART I TABLE 4.1
contnued
Property
Description
Subdatasheet Height
Specifies the height (in inches) of a subdatasheet when it is displayed.
Subdatasheet Expanded
Controls when a subdatasheet is displayed.
Note Although it is possible to update data through a subdatasheet, as of this writing, the query does not automatically reflect that change in the main data sheet’s calculations without being restarted.
Setting Output All Fields to Yes is the same as clicking the Show checkbox of every field in the query. One reason to use this option is that it makes all the fields in the query available to other queries, forms, and reports. On the other hand, it often simply results in cluttered, hard to query output. You can use either integers or percentages with the Top Values property. You can also choose one of the canned values or percentages, or provide your own. The sort key, which defines what constitutes the top values, is the leftmost sorted field. For example, if a query result contains fields named product name, unit cost, and retail price (from left to right in the grid) and needs to show the five most expensive products based on their retail prices, the retail_price must be the first sorted field (again, reading left to right in the grid) and it must be sorted in descending order. An ascending sort would return the five least expensive products. If the results were also sorted on unit_cost, the top five items would be the most expensive products based on their unit cost. If no fields are sorted, you will get the first five records presented without sorting. The Unique Values property reduces the number of records a query returns. For example, suppose you have an outstanding_orders table that contains, among others, a column named custid showing the customer ID of each outstanding order. If you want to find out which customers have unfilled orders, set the Unique Values property to Yes for the custid field (a customer can have many orders). When securing a database, especially in a multiuser environment, locked tables prevent users from editing data arbitrarily. Certain queries, though, might still need to modify the data. Run Permissions make this possible because a query’s permissions can be set. For example, a query whose Run Permissions are set to those of the query’s owner will
Advanced Queries CHAPTER 4
65
execute with the owner’s permissions, not those of the user. This property makes it relatively painless to secure a database and still allow users to perform actions against it. The Source Database and Source Connect Str property settings work together to give a query access to unattached external data. The Source Database property would contain a path and filename if the data were contained in another database to which there was no attachment. The Record Locks property has three options: No Locks, All Records, and Edited Record. No Locks allows multiple users to make changes to the same record. The first user to write changes to disk “wins,” at least temporarily. Access warns the others that they are working with a record someone else has changed and gives each the option to abandon their own changes, to overwrite the changes, or to copy the changes to the Clipboard and decide what to do after that. All Records locks the records controlled by the query against edits by other users until the first user releases. Edited Record affects only the record the user is currently editing. When setting a query’s Recordset Type property, keep referential integrity and the query’s purpose in mind. If the query is only used to display data, use a Snapshot because Snapshots do not allow the users to edit the data and execute more quickly than the other options. Dynasets should only be used to update returned records on the many side of a one-to-many relationship that needs to be updated. The Dynaset (Inconsistent Updates) setting permits updates to data on both sides of a relationship, but, because it has serious implications for referential integrity, use it only if the relationships specify the referential integrity and cascading updates options.
The Subdatasheet Name property allows you to create a query that returns a recordset supporting drill-down. Suppose you write a query showing total sales by product. To enable drill-down, set the Subdatasheet Name property to the name of the table or query containing the actual order details. The query result will show the summary of total sales by product and a switch to click to see the details underneath the summary values. The Subdatasheet Expanded property, if set to Yes, causes the detail in the subdatasheet to be displayed when the query is opened. If the property is set to No, the user must click a switch to drill down into the detail of the subdatasheet.
4 ADVANCED QUERIES
If Max Records is set, the only way to see records that are not returned is resetting or clearing this property. Use the Orientation property to define the reading order of the results a query returns. For example, an application used by Hebrew readers should use right-to-left reading order, while applications for all Romance languages require a left-toright orientation.
66
Database Design Unleashed PART I
Note The time range for ODBC Timeout is measured in seconds with its default setting of 60 seconds. However, setting the property to zero does not make the query constantly check for a response; it actually turns the Timeout feature off, so no timeout error will occur.
Using the Table Pane All the tables, or queries, involved in a query are represented in the table pane, the top portion of the query design window. Each table appears as a small window with its field name listed inside. If you place a query in the table pane, only the fields that have been marked to show in that query’s resultset will appear. Any relationships, or joins, specifically defined using the Relationships window appear in table pane automatically. You might also see lines between tables even if you have not explicitly established any relationships. Microsoft calls this feature AutoJoin. If you add two tables to a query, the tables each have a field with the same or compatible data type, and if one of those fields is a primary key, Access assumes they are related and automatically creates a join between them. It might be that two fields with the same name are not really related, so be sure to check all the relationships in your query before you use it. Better yet, to disable AutoJoins, select Tools, Options on the menu bar, click the Tables/Queries tab, then clear the checkmark in the Enable AutoJoin checkbox. Tip For the best and most reliable performance, establish your relationships in the Relationships window of the database object. This enables relationships to be used in the engine’s execution plans, an internal method Jet uses to monitor and modify how it performs queries. Explicitly defined relationships also enable referential integrity, cascading updates, and deletes to be enforced at the engine level rather than in code.
Placing a Table or Query in the Table Pane Putting a table or query into the table pane is simple. When you first create the query and enter Query Design view, Access prompts you to select the tables or queries you want to use. If you need to add a table or query later, select Query, Show Table to reopen the dialog box or use the toolbar’s Add Table button.
Advanced Queries CHAPTER 4
67
Establishing Relationships in the Table Pane To create table relationships in the table pane, select a field name in one table representation and drag it to its related field in another table representation. This action draws a join line between those two fields and they will now act as related fields in this query. The join line might also have some characters attached to it such as an infinity symbol and the numeral 1. These characters describe the nature of the relationship between the fields and are displayed when you create the relationship at the database level. If you established the relationship at the database level, the relationship is one-to-one, one-tomany, or many-to-one. The join line represents this by displaying a 1 near the table on the one side of the relationship and an infinity sign on the many side of the relationship. Note that a join line does not mean that records exist satisfying the join, only describes that the potential exists. Like all other Access database objects, the join line (rather, the join itself) has properties you can manipulate. Unlike other Access database objects, you have to double click a join line to view or change them. Figure 4.3 illustrates a join properties window. FIGURE 4.3 Open a join’s Properties window by double clicking the join line.
4 ADVANCED QUERIES
As you can see in Figure 4.3, a join’s properties sheet contains four dropdown boxes and three radio buttons. The dropdown boxes specify the related tables and the columns that relate them. The radio buttons indicate the type of relationship (join) between the tables: an inner join, a left outer join, or a right outer join.
68
Database Design Unleashed PART I
Selecting a Join Type Selecting an improper join type can render a query useless for several reasons, such as selecting the wrong records, selecting records from the wrong table, or, most commonly, causing record inserts, updates, or deletes to fail outright or to create orphaned records in the table on the many side of a relationship. This section explains the differences between the join types available in the Join Properties window (and the Edit Relationships window). Inner Join is the default option, represented by a straight line between fields. Inner joins return a recordset consisting of only those records from both tables in which the related fields are equal. For example, a query of a customer table and an order table, joined on their CustomerID fields, would return only those customers who had placed orders and only orders connected to customers in the customers table. A left outer join (the join created if you select radio button 2 in Figure 4.3) returns all records from the table on the left side of a relationship (the Contacts table in Figure 4.3) and only records with a matching field from the table on the right side of the relation. The line representing this relationship has an arrow at one end that points at the righthand table. If you consider a left outer join one in which the left-hand table dominates the resultset because all of its records appear in a query’s resultset, whether they have a match or not, then a right outer join is the opposite because all records from the right-hand table would appear in the query result, but only records from the left-hand table with matching values appear in the result. Do not let the terms left and right confuse you. They do not refer to the tables’ positions in the query design window. Rather, left and right in this context refer to the tables’ positions relative to the query’s join expression, which controls the records selected. To illustrate, consider the following query: SELECT Customers.CustomerID, Orders.OrderID, Orders.OrderDate FROM Customers INNER JOIN Orders ON Customers.CustomerID = Orders.CustomerID;
As written, this query creates an inner, or simple, join. The join expression is Customers.CustomerID = Orders.CustomerID. The left hand table is Customers and the right-hand table is Orders. To create a left join, the SQL would resemble: SELECT Customers.CustomerID, Orders.OrderID, Orders.OrderDate FROM Customers LEFT JOIN Orders ON Customers.CustomerID = Orders.CustomerID;
Advanced Queries CHAPTER 4
69
The join expression is the same, but the added clause, LEFT JOIN Orders ON, requests a left join, so, as explained earlier, all records from Customers (the left hand table) and only records from Orders with matching values in the join field (CustomerID) will be returned. Similarly, a right join should resemble the following: SELECT Customers.CustomerID, Orders.OrderID, Orders.OrderDate FROM Customers RIGHT JOIN Orders ON Customers.CustomerID = Orders.CustomerID;
eferential integrity. It is likely that you could have customers without orders, for example, but you should not have orders without customers at the same time. If running a left outer join and a right outer join against the same relationship results in unmatched return records, you need to check your data integrity because records on the subordinate side of a relationship lacking a match on the dominant side of the relations are called orphaned records. Orphaned records are usually invisible to the normal operation of the database, but they can result in statistical discrepancies if the subordinate table is queried without the dominant table being involved. In other words, a report showing orders by product might not agree with a report showing orders by customers.
Using Inner and Outer Joins The following figures and listings show the different resultsets obtained using the join types discussed in the last section. The queries vary only slightly, and run against the same data, the Customers and Orders tables in the Northwind sample database. Listing 4.1 shows the SQL statement that creates an inner join. Figure 4.4 shows the result of an inner join.
The ten customers with the fewest orders using an inner join.
ADVANCED QUERIES
FIGURE 4.4
4
70
Database Design Unleashed PART I LISTING 4.1
The SQL Statement for the Query in Figure 4.4
SELECT TOP 10 Customers.CompanyName, Count(Orders.OrderID) AS CountOfOrderID FROM Customers INNER JOIN Orders ON Customers.CustomerID = Orders.CustomerID GROUP BY Customers.CompanyName ORDER BY Count(Orders.OrderID);
This query shows a count of orders for each customer and has an inner join, so the only records displayed are the ones represented on both sides of the relationship. Contrast this result with one created by Listing 4.2 and illustrated in Figure 4.5. FIGURE 4.5 The twelve customers with the fewest orders using an outer join.
LISTING 4.2
The SQL Statement for the Query in Figure 4.5
SELECT TOP 10 Customers.CompanyName, Count(Orders.OrderID) AS CountOfOrderID FROM Customers LEFT JOIN Orders ON Customers.CustomerID = Orders.CustomerID GROUP BY Customers.CompanyName ORDER BY Count(Orders.OrderID);
The second query indicates Figure 4.4’s resultset is inaccurate. Why? The outer join’s results (Figure 4.5) show two customers who have not ordered anything at all, something the inner join did not and could not show. Alternatively, you can use an unmatched query to isolate these customers. The term unmatched query refers to an outer join in which the foreign key’s criterion is set to Null. Unmatched queries make it easier to notice blank fields in a query’s output. Listing 4.3 executes just such an unmatched query, producing the output shown in Figure 4.6.
Advanced Queries CHAPTER 4
71
FIGURE 4.6 Customers without orders.
LISTING 4.3
The SQL Statement for the Query in Figure 4.6
SELECT Customers.CompanyName, Orders.OrderID FROM Customers LEFT JOIN Orders ON Customers.CustomerID = Orders.CustomerID WHERE Orders.OrderID Is Null;
The query in Listing 4.3 eliminates the clutter of extra records, displaying only the two records of customers who have placed no orders, instead of the 10 or 12 returned when the Null criteria is not applied against the foreign key. The SQL statements in the following two queries (Listings 4.4 and 4.5) differ by a single word, yet produce markedly different results (see Figures 4.7 and 4.8). FIGURE 4.7 Output of an inner join.
4 ADVANCED QUERIES
LISTING 4.4
The SQL Statement for the Query in Figure 4.7
SELECT TOP 10 Customers.CompanyName, Count(Orders.OrderID) AS CountOfOrderID FROM Customers INNER JOIN Orders
72
Database Design Unleashed PART I LISTING 4.4
continued
ON Customers.CustomerID = Orders.CustomerID GROUP BY Customers.CompanyName ORDER BY Count(Orders.OrderID);
FIGURE 4.8 Output from an outer join.
LISTING 4.5
The SQL Statement for the Query in Figure 4.8
SELECT TOP 10 Customers.CompanyName, Count(Orders.OrderID) AS CountOfOrderID FROM Customers LEFT JOIN Orders ON Customers.CustomerID = Orders.CustomerID GROUP BY Customers.CompanyName ORDER BY Count(Orders.OrderID);
Listing 4.5 returns the 12 records shown in Figure 4.8, rather than the 10 requested, because the LEFT JOIN forces all records from the Customers table to be displayed. Hopefully, these five examples demonstrate the differences between inner and outer join and the more important point that accurate query output depends not only on querying the right tables and fields, but also making certain that proper relationships between tables exist. As always, GIGO (Garbage In, Garbage Out)!
Using the Query Grid The lower half of the query design window is the query grid. The query grid is the real heart of a query’s design view and where you will do most of your work on a query. The query grid is so important because it is where you list the fields to query, the fields to present, the sorting order, the grouping hierarchy, the calculations, and the crosstab configuration; insert, delete, or update information if appropriate; and, most importantly, the criteria defining the records the query affects.
Advanced Queries CHAPTER 4
73
Placing Fields on the Query Grid To place fields on the query grid, you can • Double-click a field name to move it to the first available position in the query grid. • Click and drag fields to any column position in the query grid. • Control-click one field at a time to select multiple fields, then drag them simultaneously onto the grid as a group. • Double-click a table’s title bar to select all the fields in the table and then drag them to the query grid. • Double-click, or click and drag, the asterisk at the top of a table’s field list to place all of a table’s fields on the query grid. • Select values from the Fields and Tables dropdown boxes on the query grid itself. The first row determines the field and the second determines the table.
Establishing Sort Order Use the query grid’s third row, the Sort row, to set the sort order, if any. Query results can be sorted in Ascending, Descending, or Not Sorted. If more than one field is chosen for sorting, the sort order is applied left to right.
Displaying Results The fourth row controls whether fields used in the query appear in the resultset. Even if it does not appear in the resultset, it can still affect the result of the query. The resultset must display at least one field for the query to execute.
Defining Selection Criteria
• Constants • Mathematical expressions • Logical expressions • Functions • The name of a field, control, or property that evaluates to a single value • An expression that performs a calculation, manipulates string or character data, or tests data
ADVANCED QUERIES
The fifth and subsequent rows define the query’s selection criteria. The selection criteria can consist of one or more of the following:
4
74
Database Design Unleashed PART I
• The name of another query • Raw SQL statements If possible, avoid using raw SQL statements. SQL expressions used as selection criteria execute for each record in a query’s possible resultset, which slows the query’s performance. Use subqueries instead because they have the same overall effect without imposing, in most cases, the same performance penalty. Tip You can add multiple copies of the same fields to a query if need be. If you do, turn off the duplicates’ Show option, do not sort the result using the same field more than once, and do not perform the same calculation on field duplicates.
An optional row in the query grid is the Total row. Hidden by default, you can access it by clicking the Totals button on the toolbar or by selecting View, Totals from the menu bar. When activated, the Totals row becomes the third row in the query grid. Totals queries, variously called aggregate functions, aggregation queries, or rollup queries, impose significant restrictions on query design. Nevertheless, these restrictions become trivial when you realize the flexibility aggregation queries offer. Both advantages and disadvantages discussed in the section titled “Mastering Totals Queries.”
Creating Advanced Queries Depending on one’s experience level, an advanced query might be one that merely looks complex, say, a three-table select that performs a simple join and then dumps the results into a disk file. At the other end of the spectrum, an advanced query might refer to a patently complicated query, such as a long-running, CPU- and RAM-intensive, multimodule query boasting robust error-handling code to handle problems that develop while accessing multiple databases using one or more of a dozen subqueries that preselect data needing to be stored in temporary tables that are created and dropped as necessary using DDL queries that are executed by stored procedures, and which, finally, seven hours later, sends a concise, beautifully formatted two-page report to the CEO’s color printer. For this chapter’s purposes, advanced queries fall into three broadly defined categories. The first group relies on above average familiarity with SQL keywords and statements. Such queries seem advanced because they utilize standard but less familiar, less popular,
Advanced Queries CHAPTER 4
75
or less understood SQL language features. Examples include the aggregate functions discussed in the next section, parameterized queries, pass-through queries, and DDL (Data Definition Language) queries. In fact, the balance of this chapter largely focuses on queries falling into this first group. The second group of advanced queries exploits theory rather than mechanics. That is, they rely on a solid understanding of SQL design and relational database theory. You will see some of this information a few times before reaching the chapter’s end. Those of you who found the preceding section tedious, boring, or repetitive will find this section more rewarding. The third group of queries earning the advanced nom de plume demonstrate more or less intimate knowledge of the underlying operating system, the implementation of the database engine, nonstandard SQL extensions the engine supports, or some combination. This chapter ignores these types of advanced queries because they are almost always non-portable to other operating system platforms or other databases.
Mastering Totals Queries Totals queries summarize their underlying datasets, offering high level and less detailed information. Most select queries, on the other hand, present so much information that users cannot sort the wheat from the chaff. Table 4.2 lists the valid options used in Access 2002’s Totals row and the information they provide. TABLE 4.2
Options Available in the Totals Row
Description
Sum
Calculates the total of all values in fields meeting the selection criteria
Avg
Calculates the average value of all fields meeting the selection criteria
Min
Returns the lowest value of all fields meeting the selection criteria
Max
Returns the highest value of all fields meeting the selection criteria
Count
Returns the number of fields meeting the selection criteria
StDev
Calculates the standard deviation of all fields meeting the selection criteria
Var
Calculates the variance of all fields meeting the selection criteria
4 ADVANCED QUERIES
Option
76
Database Design Unleashed PART I TABLE 4.2
continued
Option
Description
Expression
Defines a valid custom expression applied to all fields meeting the selection criteria
First
Returns the first record in the group on which calculations are being performed
Last
Returns the last record in the group on which calculations are being performed
Group By
Specifies the fields on which to perform calculations
Where
Specifies the selection criteria for records not included in a calculation and which will not be shown in the query results
One key caveat regarding the aggregate functions (Sum, Avg, Min, Max, Count, StdDev, and Var) listed in Table 4.2 is that none of them count Null values in their calculations. If you want the aggregate functions to consider Null values, convert the Nulls to zeroes by running an update query. Alternatively, use an expression like the following. IIF(IsNull([fieldnamereference]),0,[ fieldnamereference])
This expression returns 0 to the caller (the aggregate function in this case) if, and only if, the field value is Null. The next few subsections illustrate how to create, execute, and interpret queries using many of the options available in the query grid’s Totals row. Unless stated otherwise, all queries use an unaltered copy of the Northwind sample database.
Counting Records With Count The Count function returns the number of fields in a query resultset meeting the value specified in the query selection criteria. For example, the query in Listing 4.6 counts how many orders each customer has placed. When creating and running an aggregate query, delete all unused objects from the query design grid, especially tables, fields, and other queries. The result of an aggregate function can easily be skewed by extraneous data, even data not used in the query. Figure 4.9 shows the query results.
Advanced Queries CHAPTER 4
77
FIGURE 4.9 Customer order count.
Notice that there is no need to state a sort order. Simple aggregate queries like this one sort themselves left to right using the Group By field(s) in the Totals row, unless otherwise specified. LISTING 4.6
The SQL Statement for the Query in Figure 4.9
SELECT Customers.CompanyName, Count(Orders.OrderID) AS CountOfOrderID FROM Customers INNER JOIN Orders ON Customers.CustomerID = Orders.CustomerID GROUP BY Customers.CompanyName;
Calculating Averages with Avg
FIGURE 4.10 Average aggregate query as seen from the query design window.
4 ADVANCED QUERIES
To see an average unit price by product category, create a query of only the Products table. Put the CategoryID and the UnitPrice fields into the query grid, make the query a totals query, and set the Totals option for the unit price field to Avg (average). Figure 4.10 shows the query results; Listing 4.7 contains the actual query text.
78
Database Design Unleashed PART I LISTING 4.7
The SQL Statement for the Query in Figure 4.10
SELECT Products.CategoryID, Avg(Products.UnitPrice) AS AvgOfUnitPrice FROM Products GROUP BY Products.CategoryID;
The Avg aggregate function operates on all the Number, Date/Time, Currency, and AutoNumber fields within a grouping, and yields the average for the values in that group.
Using Min and Max The Max and Min functions can be useful for identifying data such as each customer’s biggest and smallest orders (in monetary terms), the highest and lowest outstanding credit balances, or the most popular and least popular items ordered. In fact, you can even display the maximum and minimum values of any given field side-by-side simply by adding two copies of the field that interests you to the query grid, and selecting Min for one, and Max for the other.
Using First and Last The First and Last functions return the first and last items, respectively, presented to the query, sometimes producing surprising or unexpected results. Intuitively, First and Last seem comparable to Min and Max, but they are completely different. First and Last do not evaluate the data they see, but simply retrieve the specified record. Min and Max do evaluate and compare the data they see. The implication is that First and Last should be used cautiously, preferably against presorted data in a known state. It should be clear that using First or Last against unsorted data, or data sorted in a way unrelated to your desires, will yield arbitrary results. First and Last operate based on data’s order of presentation, not its content.
Validating Data With StDev and Var The standard deviation (StDev) and variance (Var) functions allow you to validate your data. Before using them, though, you might want to know what they are. Briefly, StDev and Var are statistical functions measuring data dispersion, or how far the individual data points in a set are from a value derived from all items of the set considered collectively. That is, they provide rough estimations of how well your data represents the entity it describes.
Advanced Queries CHAPTER 4
79
Note Statistical analysis is far more sophisticated and complex than this section suggests. To learn more about it, refer to a statistics textbook.
Variance expresses the average distance (actually, the average squared distance) of each individual data point from the mean of the entire set. In practical terms, standard deviation (technically, the positive square root of the variance) of a data population quantifies the data’s overall consistency and uniformity. The lower the standard deviation, the more uniform and consistent (closer to the mean) the data. What is the practical use of the Var and StDev functions in queries? They can tell you a lot about your data. Suppose you have two stores, NorthStore and SouthStore, identical in every respect except they are located on opposite sides of the city. Your first query uses the Sum function to compare sales, and you see that NorthStore’s mean sales are higher than SouthStore’s. The conclusion most would draw is that NorthStore is the better, more profitable store. However, a query using StDev returns a high standard deviation for NorthStore and a low one for SouthStore. How do you explain this result? One possibility is that SouthStore’s sales, although lower overall, might be concentrated in a particular price range or that SouthStore’s sales pattern seems to be based on many small sales. NorthStore’s high standard deviation might suggest few sales or sales varying widely in dollar value, either one of which might hint that NorthStore’s business base is less solid than SouthStore’s. Additional queries will make the result less ambiguous.
Creating Custom Aggregation Queries With Expression Expression allows you to present a calculation in your result, but that calculation must contain an aggregate function. Use this feature when you want to present the results of multiple functions in your query. For example, the query defined in Listing 4.8 contains a custom expression and returns the results illustrated in Figure 4.11.
4 ADVANCED QUERIES
Now that StDev’s and Var’s existence has been justified, creating a query using them is straightforward. Simply create a new query with the fields and grouping you want. Select the appropriate field and set its aggregate function to StDev or Var.
80
Database Design Unleashed PART I
FIGURE 4.11 A resultset created with a custom expression.
LISTING 4.8
The SQL Statement for the Query in Figure 4.11
SELECT Categories.CategoryName, Count(Products.ProductName) AS CountOfProductName, Sum([UnitPrice])*1.05 AS [ExpressionExample] FROM Categories INNER JOIN Products ON Categories.CategoryID = Products.CategoryID GROUP BY Categories.CategoryName;
The query in Listing 4.8 counts the number of products in each category, increases each category’s average price by 5 percent using the custom aggregate function Sum([UnitPrice])*1.05
and stores the results in a calculated field named ExpressionExample. To create a similar query of your own, set the Total property of the calculated field to and then write a formula that uses one of Access’s predefined aggregate functions. If your expression lacks one of the aggregate functions, you will receive an error message and the query will not run.
Expression
Understanding the Where Clause To apply selection criteria in an aggregate query, you can enter the criteria into the query grid directly, as previous examples have done, or you can select the Where clause on the Totals row. However, a selection criterion entered directly into the grid will not create the same query resultset if it specified using the Where option in the Totals row. In particular, • Selection criteria specified using the Where clause define the records to aggregate and are applied before any grouping. • Selection criteria specified without the Where clause (that is, entered directly into the query grid) affect are applied after grouping, and so affect the aggregated results.
Advanced Queries CHAPTER 4
81
• Selection criteria specified without the Where clause appear as elements of an SQL HAVING statement. The implications of these differences are subtle, but important. To include or exclude records from an aggregate query, use Where. Enter criteria without the Where clause, or use the SQL HAVING statement, to apply selection criteria against finished aggregation calculations. The examples shown in Figures 4.12–4.15 and their corresponding SQL statements (Listings 4.9 and 4.10, respectively) demonstrate the difference. Figure 4.12 shows a query design grid using only a Where clause, Listing 4.9 shows the corresponding SQL statement, and Figure 4.13 shows the query’s result. FIGURE 4.12 The Where clause selects records for aggregation.
This query shows unit sales by product category. The Where clause excludes orders shipped outside of the United States. Listing 4.9 shows the corresponding SQL statement. LISTING 4.9
SQL Statement for the Query in Figure 4.12
4 ADVANCED QUERIES
SELECT Categories.CategoryName, Count(Products.ProductName) AS CountOfProductName, Sum([Order Details].Quantity) AS SumOfQuantity FROM Categories INNER JOIN (Products INNER JOIN ((Customers INNER JOIN Orders ON Customers.CustomerID = Orders.CustomerID) INNER JOIN [Order Details] ON Orders.OrderID = [Order Details].OrderID) ON Products.ProductID = [Order Details].ProductID) ON Categories.CategoryID = Products.CategoryID WHERE (((Orders.ShipCountry)=”USA”)) GROUP BY Categories.CategoryName;
82
Database Design Unleashed PART I
The key detail to note in Listing 4.9 is that the WHERE phrase in Listing 4.9, which corresponds to the Where clause in Figure 4.12, is applied before the grouping specified in the GROUP BY phrase. Figure 4.13 shows the query result. FIGURE 4.13 Total U.S. unit product sales by category.
Suppose, however, that you only want to see the product categories that sold less than 1000 units. To do so, enter this criterion directly into the query grid or, if you are writing the SQL directly, use a HAVING statement. This second criterion will be applied after the aggregation and after grouping. Figure 4.14 shows the query grid for this query. Listing 4.10 shows the equivalent SQL. Figure 4.15 shows the query result. FIGURE 4.14 Selecting a subset of aggregated data.
Note that the criterion <1000 in Figure 4.14 does not use the Where option on the Totals row, so it applies only to quantities (Quantity) with sums (Sum) less than 1000. LISTING 4.10
SQL Combining WHERE and HAVING Statements
SELECT Categories.CategoryName, Count(Products.ProductName) AS CountOfProductName, Sum([Order Details].Quantity) AS SumOfQuantity FROM Categories INNER JOIN (Products INNER JOIN ((Customers
Advanced Queries CHAPTER 4 LISTING 4.10
83
continued
INNER JOIN Orders ON Customers.CustomerID = Orders.CustomerID) INNER JOIN [Order Details] ON Orders.OrderID = [Order Details].OrderID) ON Products.ProductID = [Order Details].ProductID) ON Categories.CategoryID = Products.CategoryID WHERE (((Orders.ShipCountry)=”USA”)) GROUP BY Categories.CategoryName HAVING (((Sum([Order Details].Quantity))<1000));
The only difference between Listings 4.9 and 4.10 is the extra line, HAVING It will be applied to the results of the aggregation operation after the grouping. Note how the HAVING statement follows the GROUP BY statement. This is a visual reminder that selection criteria applied without a Where clause are evaluated after grouping.
(((Sum([Order Details].Quantity))<1000)).
FIGURE 4.15 Total U.S. product sales less than 1000 by category.
Figure 4.15 shows the results of the modified query. It only shows the underperforming products. To reiterate the point made earlier, selection criteria in aggregate queries made with the Where option produce different results than those made without it.
Crosstab (short for crosstabulation) queries are closely related to aggregate queries, but offer more analytical capabilities than aggregate queries. Generally speaking, crosstab queries let you examine the results of aggregate queries using grouping levels to manipulate the aggregate results. You might have just said, “Huh?” In a typical select query, the query columns appear across the top of the resultset and individual records make up the resultset. The same is true of aggregate queries, but the resultset is made up of grouped summary values, each group level listed down the side of the result. A crosstab query allows you to distribute the summary values of one of the groups across the top of the resultset. The matrix
ADVANCED QUERIES
Mastering Crosstab Queries
4
84
Database Design Unleashed PART I
formed between the left column and the top of the resultset filled with calculations of your choice. The result looks very much like a pivot table. The simplest crosstab requires at least three fields: one for a row heading, one for a column heading, and one for a value. A crosstab query can use any resultset produced by a select query. To illustrate, create a crosstab of customer purchases by different categories. Create a new query and add the following tables: Customers, Orders, Order Details, Products, and Categories. Place the following fields on the query grid: CompanyName from the Customers table, CategoryName from the Categories table, and Quantity from the Order Details table. The query is still a select query until you choose Query, Crosstab Query from the menu. Doing so adds a new row to the query grid, Crosstab. This row allows you to designate which fields belong to which aspects of the crosstab. Set CompanyName as the Row Heading, which defines the records making up the resultset. Set CategoryName as the Column Heading, which defines the columns in the resultset. Set Quantity as the Value and change Group By to Sum, which defines the values that will fill the matrix. Figure 4.16 shows what the query grid should look like. Listing 4.11 shows the associated SQL. When this query runs, Access automatically creates a sum for each intersection of customer and product (see Figure 4.17). FIGURE 4.16 A crosstab query in the query design grid.
LISTING 4.11
The SQL Statement for the Query in Figure 4.16
TRANSFORM Sum([Order Details].Quantity) AS SumOfQuantity SELECT Customers.CompanyName FROM Categories INNER JOIN (Products INNER JOIN ((Customers INNER JOIN Orders
Advanced Queries CHAPTER 4 LISTING 4.11
85
continued
ON Customers.CustomerID = Orders.CustomerID) INNER JOIN [Order Details] ON Orders.OrderID = [Order Details].OrderID) ON Products.ProductID = [Order Details].ProductID) ON Categories.CategoryID = Products.CategoryID GROUP BY Customers.CompanyName PIVOT Categories.CategoryName;
The TRANSFORM and PIVOT statements are the key elements for creating a crosstab query. The result, as you can see in Figure 4.17, shows the distribution of products each company has purchased, broken down by category. FIGURE 4.17 Each company’s total product purchases by category.
The query result in Figure 4.17 makes it easy to see how many products in each category each company has purchased, which provides more information than a simple aggregate query showing each company’s total product purchases regardless of category.
You can also use custom calculations for the Value criteria. For example, change the Quantity field’s Total property to Expression and use the following expression: Expr1:IIf(Sum([Quantity])>=50,”High”,”Low”)
This code uses an aggregate function to change the display of the value in a crosstab query. When you run the crosstab, the result of the IIf() statement appears in the matrix. The expressions you create in a crosstab must be compatible with expressions you would write for any other aggregate query.
4 ADVANCED QUERIES
Access crosstab queries might have more than one field as a Row Heading, but only one field can be defined as a Column Heading or a Value. Multiple Row Headings create a hierarchical view of your data with increasing detail as you read from left to right. To see this, add Country and Region to the previous query and set them as Row Headings.
86
Database Design Unleashed PART I
Just as crosstab queries can present the result of a formula as its value, they can also use custom expressions as row or column headings. The following query (see Figures 4.18 and 4.19 and the underlying SQL in Listing 4.12) uses order dates broken into quarters for the column headings. The PIVOT phrase contains the custom expression, which is: “Q” & CStr(DatePart(“Q”,[OrderDate]))
FIGURE 4.18 Designing a crosstab query with a custom column heading.
FIGURE 4.19 The resultset created by Figure 4.18’s query.
LISTING 4.12
The SQL Statement for the Query in Figures 4.18 and 4.19
TRANSFORM Sum([Order Details].Quantity) AS SumOfQuantity SELECT Customers.CompanyName FROM (Categories INNER JOIN Products ON Categories.CategoryID = Products.CategoryID) INNER JOIN ((Customers INNER JOIN Orders ON Customers.CustomerID = Orders.CustomerID) INNER JOIN [Order Details] ON Orders.OrderID = [Order Details].OrderID)
Advanced Queries CHAPTER 4 LISTING 4.12
87
continued
ON Products.ProductID = [Order Details].ProductID WHERE (((Orders.OrderDate) Between #1/1/1998# And #6/30/1998#)) GROUP BY Customers.CompanyName PIVOT “Q” & CStr(DatePart(“q”,[OrderDate]));
In order for a crosstab query to show changes in the underlying data, it must be closed and reopened because it is not a restartable query.
Mastering Parameter Queries Parameter queries are queries that accept user input to define their selection query. Any query can request information before it runs. Before a parameter query executes, it prompts the user for some piece of information. This section shows you how to create parameter queries (sometimes called parameterized queries) using the query design window and in code. You will also learn how to execute parameter queries from code and how to use parameter collections.
Creating Parameter Queries in the Query Design Window Creating a parameterized query in the query design window is a relatively simple, twostep process. First, select Query, Parameters from the menu and use the resulting dialog box to define the parameters you want. Although it is possible to create parameter queries without using the dialog box, the dialog box allows you to control both the order in which parameters will be requested and their data type.
To see the process in action, use the following steps. 1. Start a new query. 2. Add the Customers, Orders, Order Details, and Products tables. 3. Place the following fields on the query grid: CustomerID and CompanyName from the Customers table; OrderID and OrderDate from the Orders table; ProductName from the Products table; and UnitPrice, Quantity, and Discount from the Order Details table.
4 ADVANCED QUERIES
After defining parameters in the dialog box, place them in the query grid in the appropriate places. Parameters in the query grid must exactly match the parameter in the dialog box. If the parameter exists only in the dialog box, the query will prompt the user for information, but it will not know how to apply it to the query.
88
Database Design Unleashed PART I
4. Sort the query by OrderDate in descending order and by ProductName in ascending order. 5. Select Query, Parameters from the menu bar. 6. Enter the first parameter as Customer
ID
with a data type of text.
7. On the first line of the criteria section for the CustomerID field, enter [Customer ID]. This tells the query that it will accept a text parameter called Customer ID and apply it as a criterion against the CustomerID field in the query. Figure 4.20 illustrates the parameter query in design mode. Its associated SQL statement is shown in Listing 4.13. FIGURE 4.20 Designing a parameterized query.
Note the simple dialog box for adding parameters. You can use the dropdown box to select the data type. LISTING 4.13
The SQL Statement for the Parameter Query in Figure 4.20
PARAMETERS [Customer ID] Text; SELECT Customers.CustomerID, Customers.CompanyName, Orders.OrderID, Orders.OrderDate, Products.ProductName, [Order Details].UnitPrice, [Order Details].Quantity, [Order Details].Discount
Advanced Queries CHAPTER 4 LISTING 4.13
89
continued
FROM Products INNER JOIN ((Customers INNER JOIN Orders ON Customers.CustomerID = Orders.CustomerID) INNER JOIN [Order Details] ON Orders.OrderID = [Order Details].OrderID) ON Products.ProductID = [Order Details].ProductID WHERE (((Customers.CustomerID)=[Customer ID])) ORDER BY Orders.OrderDate DESC, Products.ProductName;
The PARAMETERS statement at the top of Listing 4.13 is the SQL statement telling Access’ query engine to prompt the user for a parameter. The parameter can also be a phrase up to 255 characters in length. This allows you to ask your users for criteria in a way they might better understand, or in a way they might simply find polite. Execute the query and enter Quick in response to the parameter prompt. The resultset lists all records with a CustomerID of Quick.
Using Parameterized Queries in Code Parameter queries can run in your application in another way—through code. The parameters make up a collection in a query object executed using VBA code. This method offers at least two advantages. First, you can collect all the parameters from a form, which lets you test the data’s type and validity before submitting them to the query. The second advantage is that the user can review and modify the data entered before executing the query. Normal execution of a parameter query makes this impossible, because once data is entered in response to a prompt, the only options are to continue or to cancel the query.
LISTING 4.14
A Function to Execute a Parameter Query from Code
Function RunParamQuery(QryName As String, CustID As String) ‘This function will run a parameterized query that ‘takes the customer’s ID number as an argument ‘Arguments: ‘ QryName - Name of the parameterized query object ‘ CustID - String identifying the customer
ADVANCED QUERIES
Listing 4.14 demonstrates executing a parameterized query from code. The function RunParamQuery() takes a query name and a customer ID as arguments, and then uses those two arguments to open the named query and count its records. The return value is the number of records in the recordset. You can execute this by running the function from the debug window or from an event on a form.
4
90
Database Design Unleashed PART I LISTING 4.14
continued
‘From “Microsoft Access 2002 Development Unleashed” (SAMS) ‘By:Forte, Howe, Ralston Dim db As Database Dim qrydef As QueryDef Dim rs As Recordset Set db = CurrentDb() Set qrydef = db.QueryDefs(QryName) ‘Assign the parameter by name qrydef(“Customer ID”) = CustID Set rs = qrydef.OpenRecordset() ‘Execute the parameterized query RunParamQuery = rs.RecordCount rs.Close End Function
Executing a Query Using a Parameter Collection Listing 4.15 shows the code for a function named OpenParamQuery(). It takes advantage of the parameter collection in queries. A query’s parameter collection is simply the set of all the parameters passed to the query. By using the ParamArray keyword in the function’s arguments, you can use the function in different parameter queries regardless of how many parameters they might require. Note If you parameterize a nested query, there is still only one parameter collection.
The function loops through the ParamArgs() array and assigns the parameters in the order they were given. To use this, execute it from the Debug window. The result of the function is a count of records. LISTING 4.15 Parameters
A Function for Running Parameter Queries with a Varying Number of
Function OpenParamQuery(QryName, _ ParamArray ParamArgs() As Variant) As Long ‘From “Microsoft Access 2000 Development Unleashed” (SAMS) ‘By:Forte, Howe, Ralston
Advanced Queries CHAPTER 4 LISTING 4.15
continued
‘Arguments ‘ QryName - Name of the ‘ ParamArgs - A varying ‘ parameters of the ‘ in the same order ‘ them. Dim Dim Dim Dim Dim
91
parameterized query to run list of values to plug into the query. They must be submitted that the query expects to find
db As Database qry As QueryDef i As Integer rs As Recordset rscount As Long
On Error GoTo OpenParamQuery_Error Set db = CurrentDb() Set qry = db.QueryDefs(QryName) ‘Move through all the supplied parameters and assign them by index For i = 0 To UBound(ParamArgs()) qry.Parameters(i) = ParamArgs(i) Next Set rs = qry.OpenRecordset(dbOpenSnapshot) OpenParamQuery = rs.RecordCount OpenParamQuery_Exit: Set qry = Nothing rs.Close Exit Function
End Function
Mastering Pass-Through Queries A pass-through query is a query that does not execute itself, but instead passes to another database for execution. Although Access is capable of linking tables from other data sources and querying them as if they were native data tables, it is also capable of using pass-through queries so it only handles the returned resultset.
4 ADVANCED QUERIES
OpenParamQuery_Error: OpenParamQuery = 0 GoTo OpenParamQuery_Exit
92
Database Design Unleashed PART I
The main reasons to use pass-through queries are to increase overall performance and reduce network load. When you use Access to attach and query tables from a client/server database, such as SQL Server or Oracle, the server has no idea what you want from it, and usually does not understand Access’ SQL dialect. As a result, the server sends mounds of data back to Access, forcing Jet to sort it all out. On large databases, this taxes Jet, the client system, and the network. Nor is it productive use of the server. Pass-through queries meet the server halfway. A pass-through query is what Microsoft’s documentation refers to as a SQL-specific query, meaning you must write it in SQL and cannot use the query design window. Moreover, you have to write in the SQL dialect of your server and you cannot take advantage of many Access features, such as custom functions. Hopefully, the increased speed and decreased network traffic load will offset these disadvantages. To create a pass-through query, write it as you would any other query, but do not add tables to it. Next, select Query, SQL Specific, Pass Through. This changes the Query view to the SQL window. There are only two properties important to running a passthrough Query: the SQL statement itself and the connection string, which contains the information your query needs to connect and authenticate to the destination server. A typical connection string might resemble the following: ODBC; DRIVER=SQL SERVER; SERVER=Access2000UnleashedServer; UID=sa; DATABASE=PUBS; TRUSTED_CONNECTION=YES ODBC (Open Database Connectivity) prefixes the connection string. It almost always prefixes connection strings to remote SQL Server, Oracle, Informix, and Sybase databases. DRIVER, SQL SERVER in this case, specifies the installed ODBC driver to use. Each ODBC data source uses a driver to interpret ODBC instructions. The name usually resembles the name of the server software. The SERVER line is the hostname on which the database resides. UID (User ID) tells the remote database server who you are. The password can also be stored in the connection string, but doing so is not advisable for security reasons. Because a database server can run many databases, the DATABASE clause names the database on which to execute the query. The TRUSTED CONNECTION entry allows you to access the server provided you have a permission profile that the SERVER trusts.
Advanced Queries CHAPTER 4
93
Note If you are not sure how the connection string should read, contact the database administrator or copy the connection string out of an attached table.
After setting the connection string, enter the SQL statement using the syntax appropriate to the server you are querying. For example, the following short query is a simple SQL statement to Microsoft SQL Server. Select * from Authors Where State =’CA’
Only the resultset comes over the network because the server did all the work. To further reduce network traffic, you could create stored procedures on the server. Stored procedures can run from a pass-through if they are called by name and passed any parameters they require. This approach lets the server use its own optimization abilities and execution plans to provide still better performance.
Mastering Data Definition Queries The final topic falling under the rubric “advanced queries” are data definition queries. Data definition queries are queries that create and manipulate database structures (tables, queries, indexes, and so on). Access can create, alter, and delete tables and other database objects. Using these capabilities can give your applications the ability to work intelligently with data and professional polish.
Caution Data definition queries permanently alter the number, structures, and properties of your tables, indexes, and relationships. Before working with them, back up your work and debug them in a copy of your project.
4 ADVANCED QUERIES
These data definition queries can operate against Jet tables, but not against non-Jet tables. If you need to perform data definition functions on non-Jet tables, DAO might work. If you need to perform data definition functions against SQL Server tables or Oracle tables, you can take advantage of similar capabilities in their SQL languages using pass-through queries.
94
Database Design Unleashed PART I
Data definition queries look unlike any of the queries you have seen so far in this chapter. They start with a verb (CREATE, ALTER, or DROP) specifying that action to perform, followed by the name of the table on which to act. The next section, inside parentheses, defines the fields. Each field definition consists of a field name, its data type, and the field size (in parentheses). The field definition section can be as long as is needed. After any particular field definition, an optional constraint clause can set indexes, keys, or foreign keys, or require an entry using the NOT NULL statement.
Creating a New Table A logical starting place for data definition queries is the CREATE TABLE statement. Although you can create a table with a query using Access’s Make Table functionality, such a query cannot define field sizes, field constraints, indexes, or relationships. Data definition statements do not have these shortcomings. You can create or alter a table as if you had gone into the Design view of the table object and made the alterations. The syntax for a simple CREATE
TABLE
statement is as follows:
CREATE TABLE tablename (field1 datatype(size),field2 datatype(size),...);
Note Tables must be closed when the data definition queries are run against them.
The following query creates a table named TestTable with two text fields each 15 characters in length: CREATE TABLE TestTable ( FirstName TEXT(15), LastName TEXT(15) );
After executing this query, refresh the database container and you should see the new table. Examine the new table in Design view to verify that the fields’ lengths are 15 characters. If you had used an Access Make Table query to create this table, the fields would have been 255 characters in length. Although the size specification is optional, use it whenever possible.
Advanced Queries CHAPTER 4
95
Defining Field Properties The constraints clause allows you to define other field properties. These properties fall into two categories: keys and relationships. The constraints clause appears in the field section of the data definition statement. There is no punctuation in the clause, so only the order matters. When defining keys, the syntax is as follows: CONSTRAINT constraintname PRIMARY KEY/UNIQUE/NOT NULL
When defining relationships for a table or field, the syntax varies slightly: CONSTRAINT relationshipname REFERENCES othertablename(relatedfieldname)
The relationships established using the CONSTRAINT clause must be between fields of the same or compatible data types. The data definition statement in Listing 4.16 creates a table in the Northwind database. The table is named TestTable and it has four fields. The first field is EmployeeID. EmployeeID’s data type is Long and it is defined as the table’s primary key. The second CONSTRAINT statement establishes the relationship between TestTable and Employees through the EmployeeID field they both share. The other three fields are text fields 30, 30, and 10 characters long, named FirstName, LastName, and Phone fields, respectively. Be sure to run this query in the Northwind database or it will fail. In addition, delete the TestTable created in the previous example, if it exists, before executing this query. LISTING 4.16
Using Constraints When Creating Fields
After executing the data definition query, open the Relationships window and add the TestTable to it. Access recognizes the relationship between Employees and TestTable automatically, as you can see in Figure 4.21.
4 ADVANCED QUERIES
CREATE TABLE TestTable ( EmployeeID LONG CONSTRAINT myKey PRIMARY KEY CONSTRAINT myRef REFERENCES Employees(EmployeeID), FirstName TEXT(30), LastName TEXT(30), Phone TEXT(10) );
96
Database Design Unleashed PART I
FIGURE 4.21 Access recognizes the relationship defined in Listing 4.16.
Altering a Table It is possible to alter existing tables using data definition queries. The following ALTER statement will add a field to the table. The basic ALTER TABLE statement has the following syntax:
TABLE
ALTER TABLE tablename ADD fieldname1 datatype(size), fieldname2 datatype(size);
To change your table by adding two new fields, execute the following query: ALTER TABLE TestTable ADD Fax TEXT (10), Cellular TEXT (10);
The fields created could have been defined further using constraints clauses. To drop a field, replace ADD with DROP and place the name of the field to drop after the DROP keyword. For example, the following SQL statement deletes the Phone field from TestTable: ALTER TABLE TestTable DROP Phone;
To drop multiple fields, separate the field names using commas: ALTER TABLE TestTable DROP Fax, Cellular;
Creating an Index As you might expect, DDL also supports creation and deletion of indexes. To create an index, use CREATE INDEX. Its syntax is: CREATE [UNIQUE] INDEX indexname ON tablename (fieldname1 ASC/DESC, fieldname2 ASC/DESC...) [WITH PRIMARY/DISALLOW NULL/IGNORE NULL]
Advanced Queries CHAPTER 4
97
If the index should contain only unique values, use the UNIQUE reserved word. PRIMARY is a synonym for UNIQUE. The optional WITH clause allows you to specify validation rules. Use DISALLOW NULL to prohibit Null values. IGNORE NULL allows records with Null values in the indexed field, but excludes them from the index. The following statement creates an index named idxLastName on the LastName field that does not permit Null values: CREATE INDEX LastName ON TestTable (LastName) WITH DISALLOW NULL;
Notice that the syntax is slightly different for CREATE INDEX in that the index name precedes the table name. Check the table design of the table to confirm that the index was created. Tip Indexes are possible on tables linked to an ODBC data source if that source does not already have an index. In this case, the index resides in Access, not on the server, of data fields. The server is unaware of these pseudo-indexes and you do not need special permissions to create them. To make them, you use the same SQL syntax you would for a native Jet table. Use pseudo-indexes when the ODBC source does not have its own index and the users need to update the data.
Removing a Table To remove a table from a database, or to remove an index from a table, use DROP or DROP INDEX, respectively.
TABLE
DROP INDEXindexname ON tablename]
The following statement will remove TestTable, p, from the Northwind database: DROP TABLE TestTable;
Summary Access 2002 delivers even more powerful query abilities than previous versions, and, in most cases, makes taking advantage of these features easier than ever. This chapter reviewed using the query design window, then covered advanced query topics, including
ADVANCED QUERIES
DROP TABLE tablename/
4
98
Database Design Unleashed PART I
the fine points of aggregation queries, how to create crosstab queries, using parameter queries to give users greater flexibility, using pass-through queries to access the capabilities of remote database servers, and using data definition queries to manipulate database structure. By studying the query techniques discussed in this chapter, developers can harness the power of queries to make their databases more useful than ever.
CHAPTER 5
The Microsoft Jet Database Engine
IN THIS CHAPTER • The History of Microsoft Jet • Using Jet 4.0 Features in Your Applications 103
100
100
Database Design Unleashed PART I
Microsoft Access 2002 is a sophisticated front end to the Microsoft Jet Database Engine 4.0. Whether you know it or not, Jet handles your entire database needs in the MDB file. When you are accessing a MDB file via DAO or ADO, you are using Microsoft Jet. Jet stores your data tables, indices, and queries, and it runs all your queries via its query engine. Jet is a very powerful, fully functional, multithreaded relational database engine. This chapter examines Jet’s development and then shows you how to take advantage of Jet features in your applications.
The History of Microsoft Jet Today, Jet is the database engine in over 30 Microsoft products besides Access, including Project, Money, Team Manager, and even educational children’s games like Computer Tutor. Jet has gradually come to dominate the desktop database market because each release strengthens existing features and provides innovative new technology. A short review of Jet’s history might prove instructive, or at least interesting. It will certainly show how Jet’s evolution has enabled Access to become the desktop database powerhouse it is today.
Jet 1.0 Jet’s origins go back over ten years, starting with the Access project’s creation at Microsoft. Jet 1.0 entered the desktop database market when Access 1.0 shipped in 1992. Jet 1.0 delivered many of the features expected of a desktop database as that time, such as data definition, querying, security, and indexing. However, Jet also pioneered many of the features people expect of desktop database engines today, for example, updatable queries, heterogeneous data joins, and the capability to write a query based on another query. These new features, and the continuing evolution of the Jet engine and the featurerich Microsoft Access interface on top of it, eventually resulted in Jet becoming the most popular desktop database engine around.
Jet 1.1 The success of Microsoft Access took everyone by surprise, even Microsoft. In Might 1993, Microsoft released Access 1.1 and Visual Basic 3.0, each of which came with Jet 1.1. This release of Jet gave developers many new features like improved ODBC connectivity and new ODBC drivers. Gone were the days of coding directly to the ODBC API, and accessing ODBC data became something that everyone could do. Jet 1.1 also allowed users to easily attach (link, back then!) to external data, especially the newly acquired Microsoft FoxPro data format. DAO DDLs were improved, and Jet’s maximum database size was increased from 128MB to 1.1GB.
The Microsoft Jet Database Engine CHAPTER 5
101
Jet 2.0 Jet 2.0 shipped with the very popular version 2.0 of Microsoft Access in April 1994. 2.0 marked Jet’s emergence as a modern database engine, including features such as enginelevel enforcement of validation rules and referential integrity. The Rushmore query technology, borrowed from FoxPro, was added to Jet to increase performance. Jet SQL and DAO were also beefed up. It was also more ANSI-compliant than prior versions of Jet.
Jet 2.5 In October 1994, Microsoft released the Microsoft Access 2.0 service pack and the ODBC Desktop Drivers Pack 2.0. Jet 2.5 was born. Jet 2.5 now used VBA as its expression service, greatly improved its support for ODBC data sources, and featured smoother, more robust handling of multiuser applications.
Jet 3.0 Jet entered the 32-bit age in version 3.0, with the release of Access 95 in late 1995. In addition to 32-bit support, which was not fully completed, Jet also supported database replication and more enhanced ODBC and DAO features. Due largely to its 32-bit support and continuing improvements in Rushmore query technology, Jet 3.0 was an extremely fast database engine.
Jet 3.5 Office 97, released in January 1997, introduced the world to Jet 3.5. Jet 3.5 completed the work of converting Jet to a 32-bit engine. Performance was 3.5’s most significant enhancement. Additional features of the 3.5 engine included new data-caching capabilities, improved page locking, query enhancements, ODBCDirect, and the programmatic purging of write commands to disk. Replication was extended to include partial replicas, and external data support increased with support for HTML and Exchange data.
Jet 3.51 5 THE MICROSOFT JET DATABASE ENGINE
A very much overlooked service pack release of Jet 3.5, Jet 3.51, was released in mid1997 on the Web. Jet 3.51 included a new way to compact an MDB file, “Enhanced Compact.” 3.51 rolled database repair into the greatly improved compact process and shipped with the JetCOMP.exe utility for compact/repair using the new enhanced compact feature. 3.51 also fixed some low-level bugs that emerged in multiuser environments.
102
Database Design Unleashed PART I
Jet 4.0 Other than its original release, Jet 4.0 was the most significant Jet release to date. Jet 4.0, released in June 1999 with Office 2000, was a developer’s release, offering more developer-related features included than all prior versions of the product combined! Most of these features came directly from developer requests compiled over the years. 4.0 included some incredible features: • A new native OLE DB provider • Row-level locking • Full Unicode support • Enhanced data types • Enhanced AutoNumber capabilities • Searchable memo fields • Multiuser improvements • Replication enhancements • New SQL grammar • Better ANSI-92 SQL compliance Two years later, many Access developers find it hard to remember what life was like before Jet 4.0!
Future Versions of Microsoft Jet In early 1998, there were some rumors that Microsoft Jet was entering its final phases and would soon be replaced by the MSDE that powers SQL Server. Microsoft did supply a “desktop” version of SQL Server 7.0 with Office 2000 and Access 2000 included a project type that did not use Jet (ADPs—see Chapter 15, “Introducing Access Data Projects and the Visual Tools”). ADO 2.0 and Universal Data Access emphasize that OLE DB is the data access method of choice for client/server data. Because Microsoft wanted to take advantage of OLE DB for client/server data in Access 2000, people surmised that Jet was dead. Note For more on OLE DB and ADO, see Chapter 6, “Introduction to ActiveX Data Objects,” and Chapter 7, “Advanced ADO.”
The Microsoft Jet Database Engine CHAPTER 5
103
To paraphrase Mark Twain, rumors of Jet’s death were greatly exaggerated. At Tech*Ed and other conferences, Microsoft responded to the rumors and speculation, and made it very clear that Jet is still, and will continue to be, strongly supported.
Using Jet 4.0 Features in Your Applications The remainder of this chapter covers the advanced features of Jet 4.0 and offers suggestions for utilizing these features in your own projects. The code examples will work fine in Access 2002 and, with slight modification, in Visual Basic 5 and 6.
Native OLE DB Provider As you might know, Microsoft’s data access strategy now revolves around ActiveX Data Objects, known more commonly as ADO. ADO implements universal data access that use native providers to communicate with data sources. ADO 1.0 shipped with a generic provider for ODBC, so if you used Jet with ADO, you had to go though the ODBC layer, resulting in performance comparable to walking through mud. Jet 4.0 ships with a native OLE DB provider codenamed JOLT 4.0. This enables you to use ADO as your data access methodology with Jet. All Jet’s functionality is exposed through JOLT, including some features that will only be available with JOLT. You will see more on JOLT throughout this book.
Row Level Locking Jet 4.0 supports row level locking, which means you can increase concurrency in your application by locking a row at a time instead of a page (currently 4KB) at a time. The impact of this is that multiuser applications are less subject to data contention. Row level locking can dramatically increase the performance of your high-volume, highly transactional database applications. Some tests have shown that row level locking allowed six times the throughput as page locking. However, row level locking is supported only in ADO, not DAO. The net benefit of row level locking is that page-locking conflicts will become a thing of the past. For more on row level locking, see Chapter 21, “Multiple Users and Database Locking.”
Jet 4.0 stores all character data—for example, Access’s Text and Memo fields—in Unicode. This enables you to switch the language/character set of your application with the greatest of ease. Now when you convert to other languages/alphabets, you will have complete data fidelity after conversion (at least in theory).
THE MICROSOFT JET DATABASE ENGINE
Full Unicode Support
5
104
Database Design Unleashed PART I
What Is Unicode? Unicode is an attempt to create a single, comprehensive standard for encoding a language’s character set. Most Western alphabets (English, German, Italian, Spanish, and so forth) can be completely expressed using 1 byte (8 bits), which allows 255 possible characters. Other languages, especially those with written forms based on ideograms, such as Japanese, Korean, and Chinese, have far more than 256 unique characters, so a single byte encoding scheme is insufficient. Over the years, many different encoding schemes have been created, but no single scheme incorporating all or most languages was created. Approximately ten years ago, Apple and Xerox got together and started creating a comprehensive character set standard which came to be called Unicode. In 1991, Apple, Xerox, and others founded the Unicode Consortium. Its membership now includes such companies as Microsoft, Apple, AT&T, Compaq, Ecological Linguistics, HewlettPackard, IBM, Lotus, Novell, Reuters, and many others. In the early 1990s, the International Standards Organizations (ISO) started working on a similar standard in conjunction with the Unicode Consortium. Unicode 1.1 and ISO 10646, both published in 1993, are identical code-for-code. Unicode uses 2 bytes (16 bits) to represent the characters from all languages except Chinese. A 16-bit method allows for 65535 unique characters and more comprehensively addresses the challenges of expressing many alphabets using a single standard. It also makes it possible to mix and share data between multiple languages without corruption or data loss. Tip In the localization and internationalization fields, 2-byte encoding schemes are often called double-byte encoding. Similarly, the 1-byte approach is referred to as single-byte encoding.
NOTE For more on Unicode, see The Unicode Standard, Second Edition, ISBN 0-20148348-9, from Addison-Wesley. This almost 1,000-page book includes the complete Unicode 2.0 specification.
The Microsoft Jet Database Engine CHAPTER 5
105
Unicode Support in Jet 4.0 Because Unicode stores data in larger data pages, databases with a lot of character data increase in size. To accommodate Unicode in Jet 4.0, the data page size was increased to 4KB. The larger size increases the maximum size of an MDB from 1.07GB to 2.14GB. Moreover, Jet 4.0 provides Unicode Compression.The Unicode Compression option is available from the Access Table Designer, as shown in Figure 5.1. Note By default, index compression is turned on, so if you are converting an application from an older Access file format, all character data types will have Unicode compression turned on. However, if the database is already in a Jet 4.0 file format, the property must be passed to enable Unicode Compression. Unicode compression is not applied to Memo fields unless they require 4KB or less.
FIGURE 5.1 The Access Table Designer with Unicode Compression.
To define a column that will use compression using SQL, use the new WITH COMPRESSION flag when creating a table with DDL: CREATE TABLE MyTable (MyCompressedField CHARACTER(255) WITH COMPRESSION)
5 THE MICROSOFT JET DATABASE ENGINE
This SQL code is only available via VBA Code and ADO. You can execute the above SQL Statement against the current ADO connection of the VBA project as shown in Listing 5.1.
106
Database Design Unleashed PART I LISTING 5.1
Creating a Unicode Compressed Field in VBA
Private Sub cmdUnicode_Click() ‘This code will create a table called MyTable ‘and a Unicode Compressed Field called MyCompressedField ‘This code can only run via ADO in VBA ‘This is not supported in DAO ‘From “Microsoft Access 2000 Development Unleashed” (SAMS) ‘By: Forte, Howe, Ralston Dim strSQL As String On Error GoTo Proc_Err strSQL = “CREATE TABLE MyTable “ & _ “(MyCompressedField CHARACTER(255) WITH COMPRESSION)” ‘Execute the SQL Statement against the ‘current database connection ‘Similar to Currentdb.execute CurrentProject.Connection.Execute strSQL ‘Success MsgBox “Table Created OK”, vbInformation Proc_Exit: Exit Sub Proc_Err: ‘Determine if table exists If Err.Number = -2147217900 Then MsgBox “MyTable already exists, delete it and try again”, vbCritical Else MsgBox Err.Description, vbCritical End If Resume Proc_Exit End Sub
NT Compatible Sorting Implementing Unicode in Jet 4.0 allows Access 2002 developers to develop applications that work across more languages, Windows versions, and development and database applications. First, Unicode support enables Jet applications to work unmodified in more languages. Secondly, now that Jet supports Unicode, it uses the same sorting functionality across all major Microsoft operating systems (NT, 95, 98, and ME). Finally, because Microsoft SQL Server 7.0, SQL Server 2000, and Visual Basic 6 use the same sorting functionality, there now exists a great cross-product consistency.
The Microsoft Jet Database Engine CHAPTER 5
107
Jet Data Types Jet 4.0 data types integrate better with SQL Server. Interoperability with SQL Server makes it easier to upsize Jet databases to SQL Server databases and simpler to replicate Jet databases to SQL Server. Jet data type names are not always the same as in Access, but Access translates the names for you. Table 5.1 reviews the Microsoft Jet data types and the correspondence between Jet and Access data type names. TABLE 5.1
Overview of Jet 4.0 Data Types
Jet Data Type
Access Name
Notes
Character
Text
Maximum length remains 255 characters. Unicode support now makes this maximum length viable for all languages. Supported synonyms are Char, Varchar, Character Varying, Nchar, National Character, National Char, Nvarchar, National Character Varying, and National Char Varying. The use of the Text keyword without an accompanying length specification has been changed. It is now a synonym for Memo. This better aligns the use of the Microsoft Jet Text keyword with its use in Microsoft SQL Server. You can continue to use the Text keyword with a length specification, for example, TEXT (100) to define a fixed length character data column. Examples to further illustrate the use of the Text data type keyword: is equivalent to and aligns with the SQL Server definition and syntax for TEXT. CREATE TABLE t1 (c1 TEXT) CREATE TABLE t1 (c1 MEMO)
is equivalent to CREATE TABLE t1 (c1 CHAR (100)) and will provide backward compatibility for most existing Microsoft Jet applications.
CREATE TABLE t1 (c1 TEXT (100))
LongText
Memo
Supported synonyms are Text, NText, Memo, LongChar, and Note.
5 THE MICROSOFT JET DATABASE ENGINE
Maximum length (in bytes) is now approximately 2.14GB. This would be approximately 1.07 billion characters.
108
Database Design Unleashed PART I TABLE 5.1
continued
Jet Data Type
Access Name
Notes
Binary
OLE Object
Maximum length remains 255 characters. Supported synonyms are Varbinary, Binary Varying, and Bit Varying.
LongBinary
OLE Object
Maximum length is now approximately 2.14GB.
DateTime
DateTime
The synonym Timestamp is no longer supported, as the corresponding SQL Server Timestamp does not correlate directly to the DateTime data type.
Single
Single
Supported synonyms are Real, Float4, and IEEESingle.
Double
Double
Supported synonyms are Float, Double and IEEEDouble.
Precision, Float8,
The synonym Numeric is no longer supported for the Double data type. The keyword Numeric is now used to define a column as an exact numeric data type corresponding to the SQL Server Decimal or Numeric data types. Byte
Byte
The synonym is Tinyint.
Integer
Integer
Supported synonyms are Smallint, Integer2, and Short.
LongInteger
LongInteger
Supported synonyms are Int, Integer, and Counter. The synonym AutoIncrement is no longer. See the section on Auto-Increment Columns for more information.
Currency
Currency
The synonym is Money. Data accessed via ODBC that is typed as SQL_DECIMAL or SQL_NUMERIC (for example, SQL Server Decimal or Numeric columns) is no longer mapped to Microsoft Jet Currency.
Boolean
Boolean
Supported synonyms are Bit, Logical, Logical1, and YesNo.
GUID
ReplicationID
The synonym is UniqueIdentifier.
The Microsoft Jet Database Engine CHAPTER 5 TABLE 5.1
109
continued
Jet Data Type
Access Name
Notes
Decimal
--
The Decimal data type is new for Microsoft Jet 4.0. It is an exact numeric data type that holds values from 1028–1 through –1028–1. You can define both precision (1–28) and scale (0–defined precision). The default precision and scale are 18 and 0, respectively. Supported synonyms are Dec, and Numeric. Data accessed via ODBC that is typed as or SQL_NUMERIC will now be mapped to Microsoft Jet Decimal, instead of Currency. Note that this data type is not supported via DAO. It is supported only in ADO. SQL_DECIMAL
Enhanced AutoNumber Capabilities Jet 4.0 gives you much more control over AutoNumber fields than earlier Jet versions. In particular, Jet 4.0 permits you to set an AutoNumber field’s starting value and increment interval. This functionality is only exposed via SQL DDL through ADO/JOLT. To take advantage of this capability, select Tools, Options, Tables/Queries from the menu bar: this opens the Tables/Queries tab in the Options settings. Then, select the database checkbox in the SQL Server Compatible Syntax (ANSI 92) area in the lower-right corner of the dialog box. Click OK and then restart Access to make Jet aware of the change. Now you can take advantage of the enhance AutoNumber capabilities. For example, to create a table called MyCoolCounter with an AutoNumber that starts at 1000 and increments by 100, use the following SQL syntax: CREATE TABLE MyCoolCounter (CoolCounter IDENTITY (1000, 100), myTextField CHAR)
In addition to being able to set the starting and increment values when you create the table, you can modify them at any time using the ALTER TABLE SQL statement. To change MyCoolCounter to use a new starting point of 5000 and increment by 10, use this syntax:
THE MICROSOFT JET DATABASE ENGINE
ALTER TABLE MyCoolCounter ALTER COLUMN CoolCounter IDENTITY (5000,10)
5
110
Database Design Unleashed PART I
You can always find the last inserted value by using the SELECT @@IDENTITY SQL statement. The behavior of compact will be modified for users that take advantage of increments that are in values other than one. If the increment is a value other than one, Jet’s compact will not reset the next value to the maximum value in the table. By default, as in the previous versions of Jet, users will not be able to edit the Counter datatypes. However, administrators will be able to grant security to users that will allow them to update the Counter datatype.
Searchable Memo Fields Jet 4.0, unlike previous Jet versions, supports searchable Memo fields. Specifically, Jet 4.0 will create indexes on columns with a Memo datatype, using up to the first 255 characters of data. When performing wildcard (*) searches, only the index is used. Although this performs well, it limits the search to just the first 255 characters of data. The implication of this limitation is simply not to search memo fields if possible matching data might exist after the 255th character.
Connection Control/Passive Shutdown Jet 4.0 includes two helpful multiuser features: User List and Connection Control. User List uses ADO to enumerate all the users currently using the database, just as the LDBView tool did. Connection Control enables you to limit access to a database. Although you cannot remove a current user, you can prevent new users from entering the database. Using connection control and the user list functionality enables you to shut down the database and then, when all other users are out, reopen the database exclusively.
New SQL Grammar Jet’s SQL interpreter supports new functionality and conforms more closely to ANSI-92 SQL. An added benefit is that most of the SQL extensions make it easier to write SQL Statements that interoperate between Jet and SQL Server. The improved SQL grammar includes support for • Security • Definition of views and procedures • Parameter passing • Transactions • Stronger table DDL
The Microsoft Jet Database Engine CHAPTER 5
111
Security One benefit of Jet’s enhanced SQL syntax is improved database security. The net effect is easier programmatic security maintenance: you can use SQL, instead of using DAO or ADO, to address database and application security needs. The following SQL statements show the security-related SQL grammar Jet 4.0 supports for users and groups. • CREATE/ADD/ALTER/DROP USER • CREATE/ADD/ALTER/DROP GROUP • GRANT/REVOKE Security can be applied to the following objects: • CONTAINER • INDEX • QUERY • TABLE The code in Listing 5.2 shows how to create a group called SuperGroup with full permissions on the tblCustomers table. Next, it revokes SuperGroup’s delete permission on tblCustomers. Finally, after adding a user named Steve with a password of Batman, it adds Steve to the SuperGroup group. LISTING 5.2
Using Security with Jet 4.0
Private Sub cmdSecurity_Click() ‘This procedure will open an MDB file with ‘a security file specified and add users and groups ‘This code can only run via ADO in VBA ‘This is not supported in DAO ‘From “Microsoft Access 2000 Development Unleashed” (SAMS) ‘By: Forte, Howe, Ralston Dim conn As ADODB.Connection On Error GoTo Proc_Err Set conn = New ADODB.Connection
5 THE MICROSOFT JET DATABASE ENGINE
‘Set up a connection to the database ‘using ADO and specifying the System database in the ‘connection string With conn .Provider = “Microsoft.Jet.OLEDB.4.0” .ConnectionString = “data source=c:\employees.mdb” & _ “;Jet OLEDB:System database=” & _
112
Database Design Unleashed PART I LISTING 5.2
continued
“c:\program files\microsoft office\office\system.mdw” .Open End With ‘Execute the SQL Statements conn.Execute “CREATE GROUP SuperGroup” conn.Execute “GRANT SELECT, DELETE, INSERT, “ & _ “UPDATE ON tblCustomers TO SuperGroup” conn.Execute “REVOKE DELETE ON tblCustomers From SuperGroup” conn.Execute “CREATE USER Steve Batman” conn.Execute “ADD USER Steve to SuperGroup” Proc_Exit: Exit Sub Proc_Err: MsgBox Err.Description, vbCritical Resume Proc_Exit End Sub
Jet 4.0’s SQL grammar for security also supports creating or changing a database password using a statement like the following: ALTER DATABASE PASSWORD NewPass OldPass
Definition of Views and Procedures Jet 4.0 allows you to define a stored query as either a VIEW or a PROCEDURE. A view (VIEW) is a non-parameterized, row-returning query. A procedure (PROCEDURE) refers to non-DDL, non-UNION action and parameterized queries. You can create views and procedures via ADO or using the Jet 4.0 SQL statements CREATE VIEW and CREATE PROCEDURE. The new syntax is more compatible with ANSI-92 and makes Jet 4.0 views and procedures more portable to other ANSI-92 SQL databases like SQL Server. For example, the following SQL code creates a VIEW and a PROCEDURE: CREATE VIEW qryAllCustomers AS SELECT * FROM tblCustomers CREATE PROCEDURE qryAllCustomers_DEL AS DELETE *FROM tblCustomer
Parameter Passing Jet 4.0 from ADO now supports the capability to supply parameters in a call list, similar to executing a parameterized SQL Server stored procedure. The saved query shown in the following code fragment, qryParameterQuery, has two parameters: EmployeeID and DepID:
The Microsoft Jet Database Engine CHAPTER 5
113
PARAMETERS [EmployeeID] Long, [DepID] Long; SELECT Employees.EmployeeID, Employees.[First Name], Employees.[Last Name], Employees.Phone, Employees.[Dept ID] FROM Employees WHERE (((Employees.EmployeeID)=[EmployeeID]) AND ((Employees.[Dept ID])=[DepID]));”
Supplying the parameters and executing the parameterized query is now very easy with the EXEC syntax: EXEC qryParameterQuery 1, 4179
This SQL code supplies the values 1 and 4179 for the EmployeeId and the DepIDquery parameters. You must supply the parameters in the same order that is in your SQL Code. The code in Listing 5.3 shows how to open an ADO recordset based on the query qryParameterQuery. LISTING 5.3
Opening a Parameter Query in ADO
Private Sub cmdPramQuery_Click() ‘This procedure will open a parameter ‘query using the new EXEC syntax ‘This code can only run via ADO in VBA ‘This is not supported in DAO ‘From “Microsoft Access 2000 Development Unleashed” (SAMS) ‘By: Forte, Howe, Ralston Dim rst As ADODB.Recordset On Error GoTo Proc_Err Set rst = New ADODB.Recordset ‘Open the recordset based on the ‘executed parameter query rst.Open “Exec qryParameterQuery 1, 4179”, CurrentProject.Connection ‘Display the results MsgBox rst![First Name] Proc_Exit: Exit Sub
End Sub
5 THE MICROSOFT JET DATABASE ENGINE
Proc_Err: MsgBox Err.Description, vbCritical Resume Proc_Exit
114
Database Design Unleashed PART I
Transactions Jet 4.0 SQL now supports transactions. You must explicitly start a transaction with this SQL statement: BEGIN TRANSACTION
To commit a transaction, use the following: COMMIT
To roll a transaction back, you must use the following SQL statement: ROLLBACK TRANSACTION
The code in Listing 5.4 shows how to edit a record and delete records all in one transaction. Note that you have to start a transaction on a separate line from the one on which you execute the SQL statements. LISTING 5.4
Using Transactions in Jet 4.0 SQL
Sub Jet40Transaction() Dim conn As ADODB.Connection Set conn = New ADODB.Connection With conn .Provider = “Microsoft.Jet.OLEDB.4.0” .ConnectionString = “data source=” & Application.CurrentProject.Path ➥ & “\employee_2k.mdb” .Open End With conn.Execute “BEGIN TRANSACTION” conn.Execute “UPDATE Employees SET Employees.Phone = “ & _ Chr(39) & “2129560615” & Chr(39) & _ “WHERE (((Employees.EmployeeID)=1))” conn.Execute “DELETE” & vbNewLine & _ “From Tasks” & vbNewLine & _ “WHERE (((Tasks.[Emp ID])=1));” conn.Execute “COMMIT TRANSACTION”
End Sub
Stronger Table DDL In Microsoft Jet 4.0, CREATE TABLE is much more powerful. The most interesting feature of Jet 4.0 SQL Extensions is the new CHECK CONSTRAINTS option. You can use this feature
The Microsoft Jet Database Engine CHAPTER 5
115
to enforce business rules that span more than one table. That is, a SQL query can look up information in several tables and then use that information to enforce certain conditions on a newly inserted record. For example, suppose a database has a table named Customers and one named CreditLimit. Jet can enforce a business rule that newly inserted records in Customers must have a value less than the credit limit in CreditLimit. This constraint must be defined when the table is created. The syntax looks like the following: CHECK (<SQL Condition>)
specifies the constraint. The following code creates a table with a constraint on the CreditLimit field from the CreditLimit table:
SQL_Condition
CREATE TABLE Customers ( CustId IDENTITY (100, 10), CFrstNm VARCHAR(10), CLstNm VARCHAR(15), CustomerLimit DOUBLE, ➥CHECK (CustomerLimit <= (SELECT SUM (CreditLimit) FROM CreditLimit)));
The code in Listing 5.5 shows you how to create the CreditLimit table, how to insert a value into it, how to create the Customer table with the constraint on the CustomerLimit field, and then how to try to insert rows. LISTING 5.5
Using the Constraints
Private Sub cmdCreateConstraint_Click() ‘This procedure will create 2 tables with ‘one table having a constraint based on another table ‘This code can only run via ADO in VBA ‘This is not supported in DAO ‘From “Microsoft Access 2000 Development Unleashed” (SAMS) ‘By: Forte, Howe, Ralston Dim conn As ADODB.Connection On Error GoTo Proc_Err Set conn = CurrentProject.Connection
5 THE MICROSOFT JET DATABASE ENGINE
‘Create the table that we will lookup the credit limit conn.Execute “CREATE TABLE CreditLimit (CreditLimit DOUBLE);” ‘Insert the Credit Limit conn.Execute “INSERT INTO CreditLimit VALUES (100);” ‘Create the Customer Table With the Constraint conn.Execute “CREATE TABLE Customers (CustId IDENTITY (100, “ & _ “10), CFrstNm VARCHAR(10), CLstNm VARCHAR(15), “ & _ “CustomerLimit DOUBLE, CHECK (CustomerLimit <= “ & _
116
Database Design Unleashed PART I LISTING 5.5
continued
“(SELECT SUM (CreditLimit) FROM CreditLimit)));” ‘Do a successful insert conn.Execute “INSERT INTO Customers (CLstNm, CFrstNm, CustomerLimit)” & _ “VALUES (‘Collins’, ‘Kevin’, 100);” ‘Will bomb on this line since the credit limit violates the rule conn.Execute “INSERT INTO Customers (CLstNm, CFrstNm, CustomerLimit)” & _ “VALUES (‘Forte’, ‘Stephen’, 101);” Proc_Exit: Exit Sub Proc_Err: MsgBox Err.Description, vbCritical Resume Proc_Exit End Sub
The first record meets the constraint and will insert successfully, but the second record will fail because the customer’s credit limit (101) is higher than the constraint permits.
Summary This chapter discussed the history of Microsoft Jet, the database engine behind Access 2002. It also described some of the most valuable features of the current Jet version, 4.0, and showed you how to use some of them in your own projects. Unfortunately, some of Jet’s features, such as changing the starting value of an AutoNumber field or defining a constraint, cannot be accessed directly from Microsoft Access 2002; you have to write code. However, the tradeoff is the ability to add powerful and sophisticated features to your Access applications.
Data Access
PART
II IN THIS PART 6 Introduction to ActiveX Data Objects 7 Advanced ADO
CHAPTER 6
Introduction to ActiveX Data Objects IN THIS CHAPTER • History of Data Access
120
• Microsoft’s Universal Data Access Initiative 121 • ActiveX Data Objects (ADO) • The ADO Object Model
122
125
• Moving from DAO to ADO
142
• The ADO Object Model Compared to DAO 145
120
Data Access PART II
With the release of Office 2000, ActiveX Data Objects (ADO) entered the mainstream. In Office 2000, ADO replaced DAO and ODBCDirect as the data access method of choice for both Jet and Client Server data. Now there is only one data access method and object model to learn and use. It has been a long and bumpy ride to reach this data-access nirvana.
History of Data Access You will now take a look at the road to ADO. By looking at the history of data access, you can see the benefit that you get from ADO.
Proprietary APIs Back before Microsoft was in the data access game, the only way to access data programmatically was through proprietary APIs. This forced you to learn a different API for each database system that you wanted to write to. Needless to say, this was not very convenient, nor was it any fun.
Open Database Connectivity (ODBC) A few years ago, Microsoft offered the Open Database Connectivity (ODBC) specification. ODBC was a generic programmatic API that enabled you to write to any database that had an ODBC driver. Writing to the databases required you to learn the ODBC API; however, now you only had to learn one API for all the databases that you wanted to use. The ODBC API was not easy to use; however, it was a great first step in the data access problem of too many APIs. As you know, ODBC quickly became the data access standard.
Microsoft Jet/Data Access Objects (DAO) When Microsoft Access 1.0 shipped with Microsoft Jet and Data Access Objects (DAO), data access became much easier. DAO provided a native data access object model for Jet. In addition, Jet was able to easily communicate via ODBC with many ODBC-compatible data sources, and Jet could also communicate with other desktop databases. The Microsoft Jet Engine was used by millions to access different databases under one data access object model.
Remote Data Objects (RDO) and ODBCDirect With the release of Visual Basic 4.0 Enterprise Edition, Microsoft released the new object model of ODBC data sources, Remote Data Objects (RDO). A thin wrapper
Introduction to ActiveX Data Objects CHAPTER 6
Figure 6.1 shows Microsoft Universal Data Access technology as it exists today. OLE DB’s main object model for data access is called ActiveX Data Objects (ADO). As you can see, either directly or via ADO, OLE DB can access database, non-relational, and mainframe data through one interface.
TO
With so many data access methodologies out there, Microsoft decided to create a new standard in its Universal Data Access initiative. OLE DB is the first implementation of that new initiative. An open specification designed to build on the success of ODBC, OLE DB is an open standard for accessing all kinds of data. ODBC was created to access relational databases, while OLE DB was designed for the relational and nonrelational information sources, such as mail stores, text and graphical data for the Web, directory services, and IMS and VSAM data stored in the mainframe. Where ODBC communicated via ODBC drivers, OLE DB communicates to data stores via data providers. OLE DB enables you to learn one object model for all your databases and even use that object model for non-relational data stores. OLE DB is a great improvement over ODBC because it can talk to many different data stores. To provide backward compatibility, OLE DB shipped with a provider for ODBC. Today, in addition to the OLE DB Provider for ODBC, there exist providers for Jet, SQL Server, Oracle, NT 5 Active Directory, and many more.
INTRODUCTION
Microsoft’s Universal Data Access Initiative
6 ACTIVEX DATA OBJECTS
around the ODBC API, RDO offered an object model to access ODBC data bypassing the Jet Engine. This eliminated the Jet communication layer and increased speed. While RDO did offer superior data access, programmers (including the authors of this book!) were not happy to have to learn and master two data access object models. Most programmers were already very comfortable with DAO and never learned RDO. Microsoft responded with ODBCDirect, an extension to the DAO object model that used RDO to access external data without using the Jet Engine. Now there were four ways to access data: the ODBC API, DAO, RDO, or ODBCDirect. Clearly, the proliferation of objects models from Redmond now reached critical mass, and something had to be done. Enter Microsoft’s Universal Data Access initiative.
121
122
Data Access PART II
FIGURE 6.1
Application
Data access as it exists today. DAO RDO
ADO
OLE DB
ODBC
SQL Data
Non SQL Data
SQL Server
Oracle
Mail
Video
Jet
Other
Text
Other
FoxPro
Directory Services
MainFrame and Legacy Data
ActiveX Data Objects (ADO) ActiveX Data Objects (ADO) is the object model that you can use to get at OLE DB data. ADO has been around for a while and with version 2.0, ADO matured into the preferred data access methodology from Microsoft. Let’s take a quick look at ADO’s history.
ADO 1.0 When ADO was first released in late 1996, it was primarily used to access data via script in Active Server Page–based Web applications. ADO only exposed the very basic client/server data access functionality. At that time, ADO was a subset of the popular object models DAO and RDO. Developers used the only OLE DB Provider available, a generic OLE DB provider for ODBC data sources.
ADO 1.5 In the Fall of 1997, Microsoft released ADO 1.5 with the Microsoft Data Access Components 1.0 (MDAC) and IIS 4.0. ADO 1.5 introduced, among other things, Remote Data Services (RDS) and support for disconnected recordsets. The first OLE DB provider to surface was a beta copy of the OLE DB Provider for JET (the Access engine) called JOLT.
ADO 2.0 With the release of MDAC 2.0 in the summer of 1998, ADO entered its third major release with ADO 2.0. ADO 2.0 is almost a superset of RDO 2.0 and DAO 3.5, with
Introduction to ActiveX Data Objects CHAPTER 6
• Creatable Recordsets • OLAP Recordsets We will look at these technologies in the Chapter 7, “Advanced ADO.”
ADO 2.1 ADO 2.1 shipped with SQL Server 7.0, Office 2000, and Internet Explorer 5.0. ADO 2.1 consists of all the ADO 2.0 features, including two new object models to help us out with DDL and replication. Included with ADO 2.1 are: • ADO—For DDL operations and Security (ADOx) • JRO (Jet Replication Objects)—For replication features and compact/repair of Jet databases ADOx works best with JOLT; however, it is being extended to SQL Server and other providers. JRO is Jet-specific extensions to ADO, mostly used to support Jet replication. Tip Like everything in our industry, ADO and OLE DB are a work in progress. With things changing so fast, it is hard to keep up. As Microsoft releases versions of ADO out of sync with releases of Office and this book, check out the OLE DB/ADO Web site for more information and late-breaking details. The Web site is filled with code samples and technical white papers. It is shown in Figure 6.2 and located at http://www.microsoft.com/data.
TO
• Recordset Persistence
INTRODUCTION
• Microsoft Data Links
6 ACTIVEX DATA OBJECTS
some additional cool features. ADO 2.0 also shipped with a few OLE DB providers ready for prime time, including providers for Jet, SQL Server, and Oracle. Some of the new features in ADO 2.0 we have seen before in RDO and DAO, including asynchronous operations and resynching via client cursors. ADO also included some new innovative techniques like
123
124
Data Access PART II
FIGURE 6.2 The ADO/OLE DB Web site.
ADO 2.5 Microsoft skipped versions 2.2, 2.3, and 2.4. (On occasion version skipping is done to synchronize version numbers across related products or to indicate the difference between minor revisions and major revisions.) ADO 2.5 introduced new features to further support working with data across the Web. Specifically, ADO 2.5 introduced: • The Record object, used to manage data representing things like files and directory listings • The Stream object, for managing binary byte streams • Support for Uniform Resource Locators (URLs) in Connection strings • And, special fields for document source providers a unique set of fields for managing documents We’ll look at some of these new features in detail later in this chapter.
ADO 2.6: Where We’re at Today ADO is being updated regularly. The best place to check for the current version of ADO is the www.microsoft.com/data Web site previously mentioned. By the time you are reading this text, ADO 2.7 will likely exist and be readily available. Because ADO is separate from Access, you can update ADO as Microsoft makes new versions available.
Introduction to ActiveX Data Objects CHAPTER 6
FIGURE 6.3
Connection
The ADO object model.
Errors
Error
Properties
Property
Parameters
Parameter
Properties
Property
Fields
Field
Properties
Property
Fields
Field
Command
Recordset
Record
Stream
The ADO object model consists of nine primary objects listed here: •
Connection
•
Recordset
•
Record
TO
The ADO object model is very simple and flat. While DAO and RDO were very hierarchical, ADO is not. This flat object model is shown in Figure 6.3.
INTRODUCTION
The ADO Object Model
6 ACTIVEX DATA OBJECTS
Sometime in the fourth quarter of 2001, Microsoft will likely release Visual Studio.NET and ADO.NET. Currently Office XP, including Access, does not support ADO.NET. This is likely to change in the foreseeable future, implying that there will be new and simpler means of managing data using ADO. For the current capabilities supported by ADO 2.6, read the next section entitled “The ADO Object Model.”
125
126
Data Access PART II
•
Command
•
Parameter
•
Field
•
Property
•
Stream
•
Error
Because ADO is a COM-based object library, it should be very familiar to you how to create ADO objects. For example, you can create an ADO connection object like this: Dim Connection As ADODB.Connection Set Connection = New ADODB.Connection
After you have created your object, you can then set its properties and execute its methods, which is the focus of the rest of the chapter.
Connection Object The Connection object represents a physical connection to your database or data provider. You can open a connection by telling the Connection object what provider to use and then specify a connection string. This code is shown in Listing 6.1 and is located in the chapter06.mdb file on the CD-ROM accompanying this book. LISTING 6.1
Connecting to an Access Database via ADO and a Connection Object
1: Sub ConnectToDatabase() 2: 3: Dim Connection As ADODB.Connection 4: On Error GoTo Except 5: 6: Set Connection = New ADODB.Connection 7: Connection.Provider = “Microsoft.Jet.OLEDB.4.0” 8: Connection.ConnectionString = “data source=C:\TEMP\nwind.mdb” 9: Connection.Mode = adModeReadWrite 10: Connection.Open 11: 12: MsgBox “Connected via “ & Connection.Provider & _ 13: “ OLE DB Provider!”, vbInformation 14: 15: Exit Sub 16: 17: Except: 18: MsgBox Err.Description, vbCritical 19: End Sub
Introduction to ActiveX Data Objects CHAPTER 6
Listing 6.1 makes use of some of the Connection object’s properties. We made use of
•
ConnectionString
•
Mode
Opening a Connection Within Microsoft Access 2002 When using ADO in your Access 2002 application, specifying a connection to the same database is shortened. Because Access uses a global Connection object itself, like the CurrentDB in older DAO versions, you can specify a Connection objection off the CurrentProject.Connection object like so: Dim Connection As ADODB.Connection Set Connection = CurrentProject.Connection
You can write code like this, but it is imprudent to do so. A new methodology for improving code, stemming from Extreme Programming (XP), referred to as Refactoring, suggests that local temporary variables clutter up your code. In fact, if you used these two statements everywhere you needed a local connection, then you could end up with dozens of superfluous lines of code. Note Refactoring is an outgrowth of a dissertation by William Opdike from the early 1990s. To learn more about Refactoring, read Refactoring: Improving the Design of Existing Code, by Martin Fowler, published by Addison-Wesley.
Refactoring is a process for improving code. The processes are named by the type of Refactoring and are defined by a series of steps to refine the code without changing it. Applied to our two statements we could apply the Refactoring “Replace Temp With
TO
is a string that represents the unique ProgID of your OLE DB provider. Here we use “Microsoft.Jet.OLEDB.4.0” to represent the OLE DB provider for Jet 4.0. The connection string is how you specify the path to the database and any other connection information like the location of workgroup file and security information. (See Chapter 22, “Security,” for more information.) Last, we explicitly set the Mode property to an ADO constant adModeReadWrite. This enables us to open the database in Read/Write mode. You can also specify to open a database exclusively as read-only here. Provider
6 INTRODUCTION
Provider
ACTIVEX DATA OBJECTS
•
127
128
Data Access PART II
Query,” which essentially, in this instance, shortens the CurrentProject.Connection fragment to a function that returns the reference to the current projects’ Connection object. Refactoring is beyond the scope of this book, however, you can learn more about Refactoring by reading Martin Fowler’s book (see the note). At a minimum, I would suggest simply using the CurrentProject.Connection object without a temporary variable.
Connecting with a URL As the World Wide Web swells to ubiquity, its incorporation in everyday life will become increasingly prevalent. The first place internetworking will dominate is application development. (We have to build the applications before the users can use them.) ADO has been extended in the recent release to support ADO.Connection across an intranet or the Internet using a Uniform Resource Locator (URL). The syntax for specifying the URL for a connection is identical to URL schemas in general: schema:// host/path, where schema is one of the TCP/IP schemas like ftp, file, or http. Listing 6.2 demonstrates defining an ADO.Connection to your own PC through the localhost name. LISTING 6.2
Connect Using a URL
1: Sub ConnecttoURL() 2: 3: On Error GoTo Except 4: 5: Dim Connection As New ADODB.Connection 6: Connection.Provider = “Microsoft.Jet.OLEDB.4.0” 7: Const URL = “http://localhost/access/nwind.mdb” 8: 9: Connection.ConnectionString = “URL=” & URL 10: 11: Connection.Mode = adModeReadWrite 12: Connection.Open 13: 14: MsgBox “Connected via “ & Connection.Provider & _ 15: “ OLE DB Provider!”, vbInformation 16: 17: Exit Sub 18: 19: Except: 20: MsgBox Err.Description, vbCritical 21: End Sub
Introduction to ActiveX Data Objects CHAPTER 6
6
Caution
When you are using a Connection object, you can execute SQL statements off the current Connection object. This is very similar to executing a SQL statement off a database object in DAO. Listing 6.3 shows how to execute a SQL statement off a Connection object. Our SQL statement will update all rows in the Customers table where Region= “BC” to have region now equal to “YK”. Notice how you can find out how many records were affected by supplying a variable to the Execute method and then checking the value of that variable. Executing a SQL Statement Against a Connection
1: Sub ConnectionExecute() 2: 3: On Error GoTo Except 4: 5: Dim SQL As String 6: SQL = “UPDATE Customers SET Customers.Region = “ & _ 7: Chr(39) & “YK” & Chr(39) & vbNewLine & _ 8: “WHERE (((Customers.Region)=” & _ 9: Chr(39) & “BC” & Chr(39) & “));” 10:
TO
Executing a SQL Statement off a Connection Object
INTRODUCTION
Line 3 establishes an error handler. Because creating a new Connection object, the Connection object is dimmed inside of the error handler, on line 5. Line 6 indicates the Provider and line 7 defines an absolute URL. Localhost is a predefined Uniform Resource Name (URN) that always refers to the PC it is used on. Localhost is the URN for the loopback IP address 127.0.0.1, which always refers to the PC the IP address is used on. Line 12 opens the connection and line 13 shows the provider information used to create the Connection. If Connection.Open fails, then the error handler on line 19 displays the error description.
ACTIVEX DATA OBJECTS
For Listing 6.2 to work correctly, you will need Internet Information Services (IIS) installed on your PC and have copied the NWIND.MDB (NorthWind Trading Company) sample database that ships with Access to the folder access from the default Web site on your PC. Generally, the default physical path defined when you install IIS is c:\inetpub\wwwroot. The entire path in the described scenario would be c:\inetpub\wwwroot\access\nwind.mb.
LISTING 6.3
129
130
Data Access PART II LISTING 6.3
continued
11: Dim RecordsAffected As Long 12: CurrentProject.Connection.Execute SQL, RecordsAffected 13: 14: MsgBox RecordsAffected & “ Records Updated!”, vbInformation 15: 16: Exit Sub 17: 18: Except: 19: MsgBox Err.Description, vbCritical 20: End Sub
Listing 6.3 establishes error handling on line 3. Line 6 defines the SQL statement, followed by a long used to store the number of records modified by the Execute statement on line 12. Line 12 uses the CurrentProject.Connection—instead of declaring a local variable, which unnecessarily lengthens the subroutine—and calls the Execute method passing the UPDATE SQL statement. Line 14 reports the number of modified records.
ADO Recordset Object A Recordset object is a programmatic collection of data from a database table or query/SQL statement. A recordset will have fields filled with data for each row in the underlying table or query. To open a recordset, you have to use this syntax: Recordsetobject.Open “Statement”, _ ActiveConnection, CursorType, LockType, Options
Table 6.1 defines each option. TABLE 6.1
ADO Recordset Open Parameters
Argument
Required
Notes
Default
Statement
Yes
A table name, query name, URL, or validSQL statement.
—
ActiveConnection
Yes
A valid Connection object or valid connection string.
—
Introduction to ActiveX Data Objects CHAPTER 6 TABLE 6.1
continued
6 Notes
Default
Cursor Type
No
adOpenDynamic—
adOpenForwardOnly
adOpenForwardOnly—
Forward only non-scrollable recordset. adOpenKeyset—No
capability to see other people’s changes in recordset; ability to see changes made by the current user. adOpenStatic—No
capability to see changes in recordset. No
adLockBatchOptimistic— adLockReadOnly
Lock records in a batch. adLockOptimistic—
Optimistic locking. adLockPessimistic—
Pessimistic locking. adLockReadOnly—Read
only.
TO
Capability to view changes in recordset, even changes by other users.
INTRODUCTION
Required
ACTIVEX DATA OBJECTS
Argument
Lock Type
131
132
Data Access PART II TABLE 6.1
continued
Argument
Required
Notes
Default
Options
No
adCmdFile—Opening
adCmdUnknown
a persisted recordset on disk. adCmdStoredProc—A
SQL Server stored procedure or Access query. adCmdTable—Do a Select * From a table. adCmdTableDirect—
Open a table directly. (Like dbOpenTable in DAO.) adCmdText—A SQL
Statement. adCmdUnknown—Unknown,
ADO will have to figure it out for you.
Listing 6.4 shows you how to open a recordset based on the Customers table. We establish a connection based on the current database, and open a recordset with a forwardonly, read-only cursor. We also use adCmdTableDirect, which will tell ADO to open the table directly. LISTING 6.4 1: 2: 3: 4: 5: 6: 7: 8: 9:
Opening an ADO Recordset
Sub OpenRecordset() On Error GoTo Except Dim Recordset As New ADODB.Recordset Recordset.Open “Customers”, CurrentProject.Connection, _ adOpenForwardOnly, adLockReadOnly, adCmdTableDirect
Introduction to ActiveX Data Objects CHAPTER 6 LISTING 6.4
continued
Additionally, you can supply all the connection information as a string and open the connection dynamically without a Connection object as shown here: Recordset.Open “Customers”, “provider=Microsoft.Jet.OLEDB.4.0; “ & _ “data source C:\temp\nwind.mdb “, _ adOpenForwardOnly, adLockReadOnly, adCmdTableDirect
In addition to opening a table, you can open a Recordset based on a SQL statement. An example is shown here: Recordset.Open “Select * From Customers Where CustomerID= ALFKI”, _ CurrentProject.Connection, _ adOpenForwardOnly, adLockReadOnly, adCmdTableDirect
As you know, one of the most powerful features of Microsoft Jet is its capability to work with external data so efficiently. To open an external data source, you will have to alter your connection string. The data source has to point to the external file (text file, DBF file, Excel, and so on) and you must set the “Extended Properties” property to the name of the ISAM that you are accessing. The next code snippet example demonstrates how Jet can access an Excel 8.0 spreadsheet with ADO. In the following example, we open a Recordset based on the data in “Sheet1” of the Customers.xls file: Dim Connection As ADODB.Connection Set Connection = New ADODB.Connection With Connection
TO
Recordset.Open “Customers”, _ CurrentProject.Connection, adOpenForwardOnly, adLockReadOnly, adCmdTableDirect
INTRODUCTION
In Listing 6.4, we are using an explicit CurrentProject.Connection without introducing an unnecessary local temporary as shown here:
6 ACTIVEX DATA OBJECTS
10: Do Until Recordset.EOF 11: Debug.Print Recordset!CompanyName 12: Recordset.MoveNext 13: Loop 14: 15: Recordset.Close 16: Set Recordset = Nothing 17: 18: Exit Sub 19: 20: Except: 21: MsgBox Err.Description, vbCritical 22: 23: End Sub
133
134
Data Access PART II .Provider = “Microsoft.Jet.OLEDB.4.0” .ConnectionString = “Data Source=C:\excel\Customers.xls;” & _ “Extended Properties=Excel 8.0;” .Open End With Dim Recordset As New ADODB.Recordset Recordset.Open “Sheet1$”, Connection, adOpenDynamic, _ adLockOptimistic, adCmdTableDirect
Using a Recordset with Command and Parameter Objects A Command object represents a specific command that you intend to execute against a data source via its provider. An action query is an example of a command. You can also use a Command in conjunction with a Parameter object to execute Access parameter queries or SQL Server Stored Procedures. A Parameter object maps to a parameter or argument associated with your Command object. We are going to look at how to execute an Access stored parameter query. This query is available in the chapter6.mdb file on the CD-ROM under the name qryCustOrders_Prm. The query’s SQL is shown here: PARAMETERS OrderID Long; SELECT Orders.* FROM Orders AS Orders WHERE (((Orders.OrderID)=[OrderID]));
In the Access query grid, we defined our query and created a parameter for our query by using the Query, Parameters menu option and defining our parameters as shown in Figure 6.4. FIGURE 6.4 The Query Parameters dialog.
Here, we create a Command object and tell it what Connection object you are going to use and what type of command it is. We tell it to use the Connection object that we just
Introduction to ActiveX Data Objects CHAPTER 6
We set the CommandType property to adCmdStoredProc because ADO/JOLT treats stored queries as procedures. Another type of CommandType is adCmdTable, used with older versions of Jet. Note When converting an application from Jet 3.51 to Jet 4.0 in Access 2002 or VB6, be aware of the differences in how the two methods work. With Jet 3.51, you have to specify a CommandType as an adCmdTable, with Jet 4.0, you would have to use adCmdStoredProc.
To set the parameter information, all you have to do is set four properties: Name, Type, Value, and Direction. Specify the Name of the parameter, and its datatype as it is named in your stored Jet query. You also need to specify the Direction property, which informs ADO whether the parameter is an input, output, or return value. Lastly, set the value of the parameter, based on what the user specified in your application. Then append the parameter to the Command object’s parameter collection. Note When using command objects, Jet only supports input parameters. SQL Server and other database servers can support output parameters from Stored Procedures, so do not try to declare an output parameter.
With Parameter .Name = “OrderID” .Value = 10248 .Type = adInteger .Direction = adParamInput End With cmd.Parameters.Append Parameter
TO
With Command .ActiveConnection = Connection .CommandText = “qryCustOrders_Prm” .CommandType = adCmdStoredProc End With
ACTIVEX DATA OBJECTS
Dim Command As New ADODB.Command
6 INTRODUCTION
created and then point to the qryCustOrders_Prm query in our Access database. You can use the same connectionless options for a recordset with a Command object.
135
136
Data Access PART II
Now use the Execute method of the Command object to create a Recordset object. You can use the data from the recordset to fill in text boxes on a VB Form, or perform a calculation. To get the data from the executed command, you must set the Recordset to an executed command as shown here. Set Recordset = Command.Execute
Listing 6.5 pulls all these examples together and opens a recordset based off an executed command. LISTING 6.5
Executing a Command
1: Sub OpenRecordsetviaCommand() 2: 3: On Error GoTo Except 4: 5: Dim Command As New ADODB.Command 6: With Command 7: .ActiveConnection = CurrentProject.Connection 8: .CommandText = “qryCustOrders_Prm” 9: .CommandType = adCmdTable 10: End With 11: 12: Dim Parameter As New ADODB.Parameter 13: With Parameter 14: .Name = “OrderID” 15: .Value = 10248 16: .Type = adInteger 17: .Direction = adParamInput 18: End With 19: 20: Command.Parameters.Append Parameter 21: 22: Dim Recordset As New ADODB.Recordset 23: Set Recordset = Command.Execute 24: 25: Do Until Recordset.EOF 26: Debug.Print Recordset!OrderDate 27: Recordset.MoveNext 28: Loop 29: 30: Recordset.Close 31: Set Recordset = Nothing 32: Set Command = Nothing 33: Set Parameter = Nothing 34: 35: Exit Sub 36: 37: Except: 38: MsgBox Err.Description, vbCritical 39: End Sub
Introduction to ActiveX Data Objects CHAPTER 6
Using a Record Object ADO Records represent a single row in a Recordset, a file, or a file system directory. One example of using the Record object is to connect to an absolute or relative path of a URL and manage the files and directories relative to the path using the Record object. Fields in the Record object are the files and directories. Listing 6.6 demonstrates connecting to a URL and iterating over each file relative to the URL. LISTING 6.6
Use the ADO Record Object to Manage Files Relative to a URL
1: Sub OpenRecord() 2: 3: Dim Record As New ADODB.Record 4: Call Record.Open(“”, “URL=http://localhost/”, , adOpenIfExists Or adCreateCollection) 5: 6: Dim Recordset As New ADODB.Recordset 7: Set Recordset = Record.GetChildren 8: 9: While Not Recordset.EOF 10: Debug.Print Recordset(0) 11: Recordset.MoveNext 12: Wend 13: 14: End Sub
TO
Declaring variables at the top of a procedure is a hold over from the C programming language. C required variables to be declared at the top of the function. Modern compilers no longer assert this requirement, and it is cumbersome to do so. Postponing variable declaration increases the understandability and context of the variable. In addition, postponing variable declaration until first use simplifies the process of simplifying code. For example, in an earlier section we discussed removing the temporary Connection variable. If such a decision were made in existing codel, then having the variable immediately preceding the variable would make this process very simple indeed.
INTRODUCTION
Listing 6.5 demonstrates the readability of whole words. There is no longer any penalty for, or prohibition against, using whole. Whole words make code more readable and help reduce the number of comments you might need, reducing overall labor. Note that variables are introduced immediately before they are first used; postponing variable introduction eliminates the need for prefix notations and makes it clear what the local variable’s raison d’être is.
6 ACTIVEX DATA OBJECTS
Assembled in one subroutine, the Command and Recordset objects used together are demonstrated in lines 1 through 40 as described in the text preceding the listing. Let’s take a moment to discuss style.
137
138
Data Access PART II
The code declares an ADO Record object. The Open command creates an implicit Connection by declaring a URL connection string—the second argument is the ActiveConnection—and opens a Record represented by the files at http://localhost if the directory exists. The adOpenIfExists opens an existing path and the or adCreateCollection forces the path to be created if it does not exist. The Record.GetChildren method returns an ADO.RecordSet which can be used as if the Recordset were an Access table. In Listing 6.6, each row of the Recordset based on the Record is an attribute of the files and directories at http://localhost. The Record Object is defined to allow ADO to work with the Microsoft OLE DB Provider for Internet Publishing (the Internet Publishing Provider or MSDAIPP.DSO) to manage FrontPage or IIS served files, Windows Web folders, or file systems across the Internet. The Record object can be used to upload, download, move, copy, and delete files across a network, including an intranet or the Internet.
Executing an Action Query via a Command You can execute saved Access action queries via a Command object. We have a query in our chapter6.mdb file called qryUpdateTitle that will update each employee title in our Customers table from Account Manager to Account Executive. The SQL of that query is shown here: UPDATE Customers SET Customers.ContactTitle = “My Title” WHERE (((Customers.ContactTitle)=”Accounting Manager”));
To run the query programmatically via ADO, you must create a Command object, hook it up to a Connection object, and execute it. Listing 6.7 demonstrates how to accomplish this. LISTING 6.7
Executing an Access Action Query via ADO
1: Sub ActionQueryCommand() 2: 3: On Error GoTo Except 4: 5: Dim Command As New ADODB.Command 6: Dim RecordsAffected As Long 7: 8: Command.ActiveConnection = CurrentProject.Connection 9: Command.CommandText = “qryUpdateTitle” 10: Command.CommandType = adCmdStoredProc 11: Command.Execute , RecordsAffected 12: 13: MsgBox RecordsAffected & “ records were updated!”, _ 14: vbInformation
Introduction to ActiveX Data Objects CHAPTER 6 LISTING 6.7
continued
LISTING 6.8
Working with Field and Property via ADO
1: Sub FieldandProperty() 2: 3: On Error GoTo Except 4: 5: Dim Recordset As New ADODB.Recordset 6: Recordset.Open “Customers”, CurrentProject.Connection 7: 8: Debug.Print “Table Fields:” 9: 10: Dim Field As ADODB.Field 11: For Each Field In Recordset.Fields 12: Debug.Print Field.Name & “: “ & Field.Value 13: Next Field 14: 15: Debug.Print 16: Debug.Print “Table Properites:” 17: Dim Property As ADODB.Property 18: For Each Property In Recordset.Properties 19: Debug.Print Property.Name 20: Next Property 21: 22: Recordset.Close 23: Set Recordset = Nothing 24: 25: Exit Sub 26: 27: Except: 28: MsgBox Err.Description 29: End Sub
TO
The Field and Property objects are great objects for finding out information about your table or recordset. The Field object represents each field column in your recordset. The Property object represents each property of whatever object you are querying. You can iterate through each field in your recordset or property in your object variable via the For...Each syntax as shown in Listing 6.8.
INTRODUCTION
Field and Property Objects
6 ACTIVEX DATA OBJECTS
15: 16: Exit Sub 17: 18: Except: 19: MsgBox Err.Description 20: End Sub
139
140
Data Access PART II
Using the Stream Object ADO Streams are akin to streams in most languages that implement them. Stream is the name of a class defined to manage a binary stream of data. The Record Object manages file systems; streams manage individual files. Listing 6.9 demonstrates using a Stream object to read text file across an Intranet. LISTING 6.9
Reading a File Referred to by a Record Across an Intranet
1: Sub OpenStream() 2: 3: Dim Record As New ADODB.Record 4: Call Record.Open(“Test.txt”, “URL=http://localhost/Access/”, adModeRead) 5: 6: Dim Stream As New ADODB.Stream 7: Call Stream.Open(Record, adModeRead, adOpenStreamFromRecord) 8: 9: Dim Text As String 10: Stream.Charset = “ascii” 11: Text = Stream.ReadText(adReadAll) 12: Debug.Print Text 13: 14: End Sub
Note If you installed IIS on your PC in the default directory, you need a text file in the physical file location, c:\inetpub\wwwroot\Access\Test.txt. The path localhost refers to c:\inetpub\wwwroot.
Lines 3 and 4 declare and open a Record object referring to the Localhost URL. (The example assumes IIS is running on the desktop that you are running the example on.) Lines 6 and 7 declare and open a Stream object from a Record. Line 9 changes the character set for the stream from the default Unicode to ASCII. Line 11 reads all of the text and line 12 prints the contents of the file to the Immediate window. Use the Record object to manage files across a network and use the Stream object to manage the content of those files. Stream objects make it easy to add and remove content from files.
Introduction to ActiveX Data Objects CHAPTER 6
Managing Errors with the Error Object
Property
Comment
Description
A description of the error.
Number
The ADO error number.
Native Error
The provider’s error number.
SQL State
This is a provider-specific error code. For Jet this will map to DAO’s old error number.
Source
The source of the error. In our case, it will be the Jet engine.
Because any given error in your code can generate many ADO errors, you can iterate through the Connection’s error collection and then query these properties. If you have code in your application that depends on an old DAO error number, you will have to use the SQLState property for backward compatibility. SQLState will return the old DAO error code for you. You can iterate though the error collection using the Error object as shown in Listing 6.10. The result of the code in Listing 6.10 is shown in Figure 6.5. LISTING 6.10
Using the ADO Error Object
1: Sub ConnectionErrorHandler() 2: 3: On Error GoTo Except 4: Dim Connection As ADODB.Connection 5: Set Connection = CurrentProject.Connection 6: Dim Recordset As New ADODB.Recordset 7: Recordset.Open “badTable”, Connection 8: Exit Sub 9: 10: Except: 11: Dim ADOError As ADODB.Error 12: 13: For Each ADOError In Connection.Errors 14: MsgBox “ADO Error: “ & ADOError.Description & _
TO
The Major Properties of the Error Object
INTRODUCTION
TABLE 6.2
6 ACTIVEX DATA OBJECTS
When writing code, you sometimes introduce bugs; or system changes, beyond your control, render your code invalid. (Like a LAN administrator moving a back-end MDB file without alerting you!) The ADO Connection object has a collection of Error objects that will represent each error that occurred. The Error object has a few properties that you will be concerned with. These properties are summarized in Table 6.2.
141
142
Data Access PART II LISTING 6.10
continued
15: vbNewLine & “Native Error: “ & _ 16: ADOError.NativeError & _ 17: vbNewLine & “SQL State: “ & _ 18: ADOError.SQLState & _ 19: vbNewLine & “Source: “ & _ 20: ADOError.Source, vbCritical, _ 21: “Error Number: “ & ADOError.Number 22: Next ADOError 23: End Sub
FIGURE 6.5 An error message making use of the Error object.
Moving from DAO to ADO Our introduction to ADO has shown that there are many similarities between Data Access Objects (DAO) and ADO. Throughout this entire book, you will be given advice on how to use ADO compared to DAO. This section is intended to prepare you for the initial conversion process and to compare the two object models.
Converting from Prior Versions of Access When converting prior version of an Access database to Access 2002, you should note that ADO is the new default data access methodology. This might cause some confusion when creating an object that has the same name in DAO and ADO like “recordset.” If you have some code like this in Access 2002:
Introduction to ActiveX Data Objects CHAPTER 6 Dim db As Database Dim Recordset as Recordset
Should I Convert to ADO? When starting a new Access 2002 application, the choice is easy. Use ADO. What about applications that you are converting to Access 2002? The move to ADO should be considered when choosing to convert to Access 2002. You will want to convert to ADO as soon as possible to take advantage of the new features that are not available in DAO. In addition, Microsoft has announced that it is phasing out DAO; so in a future version of Access, DAO might not be supported directly. Because ADO is the way of the future, you should take ADO very seriously. Do you have the time? Money? The major consideration should be your skill level and budget. Reading through the chapters in this book and the ADO documentation on the Microsoft Web site (http://www.microsoft.com/data) should prepare you for learning ADO. The next section outlines a typical conversion plan. Learning ADO and converting your application’s code from DAO to ADO should be part of the conversion budget. Converting to Access 2002 will require more developer hours than a typical conversion. Following the conventions outlined here can save you much time, money, and aggravation. This section alone can more than pay for the price of the book. (Feel free to share the wealth with Sams and the authors!)
A Conversion Guideline This section outlines how you should approach converting an application from DAO to ADO. Remember, back up your work religiously! 1. If you are converting from a version of Access prior to Access 2000 and are using DAO 2.5 to 3.x then you will need to replace the DAO code with ADO code before converting the database. Determine if the benefits outweigh the costs. If so, then continue. 2. Install the latest version of Data Access Components, downloadable from www.microsoft.com/data.
TO
This will leave zero room for failure when converting for your DAO object variables.
INTRODUCTION
Dim db as DAO.Database Dim Recordset as DAO.Recordset
6 ACTIVEX DATA OBJECTS
Access 2002 will assume that the Recordset variable will be an ADO Recordset, not a DAO Recordset, because ADO is referenced before DAO in your VBA References by default. Prior to converting your Access 97, 95, or other database, you should prefix all your DAO objects with the type library name: DAO. The code should be rewritten like this:
143
144
Data Access PART II
3. Open the existing database in the version of Access in which it was created. 4. Begin by converting the procedures that do not communicate with other procedures first. When you are done with one procedure, test and retest. Then move on to the next procedure. This might take days or even weeks, depending on how large your database is. 5. Do not delete your old procedures; rename them ProcedureName_DAO, adding the _DAO to the end of the procedure, so you can quickly rename the ADO procedure (use _ADO) and substitute the DAO procedure in your testing. 6. After you convert the code that exists in more isolated procedures, start looking at the code in larger and more complex procedures. Do not get caught up in fixing other things in this procedure; save that enhancement for a later time. Change only the DAO code. Use the same testing methodology as mentioned in step 5. 7. After you convert all the code, test an old DAO copy of the application side-byside with the new one. Then have another developer test your application. 8. Develop routines that will enable users to easily undo anything that they have done. This way, if your application is causing data errors, users can revert back to the state they were in before they started running your code. 9. Have user “beta” testing of your application in daily work. Choose a few reliable users to test your ADO version. Do not delete the old working DAO copy; provide an icon to it just in case there are errors so severe that they interfere with productivity. 10. After you are satisfied that the users have tested your application thoroughly, convert your application to Access 2002 and repeat numbers 7–9. Making Sure That Your Users Are Actually Testing! In order to know that your users actually are testing the application enough, you can incorporate a technique that we use at the Aurora Development Group. We do not want to be blamed for bugs that a user could have found when testing, so we implement a very detailed audit trail in our beta test applications. At the start of each procedure, even simple ones like a Close button, we log all the information into a database. This will give us an indication as to how many times a user has entered a particular procedure, or even run a certain report. Then, we do an analysis of these numbers and ask the users to test certain parts of the application based on what was low in usage. With this procedure, we can be sure that the users have tested everything before we convert the beta application to a production system.
Introduction to ActiveX Data Objects CHAPTER 6
When Not to Convert to ADO
The ADO Object Model Compared to DAO DAO has a huge object model with over 50 objects. ADO is small and has only 9. Where did everything go! You will see in this section how to compare DAO and ADO in Data Access. Chapter 7, “Advanced ADO,” discusses this issue. Table 6.3 summarizes the most common objects for data access in DAO and shows their ADO equivalent. TABLE 6.3
DAO to ADO Data Access Reference
DAO Object
ADO Object
DBEngine
None
Workspace
None
Database
Connection
Recordset
Recordset
Field
Field
QueryDef
Command
Parameter
Parameter
Error
Error
TO
A possible alternative to converting is to implement the data part of the database in one format and implement the client in more than one version of Access. For example, you might implement an Access 97 client and an Access 2002 client and connect to an external Access 97 database containing tables and queries only. This is probably a less pragmatic approach then simply upgrading users to the new version of Access.
INTRODUCTION
Databases created in versions earlier than 2000 can be used in 2002, but Objects can not be modified. If you convert an older database to 2002, then you cannot use the database in the older version of Access. These requirements suggest that you should only convert when all users have upgraded to the new version of Access.
6 ACTIVEX DATA OBJECTS
If all of your users have upgraded to Access 2000 or 2002, you will want to convert your database to Access 2002. Access 2000 databases must be converted to the 2002 format if you want to save the file in the .MDE or .ADE (compiled files and source code removed formats), but otherwise you can leave an existing database in the 2000 format.
145
146
Data Access PART II
Summary ActiveX Data Objects is the wave of the future! Microsoft has made available an OLE DB Provider for Access and is very committed to moving you from DAO to ADO. Proof of this is that ADO is the default database access method when you start a new Access 2002 project. This chapter gave you a good enough introduction to ADO to get you started. Future chapters include more in-depth coverage of ADO.
CHAPTER 7
Advanced ADO
IN THIS CHAPTER • Using the OLE DB Provider for Jet in Access 2002 148 • Accessing Non-Relational Data with ADO 157 • Advanced Data Manipulation with ADO 162 • Data Definition with ADOX
167
148
Data Access PART II
Now that you have seen how to use ADO and viewed it side by side with DAO, take a look at some of the features of ADO that will help you develop Access 2002 applications.
Using the OLE DB Provider for Jet in Access 2002 When you use ADO in your Access application, you will probably be using the OLE DB Provider for Jet. (Using the OLE DB Provider for SQL Server is discussed in Chapter 15, “Introducing Access Data Projects and the Visual Tools.”) The OLE DB provider will let you talk to Access MDB files directly. The capability to talk directly to the data source of your choice, via a provider, is a giant step for ADO. To use the OLE DB Provider for Jet, you have to supply the provider name and full path to the database as part of the connection string. To keep things more readable, ADO has a Provider property that you can set to use Jet’s Provider. Jet’s Provider’s unique CLASSID to use in the connection string is: Microsoft.Jet.OLEDB.4.0. The following is an example of how to open a connection to a Microsoft Access database using the Jet OLE DB provider: Dim Connection As ADODB.Connection Set Connection = New ADODB.Connection Connection.Provider = “Microsoft.Jet.OLEDB.4.0” Connection.ConnectionString = “data source=” & C:\databases\sample.mdb” Connection.Open
If you must specify other connection information, like a database password or workgroup file, append the information to the connection string preceded by a semicolon. Table 7.1 lists the available provider-specific connection properties that can be used in the connection string. Other provider specific connection properties that are in the connection’s properties collection are ignored. TABLE 7.1
The Microsoft Jet OLE DB Provider Specific Connection Property Strings
Name
Description
Compact Reclaimed Space Amount
Approximately the amount of space that can be reclaimed by compacting the database.
Connection Control
Controls user access to the database.
Create System Database
Used to create a system database when a new data source is created.
Advanced ADO CHAPTER 7 TABLE 7.1
149
continued
Description
Database Locking Mode
Scheme to be used when locking the database. For more information see Chapter 21, “Multiple Users and Database Locking.” Note that a database can only be open in one mode at a time. The first user to open the database determines the locking mode used while the database is open.
Database Password
Password used to open the database. This differs from the user password in that the database password is per file, whereas a user password is per user. For more information, see Chapter 21.
Don’t Copy Locale on Compact
Used to control copying locale information on compact.
Encrypt Database
Used to control whether database is encrypted on compact.
Engine Type
An enumeration defining the storage engine currently in use to access this database.
Exclusive Asynch Delay
Indicates maximum length of asynchronous write delay.
Flush Transaction Timeout
Indicates wait period before asynchronous writes are written to disk.
Global Bulk Transactions
Determines whether SQL bulk operations are transacted. This property determines the default for all operations in the current connection.
Global Partial Bulk Ops
This property determines the behavior of Jet when SQL DML bulk operations fail. It can be overridden on a per-rowset basis by setting the Jet OLEDB:Partial Bulk Ops property.
Implicit Commit Synch
Determines whether internal implicit transactions are written synchronously or asynchronously.
Lock Delay
Delay in milliseconds before attempting to reacquire a failed lock.
Lock Retry
Indicates number of attempts to acquire a lock.
Max Buffer Size
Maximum memory buffer available before Jet writes to disk.
7 ADVANCED ADO
Name
150
Data Access PART II TABLE 7.1
continued
Name
Description
Max Locks Per File
Maximum number of database locks. The default is 9500.
New Database Password
Sets new database password.
ODBC Command Time Out
Number of milliseconds before a remote ODBC command times out.
Page Locks to Table Lock
Indicates number of page locks allowed before the locks are promoted to table locks.
Page Timeout
Wait in milliseconds before database is checked to determine whether cache is out of date.
Recycle Long-Valued Pages
Determines if BLOB pages are reclaimed aggressively.
Registry Path
Path to the registry key to use for Jet information. This does not include the HKEY_LOCAL_MACHINE tag. This value can be changed to a secondary location to store registry values for a particular application that are not shared with other applications that use Jet on the machine. For example, the setting for Access 2002 is SOFTWARE\Microsoft\Office\9.0\Access\Jet\4.0\ Engines
Reset ISAM Stats
Indicates whether performance counters should be reset after fetch.
Shared Asynch Delay
Indicates millisecond asynchronous write delay when database is opened in multi-user mode.
System database
Location of the Jet system database to use for authenticating users. This overrides the value set in the registry or the corresponding systemdb registry key used when Jet OLEDB:Registry Path is used. This can include the path to the file.
Transaction Commit Mode
Indicates asynchronous or synchronous writes on commit.
User Commit Sync
Indicates whether transaction changes are written synchronously or asynchronously.
In addition to the properties listed in the table above, the Microsoft Jet database engine exposes a number of settable options that will dictate how the engine will behave. These
Advanced ADO CHAPTER 7
151
options often have a direct impact on performance. By default, when the Jet engine is initialized, it uses the values set in the registry under the \HKEY_LOCAL_MACHINES\ Software\Microsoft\Jet key. At runtime, it is possible to temporarily override these settings. In ADO, these values are set as part of the connection string. The connection string constants are shown in Table 7.2. TABLE 7.2
ADO Connection String Options
ADO
Constant
Property
dbPageTimeout
Jet OLEDB:Page Timeout
dbSharedAsyncDelay
Jet OLEDB:Shared Async Delay
dbExclusiveAsyncDelay
Jet OLEDB:Exclusive Async Delay
dbLockRetry
Jet OLEDB:Lock Retry
dbUserCommitSync
Jet OLEDB:User Commit Sync
dbImplicitCommitSync
Jet OLEDB:Implicit Commit Sync
dbMaxBufferSize
Jet OLEDB:Max Buffer Size
dbMaxLocksPerFile
Jet OLEDB:Max Locks Per File
dbLockDelay
Jet OLEDB:Lock Delay
dbRecycleLVs
Jet OLEDB:Recycle Long-Valued Pages
dbFlushTransactionTimeout
Jet OLEDB:Flush Transaction Timeout
The following code example opens a secured database, specifying a database password and workgroup file: Dim Connection As ADODB.Connection Set Connection = New ADODB.Connection Connection.Provider = “Microsoft.Jet.OLEDB.4.0” Connection.ConnectionString = “data source=” C:\databases\sample.mdb” & _ “;Jet OLEDB:Database Password=supersecret;Jet OLEDB:System database=” & _ “c:\windows\system\system.mdw” Connection.Open
CurrentProject.Connection When you want to access the current database via ADO code, Access 2002 provides a shortcut. It provides a global reference to an ADO Connection object via CurrentProject.Connection. You can use the CurrentProject.Connection anywhere you need a Connection object referring to the database in which the code is running.
7 ADVANCED ADO
DAO
152
Data Access PART II
For example, CurrentProject.Connection can be used to open a Recordset in the current project, as demonstrated: Dim Recordset As ADODB.Recordset Set Recordset = New ADODB.Recordset Recordset.Open “Customers”, CurrentProject.Connection
Caution Be careful using CurrentProject.Connection because it is not portable to any development environment other than Access 2002. If you plan on reusing your code in an application other than Access (like Visual Basic), you must use the long syntax for creating a connection.
Using Microsoft Data Links to Connect to a Database Now that ADO is the primary way to access data, Microsoft realizes that developers need a standardized way to persist, load, and manage OLE DB connection information, much like the old ODBC driver manager and administrator did for ODBC. Microsoft Universal Data Links (UDL) provides you with this capability. UDLs give you the opportunity to save connection information to an UDL file and then enable you to open a connection object in ADO based on the information saved in the UDL file. This will come in handy if you want to test a database connection at a different site without changing any code. The Microsoft Universal Data Links consist of • A graphical user interface to create an OLE DB connection • Automation interface Before you can use a UDL in your VB or VBA application, you must first create one. To create a UDL file, open Explorer, right-click in the folder that you want to create the Data Link file in and select New, Text Document. Type a filename with a .UDL extensions (see Figure 7.1). After you create the UDL file, double-click the empty UDL file you just created to edit it. The first screen shown in Figure 7.2 lists all the OLE DB Providers installed on your system. Choose the provider that you want to use and click Next to go to the Connection tab of the UDL dialog. The Connection tab will let you set your provider-specific connection information as shown in Figure 7.3. Here you are using the OLE DB Provider for Jet, so you have to provide the database path, user ID, and password. (If you are using
Advanced ADO CHAPTER 7
153
the OLE DB Provider for SQL Server, you will have to specify the server and database name.) The next tab, called Advanced, is used to set provider-specific properties that are usually set for you by default like CommandTimeout. The last page All summarizes all the connection properties for you. FIGURE 7.1 Creating a new UDL file.
7 ADVANCED ADO
FIGURE 7.2 Choosing an OLE DB Provider.
154
Data Access PART II
FIGURE 7.3 Entering the connection information.
Now that your UDL file is created, you can use it from your VBA code to open a Connection object in ADO. The syntax is simple—just create a Connection object as you normally would and use the open method. Just use the File Name identifier in your connection string and point to the UDL file as shown here: Dim Connection As ADODB.Connection Set Connection = New ADODB.Connection Connection.Open “File Name=c:\temp\biblio.udl;”
The code in Listing 7.1, available on the chapter07.mdb file on the CD-ROM accompanying this book, shows you how to open a Connection object based on a UDL file located in the application’s directory to the Biblio database. You connect to the database and fill a list box with the contents of the Customers table. What is great about this code is that if you want to use the SQL Server 7.0 version of Biblio, all you have to do is change the UDL file’s properties and then rerun the code. LISTING 7.1
Using UDLs in Your VBA Code
Private Sub OpenViaLink() On Error GoTo Except Dim Connection As ADODB.Connection Set Connection = New ADODB.Connection Connection.Open “File Name=c:\temp\biblio.udl;”
Advanced ADO CHAPTER 7 LISTING 7.1
155
continued
Dim Recordset As ADODB.Recordset Set Recordset = New ADODB.Recordset Recordset.Open “Select * From Publishers”, Connection Do Until Recordset.EOF Debug.Print Recordset.Fields(1) Recordset.MoveNext Loop Recordset.Close Set Recordset = Nothing
Except: MsgBox Err.Description End Sub
Managing Data Links To edit a UDL file, double-click it in Windows Explorer or click Start, Run and type the name, including the full path, of the UDL file (see Figure 7.4). FIGURE 7.4 Double-click the UDL to run the Data Link Properties Applet shown.
ADVANCED ADO
Connection.Close Set Connection = Nothing Exit Sub
7
156
Data Access PART II
Programmatic Managing of UDLs Because UDLs expose their own Automation Interface, you can manage and control UDLs programmatically. To use UDLs in your VBA code, set a reference to the type library called Microsoft OLE DB Service Component 1.0 Type Library (as shown in Figure 7.5). FIGURE 7.5 Setting a reference to the called Microsoft OLE DB Service Component 1.0 Type Library.
After you have a reference to the library set, you can start managing UDLs. In addition, you can prompt a user at runtime for OLE DB connection information via the UDL Dialogs. This can come in handy in prototype applications or product demos to users who are familiar with Microsoft Data Links. You can do this with the PromptNew method of the DataLinks object. The code in Listing 7.2 prompts a user for OLE DB connection information via the UDL dialog and then connects to the database and opens a recordset. LISTING 7.2
Programmatic UDLs
Private Sub OpenUDLDialog() On Error GoTo Except Dim UDL As MSDASC.DataLinks Set UDL = New MSDASC.DataLinks Dim Connect As String Connect = UDL.PromptNew Dim Recordset As ADODB.Recordset Set Recordset = New ADODB.Recordset ‘ Assumes user selected Biblio.mdb sample database
Advanced ADO CHAPTER 7 LISTING 7.2
157
continued
Recordset.Open “Select * From Publishers”, Connect MsgBox Recordset.Fields(1) Exit Sub Except: MsgBox Err.Description End Sub
In addition to using Microsoft Access to communicate with non-relational data like Excel, as shown in Chapter 6, “Introduction to ActiveX Data Objects,” ADO has some advanced features that enable you to work with non-relational data with ease. You will look at • The Jet User Roster • Creatable recordsets • Data shaping
The Jet User Roster The OLE DB Provider for Microsoft Jet will enable you to open a recordset filled with the names of the current users logged into the database that you specify in the connection. This replaces the need to use the LDBView utility that shipped with prior versions of Jet. The code in Listing 7.3 shows you how to open a recordset filled with all the current users in the database. Listing 7.3 will use the OpenSchema method of the Connection object with a JET/JOLT specific parameter. Notice that ADO does not support any constants for you. You have to supply the very ugly GUID value: “{947bb1025d43-11d1-bdbf-00c04fb92675}”). Hopefully in the future ADO will provide a constant for you to use. LISTING 7.3
Using the User Roster
Sub UserRoster() On Error GoTo Except Dim Connection As ADODB.Connection Set Connection = New ADODB.Connection Connection.Provider = “Microsoft.Jet.OLEDB.4.0”
7 ADVANCED ADO
Accessing Non-Relational Data with ADO
158
Data Access PART II LISTING 7.3
continued
Connection.ConnectionString = “file name=c:\temp\biblio.udl” Connection.Open Dim Recordset As ADODB.Recordset Set Recordset = Connection.OpenSchema(adSchemaProviderSpecific, , _ “{947bb102-5d43-11d1-bdbf-00c04fb92675}”) Do Until Recordset.EOF Debug.Print Recordset!COMPUTER_NAME Debug.Print Recordset!LOGIN_NAME Debug.Print Recordset!CONNECTED Debug.Print Recordset!SUSPECT_STATE Recordset.MoveNext Loop Exit Sub Except: MsgBox Err.Description End Sub
Creatable Recordsets ADO gives you the opportunity to create recordsets “out of thin air.” You now can use the Fields.Append method and the AddNew method to add fields and data to your recordset. This is a great technique for creating procedures that will grab information from nonrelational data locations, such as a file directory, and then return a recordset to the calling procedure. Using ADO, your application can always deal with recordsets, and your applications are easier to code. The following example shows you how to create a recordset filled with filenames in a given directory. If you wrap this code in a class module, you can use it in many applications. For example, I use it to read all the ZIP files on FTP server’s directory and iterate through them to create a download page. The advantage of this technique over the NT Active Directory OLE DB Provider is that it is available now and will run under Windows 95. Listing 7.4 demonstrates how to open a recordset based on a listing of filenames in a directory. LISTING 7.4
Creating a Recordset from Non-Relational Data
Sub CreatableRecordset(Optional Path As String = “C:\temp”) On Error GoTo Except Dim Recordset As ADODB.Recordset Set Recordset = New ADODB.Recordset
Advanced ADO CHAPTER 7 LISTING 7.4
159
continued
Recordset.CursorLocation = adUseClient Recordset.Fields.Append “FileName”, adVarChar, 255, adFldRowID Recordset.Fields.Append “Extension”, adChar, 3, adFldFixed Recordset.Open , , adOpenStatic, adLockBatchOptimistic If Right(Path, 1) <> “\” Then Path = Path & “\” Path = Dir(Path & “*.*”, vbNormal) Do While Path > “”
Path = Dir Loop Recordset.MoveFirst Do Until Recordset.EOF Debug.Print Recordset!FileName Recordset.MoveNext Loop Exit Sub Except: MsgBox Err.Description End Sub
Data Shaping The ability to view your data in a hierarchical fashion is very easy with ADO. You can use a new ADO feature called Data Shaping to view parent and child records in just one recordset. You can use the MSDataShape OLE DB Provider to create relationship-based hierarchies and grouping hierarchies. Creating these types of hierarchical recordsets can ease the development burden for hierarchical data. For example, in Figure 7.6, you can see a group hierarchy of all customers’ orders in Northwind viewed in the new Microsoft Hierarchical FlexGrid (an OLAP version of the popular FlexGrid). This control is provided with the Office 2002, Developer Edition, or Visual Basic 6. (Our figures and listings here are in VB 6 using an Access database as the data source.) Notice the plus sign at each record. This gives you the opportunity to expand and collapse each record to view its detail as shown in Figure 7.7. Before the MSDataShape OLE DB Provider, a lot of code was needed to get a grid to behave like this.
7 ADVANCED ADO
Recordset.AddNew Array(“FileName”, “Extension”), _ Array(Path, Right(Path, 3))
160
Data Access PART II
FIGURE 7.6 An MSDataShape OLE DB Provider recordset in VB.
FIGURE 7.7 A GroupBy recordset in VB.
LISTING 7.5
Creating an OLAP Recordset and Filling the MSHFlexGrid in VB 6
Sub CubeGroupHierarchy() Dim ConnectionString As String ConnectionString = “Provider=MSDataShape;” & _ “data provider=Microsoft.Jet.OLEDB.4.0;” & _ “data source=” & App.Path & “\sample.mdb” Dim Recordset As ADODB.Recordset Set Recordset = New ADODB.Recordset Recordset.Source = _ “shape {Select customerid, Region from Customers} rst1 “ & _ “COMPUTE COUNT (rst1.customerid) AS CustCount, rst1 By Region “ Recordset.Open , ConnectionString Set frmADO.MSHFlexGrid1.Recordset = Recordset End Sub
As you can see from the code example, you have to use special Data Shaping SQL syntax. For a complete listing of how to use this syntax, check out the MSDN books online that ship with Visual Basic 6/ODE 2002 or the great ADO documentation on the Web at http://www.microsoft.com/data.
Advanced ADO CHAPTER 7
161
You can also take this code for Data Shaping and bring the data into Microsoft Excel. The code in Listing 7.6 shows you how to take the prior example and dump the data into an Excel Spreadsheet. LISTING 7.6
Using Data Shaping with Microsoft Excel
Function GetDatabase() As String ‘ Change this function to return the ‘ path where you copied the sample files GetDatabase = “C:\temp\sample.mdb” End Function
Dim Recordset As ADODB.Recordset Set Recordset = New ADODB.Recordset Dim ConnectionString As String ConnectionString = _ “Provider=MSDataShape;data provider=Microsoft.Jet.OLEDB.4.0” & _ “;data source=” & GetDatabase() Recordset.Source = _ “shape {Select * from customers where Customerid=’ALFKI’} Append “ & _ “({Select * From Orders} As rsOrders “ & _ “RELATE customerid to customerid)” Recordset.ActiveConnection = ConnectionString Recordset.Open , , adOpenStatic, adLockBatchOptimistic ShowRecordset Recordset
End Sub Sub ShowRecordset(ByVal Recordset As ADODB.Recordset, _ Optional SkipClear As Boolean = False) Dim Dim Dim Dim
Child As ADODB.Recordset Col As ADODB.Field CurrentColumn As Integer CurrentRow As Integer
If Not SkipClear Then Cells.Select Selection.ClearContents End If
ADVANCED ADO
Sub CUBRelation()
7
162
Data Access PART II LISTING 7.6
continued
Do Until Recordset.EOF CurrentColumn = CurrentColumn + 1 If Not SkipClear Then CurrentRow = 1 Else CurrentRow = 2 End If
For Each Col In Recordset.Fields If Col.Type <> adChapter Then Cells(CurrentColumn, CurrentRow) = _ Col.Name & “: “ & Col.Value Else Set Child = Col.Value ShowRecordset Child, True End If CurrentRow = CurrentRow + 1 Next Recordset.MoveNext Loop Cells(1, 1).Select End Sub
Advanced Data Manipulation with ADO The last chapter showed you how to open up recordsets filled with data and execute Command objects. This section will show you some additional tips and tricks with ADO. We will look at • Modifying data in a recordset • Persisted recordsets
Modifying Data in a Recordset To modify data in a recordset, all you have to do is move to that record and start editing it. When you move to the next record or call the Update method, your changes will be
Advanced ADO CHAPTER 7
163
saved. This represents an important change from DAO where you had to use the Edit method first, then explicitly call the Update method. The code in Listing 7.7 shows how to edit data. LISTING 7.7
Editing Records
Sub EditRecords() On Error GoTo Except Dim Recordset As ADODB.Recordset Set Recordset = New ADODB.Recordset
Recordset.Open SQL, CurrentProject.Connection, _ adOpenKeyset, adLockOptimistic Recordset!Name_First = “New Name” Recordset.Update Recordset.Close Set Recordset = Nothing Exit Sub Except: MsgBox Err.Description End Sub
Tip It is faster to open a recordset based on a SQL statement that restricts the primary key than it is to open the whole table and then search for the record that you want.
Caution Because the changes that you make to the recordset are committed without an Update method by moving to the next record, be very careful when editing data.
ADVANCED ADO
Dim SQL As String SQL = “Select * From Customers Where CustomerID=1”
7
164
Data Access PART II
Adding a Record Adding a record is almost the same as editing one. You have to open a recordset and then use the AddNew method. The same rules apply with Update as with an Edit. After you add the record, you will be on the current record. Listing 7.8 shows an example of adding a record to a table. LISTING 7.8
Adding a Record to a Table
Sub AddRecord() On Error GoTo Except Dim Recordset As ADODB.Recordset Set Recordset = New ADODB.Recordset Recordset.Open “Customers”, CurrentProject.Connection, _ adOpenDynamic, adLockOptimistic, adCmdTableDirect Recordset.AddNew ‘ Define an algorithm to generate a unique CustomerID Recordset!CustomerID = 3 Recordset!Name_Pre = “Mr.” Recordset!Name_First = “Paul” Recordset!Name_Last = “Kimmel” Recordset.Update MsgBox “New Customer ID: “ & Recordset!CustomerID Recordset.Close Set Recordset = Nothing Exit Sub Except: MsgBox Err.Description End Sub
You might have noticed that you opened the table with a constant adCmdTableDirect. If you use this constant with an adOpenDynaset cursor type and Optimistic locking, you will map to the old DAO equivalent dbOpenTable. Table 7.3 shows you all the possible options for ADO cursor/lock types and their DAO equivalent. TABLE 7.3
Combinations for Access in ADO
Cursor Type
Lock Type/Options
DAO Equivalent
adOpenForwardOnly
adLockReadOnly
dbOpenSnapShot, dbForwardOnly
adOpenKeySet
adLockReadOnly
No DAO Match
Advanced ADO CHAPTER 7 TABLE 7.3
165
continued
Cursor Type
Lock Type/Options
DAO Equivalent
adOpenKeySet
adLockPessimistic
dbOpenDynaset
adOpenKeySet
adLockOptimistic
dbOpenDynaset
adOpenKeySet
adLockBatchOptimistic
dbOpenDynaset
adOpenStatic
adLockReadOnly
dbOpenDynaset
adOpenDynamic
adLockOptimistic, adCmdTableDirect
dbOpenTable
For those of you who have to support disconnected users, the notion of recordset persistence is just an awesome gift from Redmond. Now you have the capability to save a recordset to disk and then work with it from your VB or VBA application. Then later, you can resync it to the database. To accomplish this, open an ADO recordset with the adLockBatchOptimistic lock type specified and using a client cursor. Then use the save method of the recordset object. You have to specify a filename and save format type. ADO gives you these options: •
adPersistADTG
•
adPersistXML
If you chose to save to the adPersistADTG or adPersistXML format, you can easily open it up later in ADO. Listing 7.9 shows you how to open a recordset, change a record, save the recordset to file, reopen it, and resync it with the database. LISTING 7.9 Saving a Recordset to Disk, Opening It Again, and Resyncing with the Original Database Sub Persist() On Error GoTo Except Dim SQL As String Dim Msg As String Dim NewValue As String
SQL = “Select * From Customers Where CustomerID=’ALFKI’” Dim Connection As ADODB.Connection Set Connection = New ADODB.Connection
ADVANCED ADO
Persisted Recordsets
7
166
Data Access PART II LISTING 7.9
continued
Connection.Provider = “Microsoft.Jet.OLEDB.3.51” Connection.ConnectionString = “data source=” & _ App.Path & “\sample.mdb” Connection.Open Dim Recordset As ADODB.Recordset Set Recordset = New ADODB.Recordset Recordset.CursorLocation = adUseClient Recordset.Open SQL, _ Connection, adOpenStatic, adLockBatchOptimistic Msg = “Please Enter in a new CompanyName for: “ & _ Recordset!CompanyName & vbNewLine & _ “This CustomerID=” & Recordset!CustomerID NewValue = InputBox(Msg) Recordset.Update “CompanyName”, NewValue On Error Resume Next Kill App.Path & “\hcado.dat” On Error GoTo Except Recordset.Save App.Path & “\hcado.dat”, adPersistADTG Recordset.Close Set Recordset = Nothing MsgBox “Saved to: “ & App.Path & “\hcado.dat”, vbInformation Exit Sub Except: MsgBox Err.Description End Sub Sub Resynch() On Error GoTo Except Dim SQL As String SQL = “Select * From Customers Where CustomerID=’ALFKI’” Dim Recordset As ADODB.Recordset Set Recordset = New ADODB.Recordset ‘ Open the recordset pesisted to file
Advanced ADO CHAPTER 7 LISTING 7.9
167
continued
Recordset.Open App.Path & “\hcado.dat”, , _ adOpenStatic, adLockBatchOptimistic, adCmdFile Dim Msg As String Msg = “Value in DataSource: “ & _ Recordset!CompanyName.OriginalValue Msg = Msg & vbNewLine & _ “Value on Disk
: “ & Recordset!CompanyName
MsgBox Msg, vbInformation, “Original Value vs Saved on Disk”
Recordset.ActiveConnection = Connection Recordset.UpdateBatch MsgBox “Database Re-Synced!”, vbInformation Exit Sub Except: MsgBox Err.Description End Sub
Data Definition with ADOX With ADO, you can easily perform data definition. To create and modify tables, queries, and other data objects like indices, you have to use a special ADO Library called ADOX. To use ADOX, you have to set a reference to Microsoft ADO Ext. 2.5 For DDL and Security from Tools, References in the VBE, as shown in Figure 7.8. When you have your reference set, you are ready to use ADOX.
The Catalog Object When using ADOX, everything revolves around a catalog object. A catalog represents a database. With Access, all you have to do is set the catalog’s ActiveConnection property to a valid ADO Command object to start working.
ADVANCED ADO
Dim Connection As ADODB.Connection Set Connection = New ADODB.Connection Connection.Provider = “Microsoft.Jet.OLEDB.3.51” Connection.ConnectionString = “data source=” & _ App.Path & “\sample.mdb” Connection.Open
7
168
Data Access PART II
FIGURE 7.8 Microsoft ADO Ext. 2.5 For DDL and Security.
Dim Catalog As New ADOX.Catalog Set Catalog = New ADOX.Catalog ‘Point the Catalog Object to ‘The Current Database Catalog.ActiveConnection = CurrentProject.Connection
Creating a Database To create a new blank database with ADOX, you have to use the Create method of the catalog object and pass it the path of the new database as shown in Listing 7.10. LISTING 7.10
Creating a Database with ADOX
Sub CreateDataBase() On Error GoTo Except Dim Catalog As ADOX.Catalog Set Catalog = New ADOX.Catalog Catalog.Create “Provider=Microsoft.Jet.OLEDB.4.0;” & _ “Data Source=C:\newdb.mdb” MsgBox “Database Created!”, vbInformation Set Catalog = Nothing Exit Sub Except: MsgBox Err.Description End Sub
Advanced ADO CHAPTER 7
169
Creating Tables and Fields To create a table and its fields, you can create an ADOX to it as shown in Listing 7.11. LISTING 7.11
table
object and append columns
Creating Tables and Fields
Sub CreateTable_JOLT40() On Error GoTo Except
Dim Table As ADOX.Table Set Table = New ADOX.Table Table.Name = “Customer_ADO” Table.Columns.Append “CustomerID”, adInteger Table.Columns.Append “Name_Prefix”, adWChar, 25 Table.Columns.Append “Name_First”, adWChar, 25 Table.Columns.Append “Name_Last”, adWChar, 50 Catalog.Tables.Append Table Set Table = Nothing Set Catalog = Nothing Exit Sub Except: MsgBox Err.Description End Sub
Creating a Linked Table To create a linked table in Access, you have to create a table and then not append any fields to it. Then you have to set two properties: •
Jet OLEDB:Link Datasource
•
Jet OLEDB:Remote Table Name
Set Link Datasource to the path of the back end database you want to link to. Set Remote Table Name to the name of the table in the backend database. Listing 7.12 shows a full example.
7 ADVANCED ADO
Dim Catalog As ADOX.Catalog Set Catalog = New ADOX.Catalog Catalog.ActiveConnection = CurrentProject.Connection
170
Data Access PART II LISTING 7.12
Creating a Linked Table
Sub CreateAttachedJetTable() Dim Catalog As ADOX.Catalog Set Catalog = New ADOX.Catalog Catalog.ActiveConnection = CurrentProject.Connection Dim Table As ADOX.Table Set Table = New ADOX.Table Table.Name = “Customers_Linked” Set Table.ParentCatalog = Catalog Table.Properties(“Jet OLEDB:Link Datasource”) = “c:\temp\newdb.mdb” Table.Properties(“Jet OLEDB:Remote Table Name”) = “Customers” Catalog.Tables.Append Table Set Catalog = Nothing Exit Sub Except: MsgBox Err.Description End Sub
Setting a Field’s Properties In ADOX, after you have created a field, you can use the ADOX Column object to set properties specific to your field. You can set a field to be an AutoNumber by setting its AutoIncrement property to True as shown here: Dim Column As ADOX.Column Set Column = Table.Columns(“CustomerID”) Column.Properties(“AutoIncrement”) = True
There are other properties that you can set for a column object. Table 7.4 summarizes them all and maps them to their old DAO equivalent. TABLE 7.4
The Field Object’s Properties
DAO Field
ADOX Column
Property
Value
Property
Value
Attributes
dbAutoIncrField
AutoIncrement
True
Attributes
dbFixedField
ColumnAttributes
adColFixed
Attributes
dbHyperlinkField
Jet OLEDB:Hyperlink
True
Attributes
dbSystemField
Attributes
dbVariableField
ColumnAttributes
Not adColFixed
Advanced ADO CHAPTER 7
171
Creating an Index To create an index in ADOX, you have to use the Key Object. After creating a key object, you have to append a field to it and then specify whether it is going to be primary or unique and what sort order to use, as shown here: Set Index = New ADOX.Index Index.Name = “PrimaryKey” Index.Columns.Append “CustomerID” Index.Columns(“CustomerID”).SortOrder = adSortDescending Index.IndexNulls = adIndexNullsDisallow Index.PrimaryKey = True Table.Indexes.Append Index
7
TABLE 7.5
Values for the IndexNulls Property
DAO
ADOX
Description
Required Ignore Nulls
Index Nulls
True or False
True
adIndexNullsAllow
Allows null values in key columns.
True
False
adIndexNullsDisallow
A Null value isn’t allowed in the index field; no index entry added.
False
True
adIndexNullsIgnore
A Null value is allowed in the index field; no index entry added.
False
False
adIndexNullsIgnoreAny
A Null value is allowed in the index field; index entry added.
The code in Listing 7.13 brings all the examples together and creates a table, AutoNumber field, and PrimaryKey index on the table.
ADVANCED ADO
By default, the IndexNulls property is adIndexNullsDisallow, which indicates that Null values aren’t allowed in the index and that no index entry will be added if a field in the index contains Null. Table 7.5 fully describes the acceptable values for the IndexNulls property and also maps them back to their old DAO equivalent.
172
Data Access PART II LISTING 7.13
Creating a Table with an AutoNumber and PrimaryKey
Sub CreateAutoNumberPK() On Error GoTo Except Dim Catalog As ADOX.Catalog Set Catalog = New ADOX.Catalog Catalog.ActiveConnection = CurrentProject.Connection Dim Table As ADOX.Table Set Table = New ADOX.Table Table.Name = “Customer_ADO” Table.ParentCatalog = Catalog Table.Columns.Append “CustomerID”, adInteger Table.Columns(“CustomerID”).Properties(“Autoincrement”) = True Table.Columns.Append “Name_Prefix”, adWChar, 25 Table.Columns.Append “Name_First”, adWChar, 25 Table.Columns.Append “Name_Last”, adWChar, 50 Catalog.Tables.Append Table Dim Index As ADOX.Index Set Index = New ADOX.Index Index.Name = “PrimaryKey” Index.Columns.Append “CustomerID” Index.Columns(“CustomerID”).SortOrder = _ adSortDescending Index.IndexNulls = adIndexNullsDisallow Index.PrimaryKey = True Table.Indexes.Append Index Set Index = Nothing Set Table = Nothing Set Catalog = Nothing Exit Sub Except: MsgBox Err.Description End Sub
Creating Relationships in ADOX To create a relationship in ADOX, you have to create a Key object, append its properties, and append the new key to a table object. Use the following syntax:
Advanced ADO CHAPTER 7
173
Catalog.Tables(“Products”).Keys.Append Key
The code in Listing 7.14 brings this all together and creates a new relationship. LISTING 7.14
Creating a Relationship
Sub CreateForeignKey() On Error GoTo Except
Dim Key As ADOX.Key Set Key = New ADOX.Key Key.Name = “CategoriesProducts” Key.Type = adKeyForeign Key.RelatedTable = “Categories” Key.Columns.Append “CategoryID” Key.Columns(“CategoryID”).RelatedColumn = “CategoryID” Key.UpdateRule = adRICascade Catalog.Tables(“Products”).Keys.Append Key Exit Sub Except: MsgBox Err.Description End Sub
Creating Queries in ADOX To create a query in ADOX, you have to use an empty ADO command object and set its command text. Then append it to the current catalog object as demonstrated: Command.CommandText = “Select * FROM Categories” Catalog.Views.Append “qryCategories”, cmd
When you are referring to a query in Access, you have to remember that Microsoft Jet 4.0 handles all your table, query, and field, and index objects for you. Microsoft Jet defines Access queries as one of two types: • Views • Procedures A view is considered a row-returning, non-parameter query while a procedure is everything else.
7 ADVANCED ADO
Dim Catalog As ADOX.Catalog Set Catalog = New ADOX.Catalog Catalog.ActiveConnection = CurrentProject.Connection
174
Data Access PART II
Creating a View Microsoft Jet will handle the definition of your query for you. So to create a view, just create the query as you would normally via a command object as shown in Listing 7.15. LISTING 7.15
Creating a View in ADOX
Sub CreateView() On Error GoTo Except Dim Command As New ADODB.Command Command.CommandText = “Select * FROM Categories” Dim Catalog As New ADOX.Catalog Catalog.ActiveConnection = CurrentProject.Connection Catalog.Views.Append “qryCategories”, Command Set Catalog = Nothing Exit Sub Except: MsgBox Err.Description End Sub
Creating a Procedure As with a View, creating a procedure is straightforward. Just define your commandtext and append it to the catalog as shown in Listing 7.16. LISTING 7.16
Creating a Procedure
Sub CreateProcedure() On Error GoTo Except Dim Catalog As New ADOX.Catalog Catalog.ActiveConnection = CurrentProject.Connection Dim Command As New ADODB.Command Command.CommandText = “Parameters [@Region] Text;” & _ “Select * from Employees where Region = [@Region]” Catalog.Procedures.Append “Employees By Region”, Command Set Command = Nothing Set Catalog = Nothing Exit Sub
Advanced ADO CHAPTER 7 LISTING 7.16
175
continued
Except: MsgBox Err.Description End Sub
Modifying a Query’s SQL Statement To modify a current query’s SQL statement, you first have to create a command object based on a current query in your database. Then modify its commandtext property and then reset the command as shown in Listing 7.17. Resetting a SQL Statement
Sub ModifyQuerySQL() On Error GoTo Except Dim Catalog As New ADOX.Catalog Catalog.ActiveConnection = CurrentProject.Connection Dim Command As New ADODB.Command Set Command = Catalog.Procedures(“Employees By Region”).Command Command.CommandText = _ “Parameters [forms]![frmOrder]![txtRegion] Text;” & _ “Select * from Employees “ & _ “Where Region = [forms]![frmOrder]![txtRegion] “ Set Catalog.Procedures(“Employees By Region”).Command = Command Set Command = Nothing Set Catalog = Nothing Exit Sub Except: MsgBox Err.Description End Sub
You’ll notice that in the ADO code shown in Listing 7.17, setting the Procedure object’s Command property to the modified Command object saves the changes. If this last step were not included, the changes would not have been persisted to the database. This difference results from the fact that ADO Command objects are designed to be temporary. This is very important because DAO considered Querydefs as permanent objects. You might think that the following ADO code examples are equivalent:
ADVANCED ADO
LISTING 7.17
7
176
Data Access PART II Set Command = Catalog.Procedures(“qryEmployeesRegion “).Command Command.CommandText = “Parameters [@Region] Text;” & _ “Select * from Employees where Region = [@Region]” Set Catalog.Procedures(“qryEmployeesRegion “).Command = Command
and Catalog.Procedures(“qryEmployeesRegion “).CommandText = _ “Parameters [@Region] Text;” & _ “Select * from Employees where Region = [@Region] “
Although they look like they will do the same thing, the second piece of code will not actually update the query in the database. In the second example, you can use the command object with its new SQL in your VBA code; however, when you are done working with it, the SQL changes will not be saved back to the database. In the first example, because you are explicitly saving the Command, the changes will be reflected in the database.
Summary This chapter covered a lot of ground on ADO and ADOX. As you can see, ADO and ADOX are fully featured, flexible, and very powerful. ADO and ADOX are a great new data access technology, as you will see in Chapter 15. ADO is just as easy to use with SQL Server as it is with Access. I hope you can take these examples and begin to build great Access applications around ADO and ADOX.
User Interfaces Unleashed
PART
III IN THIS PART 8 Advanced Form Design 9 Enhancing Forms with ActiveX Controls 10 Reporting Unleashed
CHAPTER 8
Advanced Form Design
IN THIS CHAPTER • Form Properties
180
• Access Form Controls
189
• Creating PivotTable and PivotChart Views 197
180
User Interfaces Unleashed PART II
Forms will make or break your application. This is true not because forms are necessarily the heart of an Access application, but because that is where users spend the most time. To that end, Microsoft has invested a great deal of time and money in making Access forms both simple and powerful. To provide you with as much information on form design as possible within a workable frame, I will focus on some of the form settings and properties that can simplify your development effort and deliver tremendous functionality. I will then look at how to use some of the controls found in Access and show you how they can help you develop forms that go beyond mere data entry. By the end of this chapter, you will be able to design forms that provide more functionality to your users, and create forms that are easier to work with and visually appealing. This session starts by looking at the properties and settings in Access 2002. Next, I’ll look at some of the more advanced controls in the Access toolbox, especially the list and combo box controls. I’ll look at the option group and how to use it with command buttons, check boxes, or option buttons. Then I will examine how manipulating subforms can increase the power of your forms without the overhead of multiple pages or numerous extra controls. Finally, I will look at some of the exciting ActiveX controls that ship with the Office 2002 Developer Edition (ODE), how to work these into your applications for even more functionality, and how to create views based on the new PivotTable and PivotChart.
Form Properties Access 2002 forms have dozens of properties for you to choose from (see Figure 8.1). A complete discussion of them would, and has, taken whole sections of how-to books. I’ve pulled out a few properties that can have a significant impact on your work as a developer. For a detailed look at other properties, see Alison Balter’s excellent book Mastering Access 97 Development. FIGURE 8.1 The Form Properties dialog box.
Advanced Form Design CHAPTER 8
181
Data Properties Forms in Access 2002 are closely tied to the data behind them. You can easily create a form and start entering data without writing a single line of code. This type of functionality can be achieved through the use of the data properties, which, as the name suggests, describe the way a form should present and work with data.
RecordSource RecordSource is probably the most used property on a form. The RecordSource allows you to bind your forms to tables, queries, SQL statements, or nothing at all. The property can be set at runtime or at design time, depending on your needs. Note If you do not specify a RecordSource at design time, you cannot bind individual fields on your form to the RecordSource.
8 These properties enable you to restrict the recordset of a bound form by specifying a WHERE clause in the Filter property or a sort order in the Order By property. The Allow Filters property tells Access whether to read these values when the form is opened. Generally, you might not need to use these properties. By using queries in the Record Source property, you can assign parameters and a sort order in one step versus two when you use the Filter and Order By properties. In addition, by using the Record Source property you can take advantage of optimized queries, which run faster.
Allow Edits When Allow Edits is True, users can edit data on a form. When False, users cannot. This is a handy way to quickly make a form read-only.
Allow Deletions When Allow Deletions is True, users can delete records from the form. You can use Allow Deletions to control which users can or cannot delete records from your database.
ADVANCED FORM DESIGN
Allow Filters, Filter, Order By
182
User Interfaces Unleashed PART II
Allow Additions When set to False, users cannot add new records to your database. Allow Additions is handy when you are displaying the results of a query in Datasheet mode but don’t want your users to add new records at the end of the result set.
Data Entry Setting the Data Entry property to True will restrict your users from seeing existing data, but will enable them to add new records.
Format Properties Forms are referred to as the presentation layer. The presentation layer is the part of the application that users see and interact with. The very important first impression about your application comes from the forms. The way they look, behave, and make their daily tasks easier (or harder) is very important to users and to you, the developer. Setting the formatting properties is a way to control the look and feel of your forms.
Default View Setting this property tells Access how to open the form. Your choices are • Single Form: Displays one record at a time. • Continuous Form: Displays multiple records, each with its own copy of the form in the form’s detail section. • Datasheet: Displays the data in rows and columns like a spreadsheet. • PivotTable: Displays data using a PivotTable. • PivotChart: Displays data using a PivotChart.
Choosing Allowable Views By setting this property, you can restrict the number of ways users can view your data at runtime. This can be useful if you only want users to see one record at a time, or only want the data presented in Datasheet view. Your choices are • Form • Datasheet • PivotTable • PivotChart
Advanced Form Design CHAPTER 8
183
Scrollbars The Scrollbars property on the Format tab of the Properties window, showing Form properties, enables you to indicate whether the form can display scrollbars. You can choose between vertical, horizontal, both vertical and horizontal, or no scrollbars. The default setting is Both, allowing forms to use more space than might be visible on the physical display.
Record Selectors By default Record Selectors is True. A Record Selector is a bar to the left of the record that the user can click to select all of the fields in a record in Datasheet or Form view.
Navigation Buttons By default Navigation Buttons is True. Navigation Buttons are the controls placed at the bottom of a form view that allow you to navigate between records, view the current and total number of records, and insert a new record.
Border Style Access forms can be displayed with a variety of borders, each with a specific purpose:
• Dialog: Fixes the size of the form at runtime. The Minimize and the Maximize buttons are disabled. This setting is great for message boxes and pop-up forms. • Thin: Fixes the size of the forms at runtime. The Minimize and the Maximize buttons are enabled. • None: No border is present. This setting is best for splash screens.
Control Box The Control Box property is a Boolean property that determines if a form menu is available on the upper-left corner of the form and whether or not the Minimize, Maximize, and Close buttons are displayed in the upper-right corner of a form.
Min Max Buttons When set to True, users can minimize or maximize forms on their desktops.
Close Button When set to True, users can use the control menu to close the form.
ADVANCED FORM DESIGN
• Sizeable: Allows users to resize the form at runtime. The control box is enabled with the Minimize and the Maximize buttons enabled.
8
184
User Interfaces Unleashed PART II
Caution If you set this property to False, you must provide another way for your users to exit the form. Otherwise they will have to use Ctrl+F4 to close the form, or Alt+F4. Besides that, the only other way to close the form is to shut down Access.
Other Properties Other Properties are as important as the categorized properties described above. They control a few important aspects of the form’s behavior and act as an “Advanced” set of properties used to put finishing touches on the form. A recent addition to Access forms is the AllowDesignChanges property described later in the chapter.
Modal When this property is set to True, opening the form prevents any other form from receiving the focus until the modal form is closed. This is effective for error messages or critical order of operation functions where the user must complete specific ordered tasks before proceeding to another task.
Pop-up Pop-up forms are child forms of the Access window. This makes them different from non–pop-up forms, which are children of the form in which they are opened. This means that pop-up forms will sit on top of all other forms and can be placed anywhere on the Access desktop. Custom toolbar forms make good pop-up forms.
Menu Bar, Toolbar If you have developed custom menus or toolbars you want associated with a particular form, setting this property will cause that menu or toolbar to appear when the form opens.
Shortcut Menu When set to True, Access will display the menu selected in the Shortcut property whenever the user right-clicks the form.
Menu Bar
Shortcut Menu Bar If you have developed a custom shortcut menu for the form, selecting it here and setting the Shortcut Menu property to True will tell Access to display your menu whenever the user right-clicks the form.
Advanced Form Design CHAPTER 8
185
Tag This property can be used to store any value you want. You can get at it from anywhere in your application and it will be saved with the form.
Has Module When set to False, Access will remove all code written behind the form. This “lightweight” form loads very fast. Caution If you have code behind a form and you set the Has Module property to False, all your code will be deleted. Access warns you of this fact.
FIGURE 8.2 Edit Hyperlink Properties dialog box.
Allow Design Changes Setting this property to All Views keeps the Form Properties dialog box open while the form is running, allowing you to modify changes and see them “live” in your application. Do not forget to set it back to Design View Only when you are done.
8 ADVANCED FORM DESIGN
If a form contains no code behind it, definitely set this property to True. You will eliminate an overhead of Access attempting to compile the form on each load. A limited extra functionality can still be achieved without writing code by inserting a hyperlink (described later in this chapter) onto the form in Design view and linking it to an object in a database (see Figure 8.2).
186
User Interfaces Unleashed PART II
Useful Properties Not Found in the Properties Window As always, things hidden are more interesting to us than those that are evident. The same applies to the hidden form properties. In this case, hidden properties provide extra convenience in developing complex form-driven applications with Access.
OpenArgs This property is only available at runtime. With OpenArgs, you can pass a string value from one form and have another form read that value in. Docmd.OpenForm “MyForm”, “some string value” Dim X As String If Not IsNull(OpenArgs) Then X = OpenArgs End If
The OpenArgs property is useful when you are using modal forms to gather required information. If you want to format a form in a slightly different way, depending on the logic of your program, you can use OpenArgs to send a “message” to the form and pick it up on the Form_Open event. Inside the event, you can format your form to look differently or even prevent it from scrolling from record to record to concentrate on the one record you must edit.
User-Defined Properties In the general declarations section of a form, declaring a variable as public or private will introduce a user-defined field. In order for the property to be accessible from other modules, you must declare the field as a Public field. If you need to make a field available to other forms, or would like to add validation when retrieving or setting this value, you can use Property Get and Property Let methods to provide access to the field and perform validation. For example, suppose you are writing a driver’s license processing application and one of the requirements is that the driver’s age must be at least 16. You could write the following property validation to handle the reading/writing of the property. In general declarations: Private FAge As Integer Public Property Let Age(ByVal Value As Integer) If( Value < 16 ) Then Err.Raise vbObjectError, _
Advanced Form Design CHAPTER 8
187
“Age must be greater than 15 years” End If FAge = Value End Property
Note A brief note on style. I prefer an F-prefix to indicate a field and drop the F for a matching property name. The parameter for a property Let or property Set method is always Value. Again, these are conventions I employ because they are easy to remember and allow me to program faster. Probably the most important thing regarding styles is simplicity and consistency. Simplicity lends itself to speed and consistency aids in a uniform, professional appearance.
Use this code to add a Property your form.
Get
statement to make your value available outside
When you want to see the property you created in an IntelliSense drop-down box (as you are coding it), you must declare a form variable as type FormName As Form.
Events Access has more than 30 events to help you control program flow. It is helpful to understand in what order events fire. The following indicates the order events fire under different circumstances. Some of the events pass the Cancel parameter, which can be set to True if you want to stop opening or closing the form. The Windows operating system is an event-driven operating system. Events are occurrences. These occurrences might be caused by something the user does, such as tapping a key on the keyboard or moving the mouse, or something that occurs internally in the computer, like the Timer ticking or the screen being repainted. In the subsections that follow are examples of actions the user might take and an ordered list of events that occur when the action is taken.
Form Open When a form is opened, the following ordered events occur:
8 ADVANCED FORM DESIGN
Public Property Get Age() as Integer Age = FAge End Property
188
User Interfaces Unleashed PART II
1. Open 2. Load 3. Resize 4. Activate 5. Current 6. Enter event occurs for first control, the control having TabIndex 0 7. GotFocus occurs once the TabIndex 0 control has the input focus Note If there are no controls on the form, the form itself will receive the focus.
If a form has a subform, the subform’s events are raised before the parent form’s events. (The same events in the same order are raised for subforms.) By initializing the subform first, you assure that the subform is properly initialized and ready to be used by the parent form before code in the parent form begins to execute.
Form Close As a form closes, the following events fire in the order described below. 1. Unload 2. Deactivate 3. Close
Form Resize As the form is resized, the following events fire in the order described below. 1. Resize
Form Maximized As the form is maximized, the following events fire in the order described below. 1. Resize
Minimized Form Restored As the form is restored, the following events fire in the order described below. 1. Resize
Advanced Form Design CHAPTER 8
189
Access Form Controls Access 2002 comes with a variety of built-in controls to aid you in development. Some controls, such as the text box, haven’t changed much since Access 1.0. Others, such as the list box, have had significant changes. In this session, I’ll highlight the capabilities of some of the more interesting controls found in Access.
The Combo Box Control Combo boxes create lists of predefined values that your users can pick from to simplify the task of data entry. Most combo boxes are based on queries or SQL statements and typically have one or two columns and a bound field. Although this is usually enough for most developers, there are some interesting capabilities in Access 2002 combo boxes that can add tremendous functionality.
Using the Not In List Event If you set the LimitToList property to True, the Not In List event is raised whenever a value is entered into a combo box that does not exist in the list of choices. This gives the developer a chance to examine the new value and decide how best to handle it.
8
For example, suppose you provided a combo box of clients, and a user entered a client that was not created yet. Using the following code, you could trap a NotInList error and ask the operator if they wanted to insert the new item.
ADVANCED FORM DESIGN
Function AddSubmitter(ByVal NewData As String) As Boolean Dim Message As String Message = “Submitter “ & NewData & “ not found. “ & _ “Do you want to add a new submitter?” AddSubmitter = MsgBox(Message, vbQuestion + vbYesNo, _ “Submitter Not Found”) = vbYes End Function Private Sub Combo18_NotInList(NewData As String, Response As Integer)
If (AddSubmitter(NewData)) Then MsgBox _ “TODO: Add code to insert new element to submitter table.”, _ vbExclamation Combo18.SetFocus Response = acDataErrContinue
190
User Interfaces Unleashed PART II End If End Sub
Making a Combo Box Drop Down Automatically How many times have you wished you could just tab into a combo box and have the list drop down without having to do a SendKeys command? Since Access 97, calling ActiveControl.DropDown from the Enter event will automatically drop the list of items from a combo box. A complete event handler follows. Private Sub Combo18_Enter() ActiveControl.Dropdown End Sub
Creating Your Own Drop-Down Lists Usually, the values in the drop-down box come from a table or a query. But this is not your only choice. By setting the Row Source Type property to Field List, you can choose to view multiple fields from the underlying table or query. Or you can set the Row Source Type property to the name of the function you create to display a custom list. Defining a custom list might come in handy when you want to allow the user to select a value that might not exist in the source table, for example an All or None choice. Listing 8.1 demonstrates a RowSourceType function that closely approximates what associating the RowSourceType with columns in a database does. LISTING 8.1 Assigning the RowSourceType Property to a Function That Approximates the Default RowSourceType of a Table/Query Value 1: 2: 3: 4: 5: 6: 7: 8: 9: 10: 11: 12: 13: 14: 15: 16: 17: 18:
Private Function GetField(ByVal Field As Long, _ ByVal Row As Long) As Variant On Error GoTo Finally Dim Recordset As New ADODB.Recordset Call Recordset.Open(“Submitter”, CurrentProject.Connection) Call Recordset.Move(Row) GetField = Recordset.Fields(Field).Value Recordset.Close Finally: Set Recordset = Nothing If (Err.Number <> 0) Then GetField = “None” End Function Private Function GetRowCount() As Long
Advanced Form Design CHAPTER 8 LISTING 8.1
191
continued
Assign the GetList to the Row Source Type property for the combo box that you want to provide custom values to (see Figure 8.3). The Row Source Type function must have one Control and four Variant arguments and return a variant. The arguments will be provided by the caller (which is Access). The first argument is the field associated with the combo box control. The second argument, ID, is a unique identifier that indicates the control being filled. The third and fourth arguments represent the row and column of the field value being requested. (You provide the number of rows and columns containing the combo box’s data. In the example, the esoteric GetRowCount function satisfies the acLBGetRowCount request code.)
8 ADVANCED FORM DESIGN
19: GetRowCount = CurrentProject.Connection.Execute( _ 20: “SELECT COUNT(*) FROM SUBMITTER”)(0).Value 21: 22: End Function 23: 24: Private Function GetList(AField As Control, _ 25: ID As Variant, Row As Variant, Column As Variant, _ 26: Code As Variant) As Variant 27: 28: Select Case Code 29: Case acLBInitialize 30: Me.Caption = “acLBInitialize” 31: GetList = ID 32: 33: Case acLBOpen 34: Me.Caption = “acLBOpen” 35: GetList = ID 36: 37: Case acLBGetRowCount 38: GetList = GetRowCount 39: 40: Case acLBGetColumnCount 41: GetList = 2 42: 43: Case acLBGetColumnWidth 44: GetList = -1 45: 46: Case acLBGetValue 47: GetList = GetField(Column, Row) 48: 49: Case acLBEnd 50: ID = 0 51: End Select 52: 53: End Function
192
User Interfaces Unleashed PART II
The fifth argument of GetList indicates what part of the puzzle the combo box is requesting. The combo box will call GetList multiple times to assemble the list. Each time the Code parameter might have a different value, one time requesting a row or column count and another specific values for a field. The code in Listing 8.1 demonstrates the technique substituting a RowSourceType with custom code, but does not represent a good reason for making the replacement. If you need custom variations in the list of elements in a combo box, you might want to define a custom function; otherwise, use a Table or Query value. FIGURE 8.3 Assign the Row Source Type property to a function with a predefined list parameters and you can populate a combo box with custom values.
Retrieving More Than One Value from a Combo or List Box Using the Column property, you can retrieve the value from any column in a combo or list box. The Column property is zero-based, thus the first column is referenced by an index of 0. For example, to read the value from the fourth column of a combo box you would type MsgBox “Submitter is: “ & Combo18.Column(3)
List Boxes The List Box control is similar to the Combo Box control described above. The differences include the option to view all the choices without having to drop down the list. And unlike the Combo Box control, List Box allows the selection of multiple values at the same time. This feature is useful when you want to let the user see information about 5 out of 100 entities (invoices, people, CDs, or trucks) in the system you are building. Because most of the features applied to the List Box control have been discussed already, I will concentrate on the differences.
Advanced Form Design CHAPTER 8
193
The Multi-Select List Box Control In Access 2, several tricks were devised to allow users to select several values from a list. Starting with Access 97, picking multiple values is easy with the Multi-Select List Box. However, retrieving the values selected is not quite as intuitive.
Property Settings To use the Multi-Select List Box you must first set a standard list box to become a MultiSelect List. You do this by changing the Multi Select property in the control’s property sheet. Your choices are shown in Table 8.1. TABLE 8.1
Multi-Select Property Choices
Meaning
None
Multiple selection isn’t allowed.
Simple
Multiple items are selected or deselected by clicking them with the mouse or pressing the Spacebar.
Extended
Multiple items are selected by holding down Shift and clicking them with the mouse or by holding down Shift and pressing an arrow key to extend the selection from the previously selected item to the current item. You can also select items by dragging with the mouse. Holding down Ctrl and clicking an item selects or deselects that item.
To read the values out, you’ll need to write a little code. For example, to read the values out the list of languages (in the chapter98.mdb example database), you could write the following code: Public Sub Iterate() Dim Elem As Variant For Each Elem In List0.ItemsSelected Debug.Print List0.Column(0, Elem) Next End Sub
The code reads the values from column one by selecting only those values whose indexes are in the ItemsSelected collection.
8 ADVANCED FORM DESIGN
Value
194
User Interfaces Unleashed PART II
Subforms Subforms have always provided a great way to show data in one to many relationships. By using the Link Master and Link Child Fields, developers can quickly tie related data together. Subforms also have another powerful feature. By changing the ControlSource property, developers can insert an unlimited number of subforms into the same main form. By using this technique, developers can create their own container objects, something Visual Basic developers have been able to do for quite a while. Containers allow you to refer to controls by a group reference. Additionally, subforms are a great way to get around the 22-inch length limit in Access forms. Subforms also let your forms load faster because they will not have to load every potential form, list, or memo field a user might need. Developers can control how data is presented and limit the number of graphics or other resource-intensive forms.
Adding Subforms There are three ways to add a subform to an existing form: • Select the subform control from the form design toolbox and drag it onto your main form. This creates a blank subform. You must then add a Control Source and set the Link Child and Link Master fields as needed. • The second way is even simpler. Open your main form in Design view then go out to the database window. With both the Design view of your main form and the database window visible, drag the form you want to use as your subform from the database window to your main form. Access will attempt to link the parent and child fields and set the Record Source for you. Access will also size the subform so that it fits correctly, which can be a real headache for developers who do it manually. • Use the Subform Wizard that comes with Access. Note The default state for the wizards is on. To enable or disable the wizards, click the Wizard button located at the top of the toolbox (see Figure 8.4).
Advanced Form Design CHAPTER 8
195
FIGURE 8.4 The ToolBox with the Control Wizards button clicked ON.
Referencing a Subform There are several ways to reference a control on a subform. The typical syntax is Forms!MyForm!SubFormControlName.Form!ControlName
Access 2002 has improved on this rather lengthy and tedious method because the controls collection is the default collection for the form. Now you can reference the same object this way:
or Me!MyForm!SubFormControlName!ControlName
Either way you do it, it will work. Using the expression builder (Ctrl+F2) is a great way to make sure you get the syntax right.
Built-In Tab Control Another way for developers to group controls and preserve resources is by using tab controls. Access 2002 ships with an excellent tab control built right in.
Option Group The Option Group control allows you to place radio buttons, check boxes, or command buttons (toggle buttons) within the object frame, and then reference each object by its index value. You can turn the visible property of all controls within the frame on or off with one command instead of five or six, and you can use the For Each command to run through the values in the Option Group instead of testing each one individually.
ADVANCED FORM DESIGN
Forms!MyForm!SubFormControlName!ControlName
8
196
User Interfaces Unleashed PART II
Pop-up Menus Windows 95 made pop-up menus cool. Most users going back to Windows 3x after using 95 for a while curse their inability to right-click on anything. Pop-up menus provide a great way to shortcut to common tasks or provide specialized, on-time features for various controls. Forms, or even individual controls, can have their own pop-up menus, and with a little bit of code you can modify the look of your command bars on-the-fly. To Create a pop-up menu, right-click any toolbar or menu bar and select Customize. The following demonstrates how to create a custom Popup element from the View menu. 1. Click the View, Toolbars, Customize menu. 2. In the Customize dialog box, with the Toolbar tab in focus, click New. 3. In the New Toolbar dialog box, type a new name for the Toolbar element. 4. Click OK. 5. Back in the Customize dialog box now and still on the Toolbar tab, click the Properties button. 6. The Toolbar Properties dialog box allows you to customize the availability and behavior of the Toolbar element. In Toolbar Properties change the type to Popup. Click Close. 7. In the Customize dialog box, check the Shortcut Menus toolbar. This step will open the Shortcut Menus toolbar. 8. Click the Custom Shortcut Menu. (When you changed the type of your toolbar element to a Popup type, it was relocated to the shortcut menu Customize menu item.) 9. To associate a behavior with the Popup menu item, drag a command from the Customize tab of the Customize dialog box to the Popup menu item you just created. To delete a custom Popup toolbar you will need to open the Customize dialog box. Click the Properties button. From the Toolbar Properties dialog box, change the Selected Toolbar to the name of the Popup you want to delete. Change the type back to Toolbar and close the Toolbar Properties dialog box. Once the control is back in the Customize dialog box you can click the toolbar element followed by the Delete button to remove the toolbar button. Essentially you have to reverse the numbered steps beginning with step 8 and, proceeding backwards to step 1.
Hyperlinks Hyperlinks are great controls that enable users to jump to forms, reports, Excel spreadsheets, Word documents, or even Web pages just by clicking on the hyperlink text. Because there is no code behind them, they are ideal in navigation forms because they
Advanced Form Design CHAPTER 8
197
can be used on lightweight forms (those with Has Module property set to False). A hyperlink is an unattached label (a label without a parent control) with Hyperlink Address or Hyperlink SubAddress property set to anything but Null.
Creating PivotTable and PivotChart Views PivotTables and PivotCharts allow you to display data and allow the user to change the perspective representing the presentation of the data. For example, if you were to use a PivotTable to display sales by employee broken down by sales-quarters, the user could dynamically reorganize the PivotTable and display sales by quarter broken down by employee. The ability to change the data is based on the same dataset. Thus users do not need to know about tables, SQL, or creating forms and reports. All users need to know is how they want to view the data and how to use a mouse.
Creating a PivotTable View A PivotTable view without any data (see Figure 8.5) is basically a blank form. Data is organized by placing a variety of fields on the fields list (View, Field List) into the different regions of the PivotTable. Fields that act as filters on the data are placed at the top of the PivotTable view in the Drop Filter Fields region. Columnar data is orchestrated by placing fields in the Drop Column Fields Here region. And, row data is controlled by the Drop Row Fields Here region. Detail data is placed in the center. The PivotTable can be defined from the Database window, for example, by selecting the Forms object and clicking the New button. From the New dialog box select the AutoForm: PivotTable, select a table name, and click OK. Follow the steps in the wizard to create a form with a PivotTable. You can also double-click a form to open a datasheet and switch to a PivotTable View from the View menu, and manually design your PivotTable. Because you are pretty familiar with wizards by now, we’ll take the long way around and create a PivotTable view using the latter method (selecting a table).
8 ADVANCED FORM DESIGN
The controls themselves were probably challenging to write, but, as with most things in Access, there are wizards making them easy to build solutions with and even easier for users to manipulate the view of the data with. (For the examples in this section, we will return to a copy of the NWIND.MDB [Northwind Trading Company] sample database that ships with Access.)
198
User Interfaces Unleashed PART II
FIGURE 8.5 A PivotTable with defined data regions.
Defining the Columns The example PivotTable view is based on the Order Details and Products tables as defined by the Query Order Details Extended in the Northwind sample database. The query returns the Product Name, Unit Price, Quantity, Discount, and Extended Price. Note You can create the Order Details Extended query by joining the Order Details and Products tables on the ProductID field and adding OrderID, ProductID, ProductName, UnitPrice, Quantity, Discount, and ExtendedPrice in the result set.
To begin creating the PivotTable (we could use the wizard and base it on the query, but I will leave that up to you), double-click the Order Details Extended query from the Database window. Select View, PivotTable to switch to a PivotTable view. Your screen should look very similar to the empty PivotTable in Figure 8.5. (A good benefit of the creating a PivotTable view is that it will forever be associated and available with the query when we are finished.) In our example we will be organizing the order details by ProductName for readability. If the Fields List is not open, select View, Field List to open the field list window. (We will use the Field List window to manage the data displayed on the PivotTable.
Advanced Form Design CHAPTER 8
199
FIGURE 8.6 The PivotTable Field List can be opened from the View menu.
From the Field List, drag the ProductName field to the Drop Column Fields Here section of the PivotTable view. Our columns of data will be constrained by ProductName at this point.
Adding Detail Fields
Creating Sum Results The PivotTable demonstrates the power of components. Once a component is created, that component should be relatively easy to use and customize. Thus far we have a nicely organized view of raw sales figures, but what we want are totals. Totals are easy to create, too. For our example, we will create totals for the average unit price, quantity, and discount. Additionally we will sum the total number of items sold, and calculate the subtotal for each block of items sold, and a grand total per product. First, to calculate the average unit price, quantity per sale, and average discount, we need to use the sum tool button (∑). Calculate and add an average for the Unit Price by clicking on the sub-column header for Unit Price, click the sum tool button and select Average from the drop down menu.
ADVANCED FORM DESIGN
The next thing we need to do is add some data to the detail section. Our PivotTable is showing Order Detail by ProductName, therefore we need to drag each of Unit Price, Quantity, and Discount to the Drop Totals or Details Fields Here region. Your PivotTable view will now contain product names by column and each column will have a list of unit prices, quantity sold, and the discount for each order. (At this juncture your PivotTable should look very close to the finished product in Figure 8.8.) The next step is to create some totals fields.
8
200
User Interfaces Unleashed PART II
Two things will happen after you click Average. First an Average of unit Price will be added to the Fields List under the Totals item (see Figure 8.8) and second, underneath each Unit Price column for each product will be the average Unit Price. Repeat the process to calculate the averages for Quantity and Discount. Calculating the total number of items sold, that is, to sum the quantity, click the Quantity column again and select Sum from the drop-down menu of the ∑ (sum) tool button. Notice that you only have to perform this operation once and each product is updated with the new sum of quantity. We now know a little about average units sold, discounts provided, and the price those units were sold at, but how much money did we get? The following section demonstrates how to create new, calculated fields.
Defining Calculated Fields Creating calculated fields can be accomplished handily by selecting PivotTable, Calculated Totals and Fields from the menu. (The PivotTable menu is only visible if an actual PivotTable has the focus.) In order to calculate how much money we received for each block of units sold, per unit, we need to select PivotTable, Calculated Totals and Fields, Create Calculated Detail Field. This menu operation will display the Properties dialog box (Figure 8.7) focused to the Calculation tab. To define the calculation, you can enter the arithmetic in manually or select the field name and click the insert Reference To button, adding the arithmetic operator manually. The calculation is shown in Figure 8.7. FIGURE 8.7 Calculations can be added to create new, derived fields.
Click the Change button to save the calculation as a new column (shown in Figure 8.8). To achieve the result shown in Figure 8.8, we need to create a sum at the bottom of the column of calculated sales; this will provide us with a total sale by product. And, we will also need to format the calculated fields representing dollar amounts.
Advanced Form Design CHAPTER 8
201
FIGURE 8.8 The finished PivotTable for Order Details from the Northwind Trading Company.
That’s it. With a little practice you will be able to create and experiment with PivotTables quickly. The added benefit is that users—non-programmers—can reorganize the data, change the presentation and layout, export the data to other Office XP applications, and use the PivotTable on Data Access Pages and display the information across a network.
Exporting to Excel Now that you have created the PivotTable, it becomes another view of the data it was based on. Hence, in addition to viewing the order Details query in a datasheet, you switch to the PivotTable view from the View menu or export the data to Excel. Exporting to Excel is simply a matter of selecting PivotTable, Export to Microsoft Excel, and a copy of the PivotTable will be written to an .HTM file and reopened in Excel.
Converting Between PivotCharts and PivotTables PivotTables and PivotCharts are different presentation styles of the same kinds of data. PivotTables are used to present flexible and dynamic cell-based data, and PivotCharts are
8 ADVANCED FORM DESIGN
Create the calculated total per product by clicking on the Calculated header (refer to Figure 8.8) and selecting Sum from the ∑ (sum) tool button. With the column still selected, right-click to display the popup menu and select the Properties menu item. The Format tab will have the focus. To change the format to Currency formatting, select Currency from the combo box labeled Number.
202
User Interfaces Unleashed PART II
designed to present flexible and dynamic graphic based data. Whether you create a PivotTable or PivotChart you can easily switch from one view or the other without making further modifications. Each view style offers additional customizations that will help you enhance the fit and finish, but designing either view is still based on the perspective on the data you are trying to get. Taken in perspective, it is important to remember that PivotTables and PivotCharts are objects. You can experiment with design time and run time properties to create a suitable fit and finish.
Summary Developers spend enormous amounts of development time on form design. Forms are what your users will identify your application with. Professional, intelligent, and easyto-use forms will convey the impression of a professional application. A good form provides an intuitive representation of data, allowing easy navigation among its controls. Keep in mind that although you might be developing on a large 17-inch or 19-inch screen, users might still have 15-inch or even 14-inch monitors. You can develop for the lowest common denominator (640 × 480 resolution) or create a way to resize controls and fonts on your form accordingly. Do not make the form too heavy with code. Remember, Access provides many tools to attach your forms to the data. Making forms bound is an easy way to let Access handle data access and control. If the requirements of your project suggest a remote database with unbound data forms, consider switching your development package to Visual Basic. In the Access 2002 world, you can create some amazing applications. By utilizing the unbound combo box, for example, you can filter the records on the form down to the one you want to see or edit. By adding the “All” option to some of your Combo Boxes, you can open some powerful search options to your users. Or by checking for existence of data on the form’s Open event, you can switch to the Create New Record form in case there is no data to view, edit, or delete.
CHAPTER 9
Enhancing Forms with ActiveX Controls IN THIS CHAPTER • How to Use ActiveX Controls • Using ActiveX Controls • 21 ActiveX Controls
204
206
210
• Distributing ActiveX Controls
238
204
User Interfaces Unleashed PART III
ActiveX controls add and extend functionality to Access applications beyond the capabilities provided by Access alone, making it easier to create and maintain applications. The possibilities are limitless. In this chapter, you will learn about a number of ActiveX controls available today and how to add them to your Access forms. First, I will discuss what ActiveX controls are, where they come from, and other general information.
How to Use ActiveX Controls You are already familiar with built-in controls such as the text box or command button controls that can be placed on Access forms. ActiveX controls work in much the same way, except the code that supports the functionality of the ActiveX control is stored in a separate file that must be installed before it can be used. ActiveX controls enable you to easily incorporate additional functionality that is not already available in Access into your applications. For example, you might want to add a calendar or a grid control to your form. ActiveX controls are generally stored in the Windows/system directory and have a file extension of .OCX or .DLL. ActiveX controls are not part of Access but can be used in Access applications. They run in the same process as the Access application, which provides excellent performance. In this chapter, I will use ActiveX controls on Access forms. However, the same ActiveX controls can be used in Visual Basic applications, Office applications, and even Web applications. Tip Not all ActiveX controls work in all applications. A control that works well in Visual Basic might not work in Access, or vice versa. To determine if an ActiveX control works in Access, review the documentation for the control, or do your own testing.
Types of ActiveX Controls There are two types of ActiveX controls: non-visual controls and visual controls. Non-visual controls are placed on Access forms but are never seen by the end user. These controls include code that provides functionality of use to the developer. Nonvisual controls are visible at design time, not at runtime, so they remain invisible to the
Enhancing Forms with ActiveX Controls CHAPTER 9
205
end user. Examples of non-visual controls include the Image control and the Windows Common Dialog control. Conversely, a visual control contains a user interface that will be seen by the end user of the application. Examples of this control that will be discussed during this chapter include the Toolbar control, MonthView control, ListView control, and more. This type of control is visible at both design time and runtime. With visual controls, users are allowed to manipulate the object directly in some way.
Where Can You Get ActiveX Controls? There are undoubtedly numerous ActiveX controls already on your computer. You might have no idea where you acquired some of these controls. The following are possibilities indicating where controls might have come from: • Windows • Microsoft Office applications • Visual Basic • Microsoft Internet Explorer • Other applications • Third-party vendors • Downloads from Web sites • Microsoft Office Developer Kit • ActiveX controls you create yourself with C++, Java, or Visual Basic. See Chapter 20, “Using Visual Basic with Access,” for information about building your own ActiveX controls.
You are advised to test the control before using it. Many controls are provided as free downloads from the Internet. Determine whether the ActiveX control meets your needs before purchasing the control.
Are ActiveX Controls Safe? ActiveX controls are not guaranteed to be bug-free. ActiveX controls are software components that include code. A malicious developer could easily create an ActiveX control that could cause damage to your computer system. It is a good idea to test a control on a test PC before deploying an application with a third-party control.
ENHANCING FORMS WITH CONTROLS
Tip
9
206
User Interfaces Unleashed PART III
Can I Use and Distribute ActiveX Controls in My Application? Just because an ActiveX control is on your computer does not mean you can use and distribute it with your application. The question to ask is, “Do I have a legal right to use the ActiveX controls?” It is important to carefully read the licensing agreement from the vendor who sold you the control. For example, you might have received controls when you purchased development tools from Microsoft. Read the licensing agreement to determine whether you can use or distribute the controls royalty-free. Similarly, if you purchase ActiveX controls from third-party vendors, read the licensing agreements to determine your rights to use and distribute the controls. Other controls you might not have purchased might have been downloaded from the World Wide Web. Presumably, you would have no right to distribute those controls with your application. Often, when you attempt to use an ActiveX control in your application, you might be warned that you do not have the right to use and distribute the control. Licensing agreements are enforceable by law. Improper use and distribution of an ActiveX control is similar to illegally copying a software product. It might be a crime, or might subject the violator to a lawsuit for financial damages.
Using ActiveX Controls The steps to using ActiveX controls in Access include 1. Install the ActiveX control on the computer. 2. Register the control. 3. Add the control to a form. 4. Set properties of the control. 5. Add code to execute the methods and respond to events.
Installing an ActiveX Control The ActiveX control must be installed on the computer, or an error will occur when the application tries to use it. This means that whenever you distribute your application, you must make sure to distribute the ActiveX controls as well. This will be discussed in detail later in the chapter.
Enhancing Forms with ActiveX Controls CHAPTER 9
207
Caution If you distribute an application that uses ActiveX controls, you must make sure the controls are installed on each computer that runs your application. For example, sample applications for this chapter will not work on your computer unless you have the ActiveX controls installed.
Registering an ActiveX Control An ActiveX control must be registered before it can be added to an Access form. To determine whether a control is registered, try to insert it in a form as discussed in the next section. If you succeed, the control is already registered. If not, you need to register the control with Access. Some ActiveX controls are automatically registered when they are installed on the computer. To register a control manually, choose ActiveX Controls under the Tools menu while working in form design. The ActiveX controls dialog box will appear. Choose the control you want to register from the Available Controls list, and then click on the Register button. The ActiveX Controls dialog box will appear. Choose the corresponding ActiveX control (.OCX) file, and then click OK (see Figure 9.1). FIGURE 9.1 Registering ActiveX Controls dialog box.
9
If an ActiveX control is registered, you can add it to a form. To do so, switch to Form Design view and choose ActiveX Control under the Insert menu. Instead of the menu, you can also choose the More Controls tool on the bottom right corner of the toolbox (see Figure 9.2). The Insert ActiveX Control dialog box will appear. Select the control you want to add to the form, and click the OK button (see Figure 9.3). The dialog box will close. Click the form where you want to place the control.
ENHANCING FORMS WITH CONTROLS
Adding an ActiveX Control to a Form
208
User Interfaces Unleashed PART III
FIGURE 9.2 The More Controls tool on toolbox.
FIGURE 9.3 Choose an ActiveX control to add to the form.
After inserting an ActiveX control in a form, Access maintains a reference to the control’s type library. To see all the references of an Access application, choose References under the Tools menu in the Visual Basic Editor (see Figure 9.4).
Setting the ActiveX Control Properties ActiveX controls have a property sheet just like any other built-in Access control. In addition, ActiveX controls have a property page that resembles a form, which makes setting properties even easier. To open a property page for the ActiveX control, click on the
Enhancing Forms with ActiveX Controls CHAPTER 9
209
Build button under Custom Property in the property sheet. In addition, you can rightclick on the control itself and choose Properties from the shortcut menu (see Figure 9.5). FIGURE 9.4 ActiveX controls shown in the References dialog box.
FIGURE 9.5 Property page of ImageList control.
9
Writing code to execute methods or respond to events with ActiveX controls is no different from writing code with built-in Access controls. Use the Object Browser to learn about a control’s properties, methods, and events, as shown in Figure 9.6.
ENHANCING FORMS WITH CONTROLS
Writing Code to Execute Methods or Respond to Events
210
User Interfaces Unleashed PART III
FIGURE 9.6 Use the Object Browser to determine a control’s properties, methods, and events.
21 ActiveX Controls I will now take a whirlwind tour through 21 ActiveX controls. Obviously, volumes can be written about all the ActiveX controls available (there are thousands of them), but these are some of ActiveX controls provided by Microsoft. Tip See this chapter’s application on the book’s CD-ROM for code examples using all 21 of these ActiveX controls.
Table 9.1 provides the name of the control, its filename, and a description. TABLE 9.1
Whirlwind Tour of ActiveX Controls
ActiveX Control
Filename
Description
Animation
MSCOMCT2.OCX
Play video (AVI) files on a form Display a calendar on a form
Calendar Common Dialog
COMDLG32.OCX
Easily display Open, Save As, Color, Font, Print, and Help dialog boxes
DateTimePicker
MSCOMCT2.OCX
Drop-down calendar for users to input date values
Enhancing Forms with ActiveX Controls CHAPTER 9 TABLE 9.1
continued
Filename
Description
FlatScrollBar
MSCOMCT2.OCX
Scrollbar with a flat look
ImageCombo
MSCOMCTL.OCX
Combo box with images associated with items in the list
ImageList
MSCOMCTL.OCX
Holds bitmaps and images that can be used by other controls
ListView
MSCOMCTL.OCX
Presents a list of data in four different views
MAPIMessages
MSMAPI32.OCX
Send and retrieve messages, display address books, and other mailrelated features
MAPISession
MSMAPI32.OCX
Log on and log off MAPI sessions
MonthView
MSCOMCT2.OCX
Calendar interface to view and select date information
ProgressBar
MSCOMCTL.OCX
Displays feedback to the user when a process is occurring
RichText
RICHTX32.OCX
Provides different fonts, colors, sizes, and other formatting to text in textboxes
Slider
MSCOMCTL.OCX
A vertical and horizontal slider control
StatusBar
MSCOMCTL.OCX
Provides a status bar on a form
SysInfo
SYSINFO.OCX
Obtain and respond to system information
TabStrip
MSCOMCTL.OCX
Arranges tabs in multiple rows and display images on tabs
ToolBar
MSCOMCTL.OCX
Provides a toolbar on forms
TreeView
MSCOMCTL.OCX
Displays data in a hierarchical format
UpDown
MSCOMCT2.OCX
Enables users to increment and decrement the value of another control
WebBrowser
SHDOCVW.DLL
Displays a browser on a form
9 ENHANCING FORMS WITH CONTROLS
ActiveX Control
Tip
211
212
User Interfaces Unleashed PART III
Tip The chapter code contains working examples that use each of these controls.
Animation Control Use the Animation control to play video files (.AVI) on Access forms (see Figure 9.7). FIGURE 9.7 Animation
control
example.
Caution The Animation control does not support all AVI files. For example, the control will not work if the AVI file contains sound. Also, the AVI file must be uncompressed or compressed with Run-Length Encoding.
The commonly used properties and methods of the Animation control are summarized in Table 9.2. TABLE 9.2
Animation Control Summary
Item
Description
AutoPlay property
If set to True, AVI file plays in a continuous loop when loaded in the control. If False, AVI file does not play until the Play method is called.
Close method
Closes the currently opened AVI file.
Open method
Opens an AVI file to play.
Play method
Plays an AVI file that is loaded in the control.
Stop method
Stops playing an AVI file that was started with the Play method.
Enhancing Forms with ActiveX Controls CHAPTER 9
213
Calendar Control The Calendar control displays a calendar on an Access form (see Figure 9.8). FIGURE 9.8 Calendar
control
example.
The Calendar control is useful for setting and retrieving date values. The appearance of the calendar is very flexible, offering day, month, and year views. The commonly used properties, methods, and events of the Calendar control are summarized in Table 9.3. TABLE 9.3
Calendar Control Summary
Description
Day property
Sets the day of the month (1–31)
Month property
Sets the month to display
ShowDateSelectors property
To display the date selector drop-down list box
Value property
Sets or retrieves the currently selected date
Year property
Sets the year to display
NextDay method
Displays the next day
PreviousDay method
Displays the previous day
Today method
Displays today’s date
Click event
Occurs when a user clicks on a date
9 ENHANCING FORMS WITH CONTROLS
Item
214
User Interfaces Unleashed PART III
Note If you attempt to insert the Calendar Control and the version displayed is 8.0 (MSCAL.OCX), it will not work correctly. This problem is covered by Microsoft Knowledge Base Article Q287472, which can be found by searching the Knowledge Base at www.microsoft.com. This problem is caused by installing Visual C++ 6.0 after you have installed Office XP. To fix the problem, run the Add/Remove Programs applet and select change Microsoft Office XP. Using the add/Remove Features selection indicate that the Calendar Control is not available. Click Update. Perform the same steps a second time and click Run from Computer selection for the Calendar Control. (You will need your Office XP installation disk for this procedure.)
Common Dialog Control With the Common Dialog control, it is easy to display common Windows dialog boxes such as Open, Save As, Color, Font, Print, and Help dialog boxes (see Figure 9.9). This control is a non-visual control. Simply insert the control in a form and call a method to display the desired dialog box. The following code displays the Color dialog box: Me.ActiveXCommonDialogControl.ShowColor
FIGURE 9.9 Common Dialog
control example.
Enhancing Forms with ActiveX Controls CHAPTER 9
The commonly used properties and methods of the Common rized in Table 9.4. TABLE 9.4
Dialog
215
control are summa-
Common Dialog Control Summary
Item
Description
Color property
Retrieves selected color in Color and Font dialog boxes
Copies property
Number of copies to print from Print dialog box
DefaultExt property
File extensions for ShowSave and ShowOpen
DialogTitle property
Caption for dialog box
Filter property
Specifies type of file for Open and Save As dialog boxes
FilterIndex property
Specifies which filter to use as the default
FontName property
Font selected in Font dialog box
FontSize property
Font Size selected in Font dialog box
InitDir property
The initial directory for ShowSave and ShowOpen
Orientation property
Page orientation (portrait or landscape) from Print dialog box
ShowColor method
Displays Color dialog box
ShowFont method
Displays Font dialog box
ShowHelp method
Displays Help
ShowOpen method
Displays Open dialog box
ShowPrinter method
Displays Print dialog box
ShowSave method
Displays Save As dialog box
9 The DateTimePicker control provides a drop-down month-view calendar so that users can easily enter dates on a form (see Figure 9.10). This is similar to the date control used in Outlook appointment forms. The preceding example shows the drop-down calendar for date selection. A user can also use the up or down arrow keys to modify a date entered in the DateTimePicker. For example, if 7/15/99 is entered in the control, when the month (7), day (15), or year (99) is selected, the up or down arrows can be used to modify the date.
ENHANCING FORMS WITH CONTROLS
DateTimePicker Control
216
User Interfaces Unleashed PART III
FIGURE 9.10 DateTimePicker
control example.
Tip The appearance of the drop-down calendar can be customized using various color schemes. See the properties in Table 9.5.
The commonly used properties of the DateTimePicker control are summarized in Table 9.5. TABLE 9.5
DateTimePicker Control Summary
Item
Description
CalendarBackColor property
Sets or retrieves background color in drop-down calendar
CalendarForeColor property
Sets or retrieves foreground color in drop-down calendar
CalendarTitleBackColor
Sets or retrieves background color of title in drop-down calendar
property CalendarTitleForeColor
property
Sets or retrieves foreground color of title in drop-down calendar
property
Sets or retrieves foreground color of trailing dates in drop-down calendar
Checkbox property
Places check boxes inside the control
CalendarTrailingForeColor
Enhancing Forms with ActiveX Controls CHAPTER 9 TABLE 9.5
217
continued
Item
Description
CustomFormat property
A custom format string describing how the date and time values will be displayed
Day, Month, and Year properties
Returns selected value
DayOfWeek property
Returns day of the week
Format property
Displays long dates, short dates, time, and other formats
MinDate and MaxDate properties
Specifies a date range
Second, Minute and Hour
Returns selected value properties
Value property
Sets or retrieves selected date/time
FlatScrollBar Control This is a new version of scrollbar that sports a flat look (see Figure 9.11). Using the orientation property, you can position the scrollbar as horizontal or vertical. FIGURE 9.11 FlatScrollBar
control example.
9
TABLE 9.6
FlatScrollBar Control Summary
Item
Description
Appearance property
Sets or retrieves appearance of scrollbar. The scrollbar can be set to two- or three-dimensional.
LargeChange
Indicates the number of ticks scrolled when the user presses the Page Up or Page Down keys.
Orientation property
Sets or retrieves orientation (horizontal or vertical) of scrollbar.
ENHANCING FORMS WITH CONTROLS
The commonly used properties of the FlatScrollBar control are summarized in Table 9.6.
218
User Interfaces Unleashed PART III TABLE 9.6
continued
Item
Description
SmallChange
Indicates the number of ticks scrolled when the user presses the left or right arrow keys.
ImageCombo Control The ImageCombo control is similar to a standard combo box except that images can be associated with each item in the list (see Figure 9.12). This makes combo boxes easier for users to work with. FIGURE 9.12 control example.
ImageCombo
The ImageList control is used to obtain images for the ImageCombo control. An image can be shown next to the text in the list, as well as in the edit portion of the combo box. To add items programmatically to the ImageCombo, use the Add method as follows: With ctlImageCombo.ComboItem ‘ Add Index, ItemName, ListBox Display Name, Image Key Name. .Add 1, “Cloudy”, “Cloudy”, “Cloudy” .Add 2, “Rainy”, “Rainy”, “Rainy” .Add 3, “Snowing”, “Snowing”, “Snowing” .Add 4, “Sunny”, “Sunny”, “Sunny” .Add 5, “Lightning”, “Lightning”, “Lightning” End With
The commonly used objects, properties, methods, and events of the ImageCombo control are summarized in Table 9.7.
Enhancing Forms with ActiveX Controls CHAPTER 9 TABLE 9.7
219
ImageCombo Control Summary
Item
Description
Add method
Programmatically add items to ImageCombo
ComboItem object
ComboItem object is an item in the list
ComboItems property
Retrieves a reference to ComboItems collection
DropDown event
Occurs when list portion of control drops down
ImageList property
Associates an ImageList control to ImageCombo
Indentation property
Sets or retrieves width of indentation (each indent equals 10 pixels)
SelImage property
Index indicating selected image
SelectedItem property
Selected item in the list
ImageList Control The ImageList control is a non-visual control used by developers. The end user will not interact with the control. Think of the ImageList control as a file cabinet of images. You can store many types of images in the control such as bitmaps (.BMP), icons (.ICO), .GIF files, .DIB files, .CUR files, and .JPG files. Other controls can then use the images stored in the ImageList control. Several of the ActiveX controls discussed in this chapter, including the ImageCombo, ListView, and Toolbar controls, use the ImageList.
FIGURE 9.13 control property page.
ImageList
9 ENHANCING FORMS WITH CONTROLS
Images are easily added to the ImageList with the control’s property page (see Figure 9.13). Keep in mind that all images added to the ImageList must be the same size. If you want to use different sized images in other controls, use multiple ImageList controls.
220
User Interfaces Unleashed PART III
Images added to the ImageList are always assigned an index number. Don’t rely on it. Instead, always enter a Key value for each image. Caution When items are deleted from the ImageList control, the index numbers are renumbered, so do not rely on them. Always use unique Key values and refer to images by Key value in code.
Tip Don’t be excessive using images in applications. The ImageList control consumes a great deal of memory and can slow down your application if a large number of images are used. All images are stored in memory when the form hosting the control is opened.
The commonly used objects, properties, and methods of the ImageList control are summarized in Table 9.8. TABLE 9.8
ImageList Control Summary
Item
Description
ListImages object
ListImages collection (1-based)
ListImage object
ListImage object—is an image in the control
Index property
A unique index value for each image
Key property
A text value (friendly name) to refer to an image
ImageCount property
The current number of images in the ImageList
Overlay method
Draws one image over another
Add images
In code, uses the Add method of the ListImages collection
For an example of images in a form with the ImageList control, see Figure 9.14. The ListView control is able to use images because of the ImageList control.
Enhancing Forms with ActiveX Controls CHAPTER 9
221
Caution After you bind controls to an ImageList, you cannot add new images to the ImageList control. Make sure to include all images you plan to use when you initially add the control to the form. If you later want to add images to the ImageList after another control is bound to it, you must unbind all controls first.
ListView Control The ListView control displays a list of items in four different views. An example can be seen in the right pane in Windows Explorer, where users can view files as Large Icons, Small Icons, List, or Details. In Access forms, lists of data can have this same functionality with the ListView control (see Figure 9.14). Items in the list can be arranged with or without column headings. This powerful control is flexible and provides many ways to view data. FIGURE 9.14 ListView
control
example.
9
TABLE 9.9
ListView Control Summary
Item
Description
ListItems object
ListItems collection (1-based)
ListItem object
ListItem object is an item in the list
ENHANCING FORMS WITH CONTROLS
The commonly used objects and properties of the ListView control are summarized in Table 9.9.
222
User Interfaces Unleashed PART III TABLE 9.9
continued
Item
Description
ColumnHeaders object
ColumnHeaders collection (1-based)
ColumnHeader object
ColumnHeader object, the heading text for a column
header AllowColumnReorder property
Reorders columns
Arrange property
Arranges icons in the control
FullRowSelect property
Selects an entire row
GridLines property
Displays gridlines in report view
HideColumnHeaders property
Hides and unhides column headers in Report view
LabelEdit property
Enables users to edit labels
LabelWrap property
Wraps ListItem object labels
MultiSelect property
Enables users to select multiple objects or items
SelectedItem property
Determines a selected ListItem
Sorted property
Determines whether items in collection are sorted
SortKey property
Determines if items are sorted by ListItem Text property or by a SubItems collection index
SortOrder property
Sorts by ascending and descending order
SubItems property
An array of strings displayed in report view
View property
Sets appearance of items: Icon (large icon), Small Icon, List, and Report (detail view)
Tip Using the ListView control in conjunction with the Treeview control provides much of the functionality of the Windows Explorer interface. This is a great way to view data because most users are already familiar with the Explorer interface.
MAPISession Control The MAPI (Messaging Application Programming Interface) controls mail-enabled Access applications. The MAPISession control provides a means to sign on and sign off a MAPI session (see Figure 9.15).
Enhancing Forms with ActiveX Controls CHAPTER 9
223
FIGURE 9.15 MAPISession
con-
trol example.
Caution For the MAPI controls to work, MAPI services for a MAPI-compliant e-mail system (such as Microsoft Exchange) must be installed on the computer.
The MAPISession control is a non-visual control and has no events. The commonly used properties and methods of the MAPISession control are summarized in Table 9.10. TABLE 9.10
MAPISession Control Summary
Description
DownloadMail property
Downloads new messages
LogonUI property
Displays a sign-on dialog box
NewSession property
Establishes a new mail session
Password property
Password associated with UserName property
SessionID property
ID of current messaging session
UserName property
Profile used to establish a messaging session
SignOff method
Signs off user and ends messaging session
SignOn method
Logs user into messaging session
MAPIMessages Control After the user establishes a MAPI session with the MAPISession control, the MAPIMessages control can be used to create new messages, access messages, send messages (with or without attachments), reply to messages, display address books, and more. See Figure 9.15 for an example using this control.
9 ENHANCING FORMS WITH CONTROLS
Item
224
User Interfaces Unleashed PART III
The commonly used properties and methods of the MAPIMessages control are summarized in Table 9.11. TABLE 9.11
MAPIMessages Control Summary
Item
Description
AttachmentCount property
Number of attachments associated with current message
AttchmentIndex property
Sets current attachment index
AttachmentName property
Name of attachment file
AttachmentType property
Read-only property that indicates attachment type; valid types are Data Embedded OLE or Static OLE
MsgCount property
Total number of messages in message set
MsgDateReceived property
Date message received
MsgID property
String identifier of a message
MsgNoteText property
Text body of a message
MsgRead property
Specifies if a message has been read
MsgSent property
Specifies if a message has been sent
MsgSubject property
Subject line of a message
RecipAddress property
E-mail address of recipient
Compose method
Composes a message
Copy method
Copies a message
Delete method
Deletes a message, recipient, or attachment
Fetch method
Creates a message set from selected inbox messages
Forward Method
Forwards a message
Reply Method
Replies to a message
Save Method
Saves a message
Send Method
Sends a message
MonthView Control The MonthView control provides a calendar interface to view and select date information and can be customized with color schemes and number of months displayed (see Figure 9.16). Users can select individual dates on the control or contiguous dates by using the MultiSelect property.
Enhancing Forms with ActiveX Controls CHAPTER 9
225
FIGURE 9.16 MonthView
control
example.
The commonly used properties and events of the MonthView control are summarized in Table 9.12. TABLE 9.12
MonthView Control Summary
Item
Description
Day property
Specifies the current Day number
DayOfWeek property
Specifies day of week
MinDate/MaxDate properties
Range of dates displayed in the MonthView
MaxSelCount property
Maximum number of contiguous days that can be selected at once Specifies the current month
MonthBackColor property
Specifies a month’s background color
MonthColumns property
Number of monthly columns displayed
MonthRows property
Number of monthly rows displayed
MultiSelect property
Allows multiple selection of dates
SelStart/SelEnd properties
Lower and upper bounds of date range selected
ShowToday property
Enables user to return to today’s date
StartOfWeek property
Sets day of week to appear in left-most column
Week property
Specifies the current week number
Value property
Date currently selected
Year property
Specifies the current year
DateClick event
Date clicked on the control
9 ENHANCING FORMS WITH CONTROLS
Month property
226
User Interfaces Unleashed PART III TABLE 9.12
continued
Item
Description
DateDblClick event
Date double-clicked on the control
SelChangeEvent
Occurs when a new date or range of dates is selected
ProgressBar Control It is important to give the users feedback when a process will be lengthy. Otherwise, thinking that the computer has locked up, the user might shut down the application. This could cause program errors, data corruption, and more. A ProgressBar control provides the user with visual feedback that the computer is busy and approximates how much of the process has been completed (see Figure 9.17). You can customize the appearance of the ProgressBar control, including minimum and maximum values and orientation of the ProgressBar. The ProgressBar can then be incremented as the user waits for the time-intensive process to complete. Tip Visual feedback provided to users during lengthy processes gives users the perception that the process is speedier than it actually is.
FIGURE 9.17 ProgressBar
con-
trol example.
Tip With long processes, partially fill the ProgressBar as soon as the process begins. This might be a bit dishonest because it does not accurately reflect the actual work completed. However, if a great deal of time passes before even the first part of the ProgressBar is filled, the user might shut off the computer, thinking it has locked up.
Enhancing Forms with ActiveX Controls CHAPTER 9
227
The commonly used properties of the ProgressBar control are summarized in Table 9.13. TABLE 9.13
ProgressBar Control Summary
Item
Description
Min/Max properties
Minimum and maximum values of the control.
Orientation property
Orientation (horizontal and vertical) of the control.
Scrolling property
Specifies whether progress as displayed in the control is segmented or smooth.
Value property
Value of the control. As value is incremented, progress displayed in the control is increased.
RichText Control The RichText control provides a text control with extensive formatting capabilities, in contrast to standard textbox controls, which do not provide for mixed fonts and colors (see Figure 9.18). This is not a problem with the RichText control because it features the following: • Mixed fonts, font styles, font sizes, and font colors • Superscripts and subscripts • Paragraph formatting with left, right, and hanging indents • Capacity for very large text files • Capability to bind to an Access memo field • Capability to add bitmaps, icons, and documents
RichText
example.
control
ENHANCING FORMS WITH CONTROLS
FIGURE 9.18
9
228
User Interfaces Unleashed PART III
The commonly used properties, methods, and events of the RichText control are summarized in Table 9.14. TABLE 9.14
RichText Control Summary
Item
Description
BulletIndent property
Sets or retrieves measurement of indent
FileName property
Filename of the file loaded in the control
MaxLength property
Maximum number of characters the control can hold
MultiLine property
Enables multiple lines of text
RightMargin property
Specifies right margin
ScrollBars property
Displays horizontal or vertical scrollbars
SelAlignment property
Specifies alignment of selected paragraphs
SelBold/SelItalic/
Formats selected text
SelStrikeThru/ SelUnderline properties SelColor property
Specifies color of selected text
SelFontName property
Specifies the font name of the selected text
SelFontSize property
Specifies the font size of the selected text
GetLineFromChar
Returns the line number of the line containing the character at position
Find method
Searches for text in the control
LoadFile method
Loads a text or .RTF file in the control
SaveFile method
Saves file contained in the control
SelPrint method
Prints selected text
SelChange event
Occurs when selection of text changes or insertion point moves
Slider Control The Slider control can be used to enter or display a value on a continuous scale (see Figure 9.19). The tick interval, movement properties, and orientation (horizontal and vertical) can be modified.
Enhancing Forms with ActiveX Controls CHAPTER 9
229
FIGURE 9.19 control example.
Slider
The commonly used properties, methods, and events of the Slider control are summarized in Table 9.15. TABLE 9.15
Slider Control Summary
Item
Description
LargeChange property
Specifies movement of ticks when Page Up or Page Down keys are pressed, or when mouse is pressed on left or right side of slider
SmallChange property
Specifies movement of ticks when left or right arrow keys are pressed
Min/Max properties
Minimum and maximum values of the control
Orientation property
Orientation of the control (horizontal or vertical)
SelectRange property
Specifies a selected range
TickStyle property
Specifies the location of the tick marks
Value property
Current value of the control
ClearSel method
Clears current selection of the control Retrieves number of ticks between Min and Max properties
Scroll event
Occurs when there is a movement on the slider
StatusBar Control are used extensively in applications to provide information to the users (see Figure 9.20). Examples include Microsoft Word and Excel.
StatusBars
ENHANCING FORMS WITH CONTROLS
GetNumTicks method
9
230
User Interfaces Unleashed PART III
FIGURE 9.20 StatusBar
control
example.
Tip The StatusBar control can be positioned on a form with the Align property (top, bottom, left, right, or none). You are urged to place the StatusBar on the bottom of the form to be consistent with other Windows applications.
The StatusBar control contains Panel objects and a Panels collection that can be used to take action programmatically. For example, if a user clicks on a certain panel, a certain action can then be taken. The commonly used objects, properties, and events of the StatusBar control are summarized in Table 9.16. TABLE 9.16
StatusBar Control Summary
Item
Description
Panels object
Panels collection (1-based)
Panels object
Panel object is an item in the list
Align property
Specifies location of a StatusBar on the form (top, bottom, left, right, or none)
SimpleText property
Sets or retrieves text in StatusBar when Style property is set to Simple
Style property
Sets the style property to display one large panel or all panels
PanelClick event
Occurs when a user clicks a panel
PanelDblClick event
Occurs when a user double-clicks on a panel
Enhancing Forms with ActiveX Controls CHAPTER 9
231
SysInfo Control The SysInfo control is useful to obtain and respond to system information (see Figure 9.21). This powerful control can monitor the following system information: • The operating system platform, version, and build number • Events for desktop, monitor size, and resolution changes • Events for Plug and Play • Power management properties and events FIGURE 9.21 control example.
SysInfo
The commonly used objects, properties, and events of the SysInfo control are summarized in Table 9.17. TABLE 9.17
SysInfo Control Summary
Description
ACStatus property
Detects if using AC power
BatteryFullTime property
When battery is fully charged, indicates number of seconds of battery life
BatteryLifePercent property
Percentage of battery life remaining
BatteryLifeTime property
Returns number of seconds of battery life remaining
BatteryStatus property
Status of battery charge (low, medium, high, charging)
OSBuild property
Operating system build number
OSPlatform property
Operating system (Windows 95, Windows NT)
OSVersion property
Operating system version
ConfigChanged event
Occurs when hardware profile changes
DeviceArrival event
Occurs when new device is added to system
PowerStatusChanged event
Occurs when power status changes
9 ENHANCING FORMS WITH CONTROLS
Item
232
User Interfaces Unleashed PART III TABLE 9.17
continued
Item
Description
PowerSuspend event
Occurs before system enters suspend mode
TimeChanged event
Occurs when system time changes
TabStrip Control The TabStrip control is useful when a large number of controls need to be placed on a single form (see Figure 9.22). With the TabStrip control, multiple controls can be placed on separate tabs. The style and orientation of the tabs on the control can be modified. FIGURE 9.22 TabStrip
control
example.
The commonly used objects, properties, methods, and events of the TabStrip control are summarized in Table 9.18. TABLE 9.18
TabStrip Control Summary
Item
Description
Tabs object
Tabs collection (1-based)
Tab object
Tab object—an individual tab
ClientHeight/ClientWidth/ ClientLeft/ClientTop
Returns coordinates of display area of the control
properties ImageList property
Associates an ImageList control
MultiSelect property
Allows multiple selection
Placement property
Places tabs on top, bottom, left, or right
Enhancing Forms with ActiveX Controls CHAPTER 9 TABLE 9.18
233
continued
Item
Description
SelectedItem property
Determines selected tab
Style property
Modifies appearance of tabs (tabs, regular buttons, or flat buttons)
DeselectAll method
Clears all selected tabs
Click event
Occurs when tab is clicked
Toolbar Control Use the Toolbar control to create a toolbar for your Access application. The Toolbar control provides users with a graphic interface for commonly used menu items (see Figure 9.23). The Toolbar control includes Button objects and a Buttons collection. Buttons can be added and removed programmatically from the control. Code can be written to respond to control events, most commonly the ButtonClick event. FIGURE 9.23 control example.
Toolbar
9
TABLE 9.19
Toolbar Control Summary
Item
Description
Buttons object
Buttons collection (1-based)
Button object
Button object—an individual button
ButtonMenus object
ButtonMenus collection (1-based)
ButtonMenu object
ButtonMenu object—Drop-down menu from Button
object
ENHANCING FORMS WITH CONTROLS
The commonly used objects, properties, methods, and events of the Toolbar control are summarized in Table 9.19.
234
User Interfaces Unleashed PART III TABLE 9.19
continued
Item
Description
Align property
Displays the control on top, bottom, left, or right side of form
AllowCustomize property
Enables users to customize the control
BorderStyle property
Specifies border style of the control
ButtonHeight/ButtonWidth
Height and width of toolbar buttons properties
ImageList property
Associates an ImageList control
Style property
Specifies style of the control (Standard, Transparent, or text to right of image)
Customize method
Enables users to customize toolbar
RestoreToolbar method
Restores toolbar to original state
ButtonClick event
Occurs when a button is clicked
ButtonMenuClick event
Occurs when a button menu is clicked
TreeView Control The TreeView control displays a hierarchical list. An example can be seen in the left pane in Windows Explorer. In Explorer, the hierarchical list of folders can be expanded and collapsed for various views. Figure 9.24 shows the use of a TreeView control on an Access form. The TreeView control contains Node objects. Node is an item in the control. Each Node can contain text and images. You can programmatically navigate through the hierarchy in the control and expand and collapse nodes. FIGURE 9.24 TreeView
example.
control
Enhancing Forms with ActiveX Controls CHAPTER 9
235
The commonly used objects, properties, and events of the TreeView control are summarized in Table 9.20. TABLE 9.20
TreeView Control Summary
Item
Description
Nodes object
Nodes collection (1-based)
Node object
Node object—an item in the TreeView control
Checkboxes property
Enables checkboxes in the control
Indentation property
Specifies width of indentation
LabelEdit property
Enables users to edit node labels
LineStyle property
Specifies how style of lines is displayed between nodes
SelectedItem property
Selected node in the control
Sorted property
Specifies how root and child-level nodes are sorted
Style property
Specifies style of each node (text, images, plus/minus, and lines)
AfterLabelEdit event
Occurs after a user edits a node label
Collapse event
Occurs when a node is collapsed
Expand event
Occurs when a node is expanded
NodeClick event
Occurs when a node is clicked
Tip The Node object also features its own set of useful properties, which include the Child, FirstSibling, LastSibling, Previous, Parent, Next, and Root properties.
The UpDown control makes it easy for users to change number values with a mouse. The control consists of a pair of arrows that users can click on to increment or decrement values (see Figure 9.25). The UpDown control can be easily associated with another control, such as a textbox, with the BuddyControl property. There’s no need to write specific code. By using the BuddyControl property to associate two controls, you’ve enabled them to work together. As the user clicks on the up arrow of the UpDown control, the value in the textbox changes automatically.
ENHANCING FORMS WITH CONTROLS
UpDown Control
9
236
User Interfaces Unleashed PART III
FIGURE 9.25 control example.
UpDown
The commonly used properties and events of the UpDown control are summarized in Table 9.21. TABLE 9.21
UpDown Control Summary
Item
Description
Alignment property
Aligns UpDown control to left or right of buddy control
AutoBuddy property
Specifies whether BuddyControl property is used to set buddy control
BuddyControl property
Specifies name of control to use as the buddy control
BuddyProperty property
Specifies property used to synchronize UpDown control with its buddy control
Increment property
Specifies amount the value of the control changes
Min/Max properties
Minimum and maximum values of the control
Orientation property
Specifies orientation of the control (vertical or horizontal)
SyncBuddy property
Specifies whether UpDown control synchronizes its value property with a property of the buddy control
Value property
Current position of scroll value
Change event
Occurs when Value Property changes
DownClick event
Occurs when down or left arrow is clicked
UpClick event
Occurs when up or right arrow is clicked
WebBrowser Control The WebBrowser control is used to provide a Microsoft Internet Explorer Web browser within an Access form (see Figure 9.26). Because most users already have a Web browser on their computer, why would you ever do this?
Enhancing Forms with ActiveX Controls CHAPTER 9
237
• The Web browser is available to users without leaving your Access application. • Restrict the user’s access only to particular Web sites. Some companies have discovered that a great deal of worker productivity is lost due to non–work-related browsing. With the WebBrowser control, access can be provided only to workrelated Web sites. Also, users can be restricted from accessing inappropriate Web sites. FIGURE 9.26 control example. WebBrowser
Caution If Microsoft Internet Explorer 3 or greater is installed on your computer, the WebBrowser control is installed. This control cannot be distributed separately with your applications. You must either make sure that users install Internet Explorer, or you must distribute the entire Internet Explorer application to them.
TABLE 9.22
WebBrowser Control Summary
Item
Description
AddressBar property
Shows address bar
FullScreen property
Maximizes screen
LocationName property
Retrieves friendly name of URL/file
LocationURL property
Retrieves full URL/path
ENHANCING FORMS WITH CONTROLS
The commonly used properties, methods, and events of the WebBrowser control are summarized in Table 9.22.
9
238
User Interfaces Unleashed PART III TABLE 9.22
continued
Item
Description
MenuBar property
Shows menu bar
Type property
Retrieves type of document in the control
GoBack method
Navigates to previous item in history list
GoForward method
Navigates to next item in history list
GoHome method
Navigates to Home page
GoSearch method
Navigates to Search page
Navigate method
Navigates to URL or file
Refresh method
Refreshes current page
Stop method
Stops opening a page
DownloadBegin event
Occurs when download of a page begins
DownloadComplete event
Occurs when download of a page is completed
StatusTextChange event
Occurs when status bar text changes
TitleChange event
Occurs when title of document changes
Distributing ActiveX Controls When you distribute your Access application to others, you will need to include all the ActiveX controls, or your application will not run properly. Each ActiveX control that is used must be correctly installed and registered on the user’s machine. The easiest way to deploy an application is to use the VBA Package and Deployment Wizard. To start the VBA Package and Deployment Wizard, choose Add-In Manager under the Tools menu in the Visual Basic Editor. Select VBA Package and Deployment Wizard. At the bottom of the form, check the load behavior you desire. Click OK. The wizard will then walk you through the steps to create a setup routine of your Access application. The VBA Package and Deployment Wizard does a very good job including all ActiveX controls and other necessary dependent files. After the end user runs the set-up routine and installs the application and dependent files on his or her computer, the application will run correctly. The VBA Package and Deployment Wizard also makes all the appropriate registry settings on the user’s computer.
Enhancing Forms with ActiveX Controls CHAPTER 9
239
Summary Using ActiveX controls will enhance and extend your Access applications. In this chapter, 21 ActiveX controls were explained. See this chapter’s application on the book’s CDROM for examples of all these powerful ActiveX controls.
9 ENHANCING FORMS WITH CONTROLS
CHAPTER 10
Reporting Unleashed
IN THIS CHAPTER • Approaching Reports
242
• Understanding the Architecture of Access Reports 242 • Building a Single Table Report Using the Report Wizard 244 • Customizing Reports
247
• Working with Subreports
256
• Creating Simple Mailing Labels • Publishing a Report
262
• Modifying a Report at Runtime • Building Reports Programmatically • Tips and Tricks
259
274
279
266
242
User Interfaces Unleashed PART III
After you have done all the work of designing the data structure of your application and have created the forms to assist the users in handling the application’s data and processes, it’s time to create the reports for the application. The reports are by far the most visible part of your application. People who might never see one of your forms and have no idea how you dealt with security and data layout will see the reports you have created, and they will have requests for more. As a matter of fact, you know you’ve created a good application when new reports or variations on existing ones are often being requested. This is both rewarding and tedious as reports are probably one of the most challenging objects to work with in Access.
Approaching Reports This chapter will break the report object down into its constituent parts and explain how each one works. I will also review some tips and tricks for making reports easily do what might seem like complicated tasks. For those tasks that cannot be done simply, I will examine how to manipulate a report with VBA code so it will do almost anything you command. I will also explore bound reports, unbound controls, and subreports. Reports were designed for creating output for printers. For this reason, there are some unique limitations to the object. Reports do not have an interactive capability like forms, so you cannot dynamically change values or data sources after the report has printed or rendered itself in Print Preview. Also, the appearance of the output depends on the print driver being used because the results are usually viewed on screen or paper. What you see and what you get must conform to the parameters of the printer and paper you are using. Despite these limitations, Access reports are incredibly flexible tools for presenting data from your application. The key to unleashing their capabilities is to understand the Report object and all its parts. The best way to do this is by reviewing it piece by piece.
Understanding the Architecture of Access Reports Access reports are divided into four major parts or sections: Report Headers/Footers, Page Headers/Footers, Section Headers/Footers, and the Detail section. These sections act as wrappers around your data presentation. The first thing to print on a report is the Report Header/Footer. There is only one Report Header/Footer. The Report Footer prints after all the data, but before the final Page Footer (though it doesn’t look that way in the Design view). Each page in a report might have a Page Header/Footer. Though you have
Reporting Unleashed CHAPTER 10
243
access to only one Page section in the Design view of the report, the section prints for each page in the report. You will see how to customize the Page Header/Footer to print differently for different pages. Section Headers/Footers appear for each grouping or banding you place in your report. A report can have as many as ten of these sections, and they can represent themselves in the printout as many times as the data warrants. Section Headers/Footers often cause confusion among report designers when they write expressions in a report. You will see how to manage them so they yield useful information. Finally, the Detail section displays the finest level of information in your report. There is only one Detail section and it is sandwiched between the other section headers and footers in the middle of the Design view. Figure 10.1 shows the sections of a report in Design view. FIGURE 10.1 Design view of the Categories and Products report.
The basic way of presenting data on a report is to place bound controls into the sections and have them present their data when printed. However, it is also possible to place a report into any of these sections so it will make its presentation as a subreport. You will see what’s new with subreports in Access 2002 and examine some of the issues involved in using them.
10 REPORTING UNLEASHED
Finally, the Report object, like the other objects in Access 2002, is filled with properties and events that enable you to customize and automate reports.
244
User Interfaces Unleashed PART III
Building a Single Table Report Using the Report Wizard The Access Report Wizard is probably the most useful wizard in Access, and although it is unlikely to provide you with a report that perfectly suits your needs, chances are that it can do about 90% of the work for you on 90% of your reports. Furthermore, the tasks that it will do for you are some of the most tedious and unexciting chores of report building. Note The Report Wizard can only create new reports. After you have created a report, you will have to modify it manually.
To create a report using the Report Wizard, simply choose the Report Wizard option from the New Report dialog box. Figure 10.2 shows the selection of the Report Wizard in a New Report dialog box. FIGURE 10.2 New Report dialog box with Report Wizard and Categories selected.
1. Select Report Wizard and the Categories table (in my example I am using the Categories table of the NWIND.MDB sample database that ships with Access 2002) and click the OK button. 2. Next, the wizard asks you which fields you want on the report. You can choose them one by one or all at once. The order in which you choose them will affect the sorting and the placement of the controls in the finished report. 3. The next dialog box, shown in Figure 10.3, wants to know how to group the data. Because this is a simple report based on a single table, groupings wouldn’t be very useful. Click Next.
Reporting Unleashed CHAPTER 10
245
Here you have the ability to determine the sorting of the report. You can sort up to four fields in ascending or descending order. You can choose CategoryID and CategoryName as the fields to sort by. FIGURE 10.3 Sorting and Grouping Property settings.
4. After choosing the sorting order, you can choose a default layout for the report: columnar, tabular, or justified. You can also make the orientation of the printed report either landscape or portrait. Another option is to adjust the fields so they fit on one page. This is not like Microsoft Excel’s Fit to Page feature where the contents of the cells are actually rendered in a different font size for printing. This feature only adjusts the width of controls so they will fit on a page. Adjusting field-width so all data fits on the page might make some data illegible. Click Next to accept the defaults. There are several styles to choose from on the next dialog box. These styles treat the headers, labels, and sections of your report differently and can give your report a nice, polished look without a lot of effort on your part. You’ll use the default Corporate style. Click Next.
Although the Report Wizard created the report, you can modify it at any time and in any way you like.
10 REPORTING UNLEASHED
5. The final dialog box asks you for a name for the report and asks whether you want to view the report or work with it in Design view. Modify the report title to Product Categories and click Finish.
246
User Interfaces Unleashed PART III
The Report Wizard can also create reports based on more than one data source. If you have established a relationship between the tables in your database, the Report Wizard will work with these Relationships and build a SQL statement for your report. 1. Again, make a new report using the Report Wizard. Go directly to the dialog box where you select the fields and add the Categories table’s CategoryName field, as shown in Figure 10.4. FIGURE 10.4 Selecting fields from the Report Wizard.
2. Now select the Products Table from the Tables/Queries drop-down list and select ProductName, as shown in Figure 10.5. FIGURE 10.5 Both fields have been added.
Reporting Unleashed CHAPTER 10
247
3. Move through the dialog boxes and set the sorting on ProductName. 4. Name the report “Categories and Products” and view the report. In the Design view of the report, you will notice that the Report Wizard has made a SQL statement for you by using the relationships established during the data design phase of Northwind.
Customizing Reports It is unusual for a report created with the Report Wizard to exactly meet your needs without some kind of modification. Though you should use the time-saving Report Wizard at every opportunity, there is no substitute for knowing how to customize a report. With only a few steps and some calculations, you can change the Categories and Products report into a report that shows product orders by category. It will have a multitable recordsource, groupings, sorting, calculations, headers, and footers.
Changing the Recordsource in a Report The first step to changing a report is to change its recordsource, as shown in Figure 10.6. It would be very difficult to make any meaningful changes to the report without obtaining the correct records and fields. FIGURE 10.6 Report property window with Recordsource.
10 REPORTING UNLEASHED
248
User Interfaces Unleashed PART III
From the report’s property window, highlight the RecordSource property and click the ellipsis button (…) to start the Query Builder (see Figure 10.7). Add the Order Details table to the query. Also add the Order Details.Quantity field and the Products.ProductID field from the Products table. Close the Query Builder. FIGURE 10.7 The Query Builder.
Now that the recordsource has been changed, you can alter the report to present the data in a useful way.
Changing the Grouping Structure in a Report The most significant modification you need to make is to change the grouping structure of the report. When you assign grouping to a report you are telling the report to gather together the relevant data and present it in a block. These blocks are also called bands and you can create them and alter them through the Sorting and Grouping dialog box. When you create a grouping band, several options are available: •
Field/Expression
The field or expression which will govern the grouping of the
report. How the grouping will be presented. Choices are either Ascending or Descending.
•
Sort Order
•
Group Header
When the Group appears on the report, you can choose to have a space in the report precede the presentation of its data. This usually contains the value being grouped and other relevant information.
Reporting Unleashed CHAPTER 10
•
Group Footer
•
This property determines what will constitute a grouping value. The setting of Each Value will group the data by the entire data item, whereas the Interval option allows you to choose just a part of the grouping data item. The Group On property works in conjunction with the Group Interval property.
•
Group Interval When Group On is set to Interval, this property specifies what the interval will be. Table 10.1 shows the possible values and when they are available.
249
The section that follows the group’s data. Usually contains totals and other calculations on the group’s data.
Group On
TABLE 10.1
Group Intervals and Their Limitations
Setting
Value
Limitation
Each Value
0
For Any Data Type
Prefix Characters
1
For Text Fields Only
Year
2
For Date Fields Only
Quarter
3
For Date Fields Only
Month
4
For Date Fields Only
Week
5
For Date Fields Only
Day
6
For Date Fields Only
Hour
7
For Date Fields Only
Minute
8
For Date Fields Only
Interval
9
For Number Fields Only
Note When you decide to group an expression, Access is unable to determine the result of that expression while the report is in Design view, so Access will present all possible Group On/Group Interval options. Be sure to choose the one that will work with your expression.
•
10 REPORTING UNLEASHED
This property affects the printed report and how Access will attempt to keep data on the same page as its group headers/footers. Table 10.2 shows the settings and their effect. KeepTogether
250
User Interfaces Unleashed PART III TABLE 10.2
KeepTogether Settings Explained
Setting
Value
Limitation
No
0
Page breaks occur without regard to the position of headers, footers, and data.
Whole Group
1
Access tries to keep headers, footers, and data on one page.
With First Detail
2
Access tries to print the group header on the same page as its first detail record.
Implementing Grouping in a Report For Grouping to be activated, all you have to do is set a header, footer, or both. When you do, a small icon appears next to the field’s name in the Sorting and Grouping property window and a new section appears in the report’s Design view. Any control placed in this section will create a group based on its values, depending on your optional settings. For a report to tally the units sold for each product by category, the report needs a grouping by product. It’s best to use a unique identifier for this. Though in my example Product Name will probably work just fine, in the real world, products can come in different sizes, weights, and configurations, but share a name. Using the Product ID field will help the report distinguish these differences. 1. From the View menu, choose Sorting and Grouping. Change the Product Name sorting property to ProductID and set the Group Header property to Yes. Also, create a Group footer for Category. You now have all the elements necessary to present a grouped report on category and product. 2. From your field list window, place the ProductID field in ProductID header just to the right of the CategoryID control in the Category Header. You can cut and paste the ProductID’s caption label control into the Page Header. 3. Next, move the ProductName control out of the Detail section and into the ProductID header. You will need to realign it with its caption. The result is a report that gathers the categories together and then gathers their sales and lists them. As it is, this report only lists products sold in each category, but not how many units have sold. For that, you need an expression.
Using Functions in a Report To convey complete and accurate information through your reports, you will need to occasionally write functions to perform calculations or other actions for your reports.
Reporting Unleashed CHAPTER 10
251
Calculations in the report can also improve the performance of a report. If you have the choice of writing a function in an underlying query or in the report, you should give careful consideration to choosing to write it in the report. By placing it in the report, you might actually perform the calculation fewer times. This section explains the ins and outs of using functions in a report.
Using Calculation Functions Calculations on reports are very much the same as calculations anywhere else in Access, except in reports the same expression can give a different result depending upon which section contains the control. The reason for this is simple. When Access cycles through your data to create the groupings you have requested, it is actually looking at different data. So the expression =Sum([Quantity])
placed in the ProductID header will return a total of the sales for each product. If this expression is placed in the category footer, it will yield a total for all the units sold in the category. To see this at work, create a text box control in the ProductID header and enter the expression =Sum([Quantity])
Even though the report does not contain a control named “quantity,” a field by this name is in the underlying recordsource and can be used in an expression. Copy the control to the Category footer. View the report in Print Preview mode and you’ll see the result shown in Figure 10.8.
Using an Immediate IF
10 REPORTING UNLEASHED
Another useful function to use in reports is the Immediate IF function (IIF()). This function allows you to create an IF…Then…Else test without having to write code. A great use for it is to help summarize or draw attention to important records in the report. It takes three arguments: the condition, what to do when the condition is true, and what to do when the condition is false. A comma separates each argument. To use it, write a test condition that will result in either a true or false resolution (for example, [sum of quantity]>=500). The second argument is usually a value to present if the condition is true (for example, “High”), and the third argument is a value to present if the condition is false (for example, “Low” or “” to display nothing). It is possible to nest IIF functions within one another so when a condition is resolved to true, another test is made, and so on. Immediate IF statements should be used sparingly as they can be quite slow.
252
User Interfaces Unleashed PART III
FIGURE 10.8 The placement of an expression changes the result.
The report could use an Immediate IF statement to mark those products which have sales equal to or greater than 500 hundred units. To do this, create a text box control at the right side of the ProductID header and enter the following formula in its control source: =IFF([Sum of Quantity]>=500,”High”, “”)
Note The [Sum of Quantity] field was created when we defined the Sum in the subsection “Using Calculation Functions.”
Using User-Defined Functions from the Report’s Module Sometimes, the expression becomes too complex to keep in a single IIF() statement. When this happens you can create a function tailored exactly to your needs and then call that function from the report. The example in Listing 10.1 shows how Immediate If, evaluating the Sum of Quantity could be rewritten in the report’s module and called from a control on the report.
Reporting Unleashed CHAPTER 10
253
While viewing the report in Design view, choose Code from the View menu. This brings you into the reports module where you can create subroutines and functions used in this report. LISTING 10.1
Shows the Function
Function HiLowTest(Quantity As Double) As String HiLowTest = Array(“”, “High”)(Abs(Quantity >= 500)) End Function
You could have used a pedestrian If Then Else test, but, after all, this is an Unleashed book and you already know how to write If Then tests. Instead HiLowTest is written using an array and the absolute value of the test Quantity >= 500 as the index into the array. Broken out into its component parts, Quantity >= 500 evaluates to a Boolean value: either Quantity is greater than or equal to 500 or it is not. False is equivalent to 0 and True is equivalent to -1. The absolute value of 0 is 0, and the absolute value of -1 is 1. Hence, Abs(Quantity>=500) yields 0 or 1. Array(“”, “High”)(0|1) is a valid expression return and empty string or “High.” As a general rule, you might want to avoid a lot of clever code like this, but that rule does not have to be strictly adhered to. The name of the function HiLowTest is pretty self-explanatory and a comment describing the behavior would satisfy any human reader sufficiently. Now you can replace the IIF() function with the following: =HiLowTest([Sum of Quantity])
By using the function, you can provide a meaningful name to the behavior and more easily step into and debug the code (by placing a breakpoint in the function). Also, placing the function in the report module allows you to reuse the function anywhere else in your report, ensuring behavioral consistency. The basic idea is that a report is an object like any other. It is desirable to have meaningfully named procedures and to reuse code as much as possible.
Using User-Defined Functions from a Separate Module 10 REPORTING UNLEASHED
There are times when the calculation you are using on a report is also used on a form and by queries. In these cases it might be a good idea to write the function in a separate module object so your application’s queries, forms, and reports can always get consistent results. The following example shows a bare-bones function to convert a string to proper case. This is the kind of function that could be called from many places in an application.
254
User Interfaces Unleashed PART III
This function uses the new Split() function in Access’s VBA. Split() will parse a string into different array elements based on a delimiter you define (spaces are used by default). This new string primitive promises to have many uses in Access 2002. In your database it will take care of the improper capitalization of products such as “Chartreuse verte,” “Gravad lax,” and “Valkoinen suklaa.” The function is very simple. It takes a string as an argument, parses it into an array (varArray), and then loops through the array, making the first character of each element uppercase with the UCase() function. In order to return words with their first letter capitalized, the function uses the left and right functions to separate the first letter from the left of the word. These groups of letters are then rejoined or concatenated to form the whole word again. Likewise, the elements of the array are concatenated into one string to re-create the original string, but in proper case. Listing 10.2 shows how this is done. LISTING 10.2
Capitalizing All First Characters and Using the New Split Function
Function MakeProper(ByVal Str As String) As String Dim varArray As Variant Dim I As Integer Dim Upper As Integer Str = LCase(Str) varArray = Split(Str) Upper = UBound(varArray) For I = 0 To Upper MakeProper = MakeProper & UCase(Left(varArray(I), 1)) & _ Right(varArray(I), Len(varArray(I)) - 1) & “ “ Next MakeProper = Trim(MakeProper) End Function
Using Concatenation Concatenation is extremely common in advanced reports. It enables you to join fields together so they are easier to print and present. When you concatenate two data elements, they can no longer be treated independently. In other words, a form that shows a customer’s concatenated last and first name cannot (without a lot of coding) be used to enter new names.
Reporting Unleashed CHAPTER 10
255
Concatenation is performed with the concatenation operator, the ampersand character [&]. It is also possible to use a [+], but formulas concatenating customer numbers with account numbers can be confusing to a developer or user if the [+] is used. You will see more uses for concatenation in a mailing label example later in this chapter. Example: =”Access” & Space(1) & “2002” & Space(1) & _ “Development” & Space(1) & “Unleashed”
returns “Access 2002 Development Unleashed”
You can test this statement through the immediate window. From the module’s View menu, choose Immediate Window, or press Ctrl+G to gain access to the immediate window. In the Immediate window, type ?MakeProper(“access 2002 development unleashed”)
and press Enter. If everything was entered correctly, you should get “Access 2002 Development Unleashed” as a result. When concatenating, there are three syntaxes to be aware of: • Field names must be surrounded by square brackets if there are spaces in the name (for example, [Order ID]), but for clarity, it is a good practice to use brackets as a rule. • Text strings must be surrounded by quotes—for example, “Attention”. Also consider the use of Chr(34), the ASCII character representing the double-quote, when dealing with quotes in code. • Date values must be surrounded by pound signs, for example #7/27/1997#. The next step is to employ this function on the report. It will change the product names to proper case. In the Design view of the report, change the control source property of the ProductName control to the following: =MakeProper([ProductName])
REPORTING UNLEASHED
In some cases, this would be all you have to do. However, in this case, it’s not so simple. Because this control has the same name as a field in the report’s recordsource, the function will get confused and return #Error for each record. To distinguish the control name from the field name, you need to provide a distinct name for the text box control. By
10
256
User Interfaces Unleashed PART III
prefixing the Name property of the text box with TextBox, you end up with a distinct control name: TextBoxProductName. Now the report will not confuse the field ProductName with the control TextBoxProductName. Note Some developers prefer prefix naming conventions. It is a matter of style, but I generally prefer whole words. There is no single, universal naming convention employed in VBA and whole words leave little room for ambiguity.
When you view the report as it appears in Figure 10.9, in Print Preview mode, you can see the few instances where the names were changed to proper case. So far you have seen how to make a simple report and a more complicated one with the wizard. You have also seen how to modify the report after it was created; you’ve examined groupings, calculations, concatenation, and the use of custom functions in reports. These topics will carry you through the creation of 90% of the reports you will have to make for an Access database. FIGURE 10.9 The products now have names in proper case.
Working with Subreports Just as forms have a main form/subform capability, reports have a main report/subreport capability as well. Subreports are reports within a report, and they are often used to show
Reporting Unleashed CHAPTER 10
257
related records. They can also be used to show subsets of data consistently through different reports. When you use a subreport, you are able to take advantage of the formatting flexibility two reports will give. When working with a one-to-many relationship between the records in the main report and the records in the subreport, the main report is known as the parent and the records in the subreport are its children. Though the effect can often be accomplished with a grouping report configuration, subreports are very useful if you want to print records from several different tables. Figure 10.10 shows a category (Beverages) from Northwind and its subreport of specific products. FIGURE 10.10 Third page of Northwind’s Catalog report shows some of the flexibility offered by subreports.
Creating a Simple Subreport A typical subreport has a one-to-many relationship between the parent records and the child records. Make a note of the related fields between the two tables or queries. 1. Create a report for the parent records. This will be the main report. 2. Create another report for the child records. This will become the subreport.
10 REPORTING UNLEASHED
3. In the toolbox deselect the Control Wizards tool button. (This will prevent the Subreport Wizard from running when you paint a subreport on the parent report.) From the toolbox, select the subform/subreport tool. Using the subreport tool, draw a rectangle in the Detail section of the parent report indicating where the subreport should be placed.
258
User Interfaces Unleashed PART III
4. In the Properties window, set the subreport’s SourceObject property to the name of the subreport created in step 2. 5. If two fields—one from each report—have the same name, Access will automatically add the LinkMasterFields and LinkChildFields properties for the subreport. If they have different names, manually enter the field names linking the parent report to the child report by typing a comma-delimited list of linking field names. Note The LinkChildFields properties require the name of the underlying field, not the name of the report’s control displaying the field. The LinkMasterFields will accept the control name.
Caution If the main report and the subreport are related, the LinkMasterFields/ LinkChildFields properties must be set correctly for the report to work. It is possible to have unrelated main report/subreport constructions. Such cases might involve disclaimers or address blocks used in many reports, but displayed as a subreport for consistency and maintainability. It is even possible to have a main report which is based on no records at all.
The display of subreports within Access 2002 has been enhanced from earlier versions. In earlier versions, the subreport appeared as a blank empty box in the Design view of the main report. Now it displays more useful information about which fields are being used by the subreport. Better still, the subreport is editable from the Design view of the main report, as shown in Figure 10.11. You can address the properties and controls of the report as never before. This is sure to save time and aggravation. In earlier versions, the developer had to return to the report container and open the subreport’s report object in a separate window to make modifications to the subreport. There’s another kind of report that doesn’t quite fit this form, but is still quite common: mailing labels. The next section will look at this type of report and some of the peculiar aspects of them.
Reporting Unleashed CHAPTER 10
259
FIGURE 10.11 Selecting controls in the subreport for modification.
Creating Simple Mailing Labels Though you might never have a need to create mailing labels per se, the same techniques can be used for a variety of other things, such as name tags for a conference, tabs for your technical documentation, equipment identification tags, and so on. Access provides a Label Wizard that can prepare a report to print labels against hundreds of different formats provided by Avery, Zweckform, and others. These formats can also be altered with the wizard or later. To create labels, simply create a new report, select Label Wizard from the New Report dialog box, and choose Customers as the records source. Click the OK button to start the Label Wizard.
10 REPORTING UNLEASHED
1. Choosing the format for your labels couldn’t be easier than selecting the matching manufacturer’s product number. The dialog box in Figure 10.12 shows the exact measurements of some of the hundreds of common labels known to Access, and it will automatically format your report to accommodate them. You have to choose the unit of measurement, whether the forms are individually sheet-fed (most common) or continuous, and whether they are measured in English units (inches) or metric units. Each selection you make for measurement and label type changes the choices of product numbers. You can filter the selection by the label manufacturer.
260
User Interfaces Unleashed PART III
Avery is the default because they are the most widely used and many other manufacturers conform to their measurements and will label their products with a compatible Avery product number. Tip If you ever find yourself in a situation where there are no preset label formats that match your needs, you can create your own label format through the Custom dialog box.
2. When you have found the label product that matches the labels you are using, move to the next dialog box in the Wizard to choose the font and size of the lettering. Because Windows allows you to choose any font and font size you like, it is possible that you might choose a font and a size which is too large for your label. The dialog box shows you what your label might look like with the font and size you have chosen, so you are unlikely to be surprised when they are actually printed. FIGURE 10.12 Choose the label template that matches the labels you are printing on.
3. The Next button will take you to the dialog box, shown in Figure 10.13, where you determine how the label will look. The large blank area on the right contains the merge fields for your prototype. You can move the fields from the data source by double-clicking them or by using the > button. In order to get a new line, you must place your insertion point at the end of a prototype line and press Enter. After a line is created, you cannot separate its elements into separate lines. To delete something from the prototype, you can select it with your mouse pointer and press Delete. Entering text in the prototype box is the same as entering text anywhere
Reporting Unleashed CHAPTER 10
261
else: Just point, click, and type. Everything you do in the prototype box will affect every label. FIGURE 10.13 A completed prototype label.
The prototype shown in Figure 10.13 will create a label with the company name at the top, followed by the address and the individual to whose attention the mail will be sent. Notice that a comma and a space follow the {City}. These were typed in and will appear on every label. The same applies to Attn: at the bottom of the label. 4. Moving to the next step in the Label Wizard gives you the option of changing the sort order for the labels. You can choose to sort by more than one field (for example, last name and then first name) or by just one field. The labels will be sorted in the order they are found in the recordsource if no selection is made. When creating mailing labels