Vfp9 (Vfp9focus) Visual Foxpro 9 Code-Focus

download Vfp9 (Vfp9focus) Visual Foxpro 9 Code-Focus

of 68

Transcript of Vfp9 (Vfp9focus) Visual Foxpro 9 Code-Focus

  • 5/20/2018 Vfp9 (Vfp9focus) Visual Foxpro 9 Code-Focus

    1/68

  • 5/20/2018 Vfp9 (Vfp9focus) Visual Foxpro 9 Code-Focus

    2/68

  • 5/20/2018 Vfp9 (Vfp9focus) Visual Foxpro 9 Code-Focus

    3/68

  • 5/20/2018 Vfp9 (Vfp9focus) Visual Foxpro 9 Code-Focus

    4/68

    Features

    8 Walking on Cloud 9.0 of Visual FoxPro

    So just what was the Visual FoxPro team thinking whenthey planned Visual FoxPro 9.0? Here is what they want-ed to accomplishstraight from the VFP team.Microsoft Visual FoxPro Development Team

    12 Whats New with Data in Visual FoxPro 9.0

    With support for new data types and removing many lim-its from the SQL language, it's now easier to develop asingle code base that works with the Visual FoxPro 9.0native data engine and SQL Server.David T. Anderson

    22 The Visual FoxPro 9.0 Report Writer

    Explore the new features of the Report Writer, includingdealing with legacy data, report protection, user interfaceenhancements, layout objects, and data groups, plus thegreat new multiple detail band feature.Cathy Pountney

    36 Controls, Events, Commands, and More

    The new productivity tools help you build interesting anduseful applications with just a few carefully chosen bits ofcode.Claudio Lassala

    44 Extending the Visual FoxPro 9.0 Report

    System

    The new reporting engine splits responsibility for ring between the report engine, which now dealwith data handling and object positioning, and a n

    ject known as a report listener, which handles renand output.Doug Hennig

    54 Visual FoxPro 9.0 IDE Enhancements

    A little bit here and a little bit there make Visual F9.0 even more productive. Rod provides an overvthe latest IDE enhancements to your favorite toolRod Paddock

    56 Interop: Making .NET and

    Visual FoxPro Talk to Each Other

    Theres no doubt that many Visual FoxPro deveneed to live in a world that supports older applicand new development architectures. But why r

    business rules that already work? Our writers ofhighlights to make it all work together.Claudio Lassala, Markus Egger, Rod Paddock

    Departments

    6 CoDe Compilers

    41 Advertisers Index

    CoDe Focus Magazine is a supplement of Code Component Developer Magazine. Code Focus reports in-depth on newly released stechnologies. The supplement is available to CoDe Component Developer Magazine subscribers that have noted interest in the stechnologies covered in the Code Focus supplements.

    Subscribe to Code Component Developer Magazine

    US subscriptions are US $29.99 for one year; Canada, Mexico, and US territories are US $44.99; Europe is US $49.99; other countri$59.99. Payments should be made in US dollars drawn on a US bank. American Express, MasterCard, Visa, and Discover credit caraccepted. Bill me option is $5 additional and available only for US subscriptions. Back issues are available. For subscription informemail [email protected] or contact customer service at 832-717-4445 ext 10.

    Subscribe online at www.code-magazine.com

    CoDe Component Developer Magazine (ISSN # 1547-5166) is published bimonthly by EPS Software Corporation, 6605 Cypresswood Suite 300, Spring, TX 77379. POSTMASTER: Send address changes to CoDe Component Developer Magazine, 6605 Cypresswood Suite 300, Spring, TX 77379.

    T

    ABLE

    OF

    CONTENTS

    Table of Contents www.code-ma4

  • 5/20/2018 Vfp9 (Vfp9focus) Visual Foxpro 9 Code-Focus

    5/68

  • 5/20/2018 Vfp9 (Vfp9focus) Visual Foxpro 9 Code-Focus

    6/686

    CODE

    COMPILERS

    Volume 2 Issue 1

    Group Publisher

    Markus Egger

    Associate Publisher

    Rick Strahl

    Editor-in-Chief

    Rod Paddock

    Managing Editor

    Ellen Whitney

    Content Editor

    Melanie Spiller

    Writers In This Issue

    David T. Anderson Markus EggerDoug Hennig Claudio LassalaKen Levy Cathy PountneyRod Paddock

    Technical Reviewers

    Markus EggerRod Paddock

    Art & Layout

    King Laurin GmbH

    [email protected]

    Production

    Franz WimmerKing Laurin GmbH39057 St. Michael/ Eppan, Italy

    Printing

    Fry Communications, Inc.800 West Church Rd.Mechanicsburg, PA 17055

    Advertising Sales

    Vice President, Sales and MarketingMichelle Yates703-328-0333

    [email protected]

    Sales Managers

    Erna Egger+43 (664) 151 0861

    [email protected]

    Tammy Ferguson

    832-717-4445 ext [email protected]

    Circulation & Distribution

    General Circulation: EPS Software Corp.

    Subscriptions

    CoDe Focus Magazine is a supplement of Code Com-ponent Developer Magazine. Code Focus reports in-depth on newly released specific technologies. Thesupplement is available to CoDe Component Develop-er Magazine subscribers that have noted interestin the specific technologies covered in the Code Focussupplements.

    Subscriptions Manager

    Cleo Gaither832-717-4445 ext 10

    [email protected]

    Subscribe to CoDe Component Developer MagazineUS subscriptions are US $29.99 for one year; Canada,Mexico & US territories are US $44.99; Europe is US$49.99; other countries are US $59.99. Paymentsshould be made in US dollars drawn on a US bank.American Express, MasterCard, Visa, and Discovercredit cards accepted. Bill me option is $5 additionaland available only for US subscriptions. Back issuesare available. For subscription information,email [email protected] or contactcustomer service at 832-717-4445 ext 10.

    Subscribe online at

    www.code-magazine.com

    CoDe Component Developer MagazineEPS Software Corporation / Publishing Division6605 Cypresswood Drive, Ste 300,Spring, Texas 77379Phone: 832-717-4445Fax: 832-717-4460

  • 5/20/2018 Vfp9 (Vfp9focus) Visual Foxpro 9 Code-Focus

    7/68

  • 5/20/2018 Vfp9 (Vfp9focus) Visual Foxpro 9 Code-Focus

    8/68

    QUICK

    ID0404012

    Visual FoxPro 9.0 Overview

    Visual FoxPro 9.0 is fully compatible withprevious versions of Visual FoxPro. With itslocal cursor engine, tight coupling betweenlanguage and data, and powerful features,Visual FoxPro 9.0 is a great tool for buildingdatabase solutions of all sizes.

    Its data-centric, object-oriented languageoffers developers a robust set of tools for

    building database applications for thedesktop, client-server environments, or theWeb. Developers will have the necessarytools to manage datafrom organizing tablesof information, running queries, and creatingan integrated relational database manage-ment system (DBMS) to programming afully-developed data management applicationfor end users.

    Walking on Cloud 9.0of Visual FoxProThe Visual FoxPro Team at Microsoft is enthused [sic] to announce Visual FoxPro 9

    Wed like to include some details as an overview to the more detailed articles in this special CoDe Focuissue devoted to Visual FoxPro 9.0.

    Visual FoxPro 9.0 Goals

    Our goals for Visual FoxPro 9.0 were to:

    Maintain backward compatibility Enhance database language and types Add end user UI features Increase developer productivity

    Improve the Report Writer significantly Extend .NET and SQL Server interoper-ability

    Increase extensibility, including Xbasesource code

    Visual FoxPro 9.0

    Product Highlights

    There are so many new features that itshard to limit the discussion. Well start

    with the flexibility to build all typdatabase solutions, move on to repsystem enhancements, and finish updata handling and interoperabilitythese only touch on some the greafeatures youll want to explore onown.

    Flexibility to Build All Types oDatabase Solutions

    Using Visual FoxPro 9.0, you can .NET-compatible solutions with hierarXML and XML Web services. You caexchange data with SQL Server thenhanced SQL language capabilitienewly supported data types.

    You can build and deploy standalonremote applications for WindowsTablet PCs.

    You can create and access COM compand XML Web services that are compwith .NET technology. Visual FoxPallows you to build end-to-end solfrom data entry forms to complex outputs.

    Reporting System Features

    To Visual FoxPros already strong repsystem, weve added an extensibleoutput architecture that provides precontrol of report data output and form

    Theres multiple-detail band support fowith multiple one-to-many relationshi

    You can customize the Print Prwindow with improved display qualimultiple page support. Our new oreports support XML, HTML, formats, and customizable multi-pagepreview windows. The enhanced writer is backward compatible with eVisual FoxPro reports. And flexible chaining allows for more complex

    jobs.

    Walking on Cloud 9.0 of Visual FoxPro www.code-ma8

    Figure 1: Pictured here are some of the Visual FoxPro team members (from left to right): Ken Levy, JohnKoziol, Yair Alan Griver, Calvin Hsia, Randy Brown, Richard Stanton, and Mike Stewart.

  • 5/20/2018 Vfp9 (Vfp9focus) Visual Foxpro 9 Code-Focus

    9/68

  • 5/20/2018 Vfp9 (Vfp9focus) Visual Foxpro 9 Code-Focus

    10/68

    The new ReportListener class provides accessto report generation and rendering events atruntime.

    Powerful design-time hooks with customiz-able builders make your development experi-ence smoother.

    Data-Handling

    and Interoperability

    Three new data types, VarChar, VarBinary,and BLOB, allow for improved interoper-ability with SQL Server. There are extendedSQL language enhancements as well,including more capabilities with SELECT,INSERT, UPDATE, and DELETE state-ments.

    A new function, CAST(), allows you toconvert different data types. You can use thenew binary index to improve performanceusing the deleted tag, and the XMLAdapter

    provides improved nested hierarchical XMLand XSD schema support.

    There are many improvements to client UIfeatures. You can dock forms, anchor formelements to control movement on a formduring resizing, and control the position ofimages on a button using text alignment.

    Theres new word wrap support for checkboxcaptions and rotating text for label captions.Using shapes and lines, you can create poly-gons and Bezier curves. The property sheetprovides support for new font and colordisplay options, extended characters, and

    long expressions.

    You can bind images to non file-basedpictures. You can use List and Combo collec-tions as databinding row sources.

    Member data extensibility adds the ability tospecify custom property editors andfavorites. With the extended system capabil-ities, there are no limits beyond availablememory for arrays, procedure size, andnesting levels.

    Single line background compiling allows you

    to see whether or not your syntax is valid asyou type command lines.

    There are new and improved task panes suchas the Data Explorer pane.

    There are new string functions and a newinline functionICASE()that is similar toDO CASE statements.

    For international solutions weve addedgreater support for using FontCharSets inapplications.

    Common Questions

    As for what will be added to Visual FoxProafter version 9.0 is released, it is too early todiscuss this at the time of writing this article.The Visual FoxPro team welcomes feedbackon how we can improve our developer toolsin the future based on what is disclosed forVisual FoxPro 9.0 and Visual Studio 2005.Details of how we enhance Visual FoxPro,

    how it is packaged, what it is called, andwhen updates will be released probably willnot be disclosed until the first half of 2005.

    A common question is how Visual FoxPro9.0 relates to Visual Studio 2005 and SQLServer 2005. We improved the XML supportin Visual FoxPro 9.0 which will also improve.NET interoperability. We also added somenew data types that will also help for use with

    both SQL Server 2000 and SQL Server 2005.

    Visual FoxPro 9.0 is scheduled to be releasedin late 2004, and the schedule for Longhorn

    is not announced yet. We can only discusshow Visual FoxPro relates to Longhorn onceLonghorn is nearly complete and close to

    being released.

    Although we will not be including nativePDF support in Visual FoxPro 9.0, we areworking to make it very easy for third partiesand FoxPro developers to create a variety ofsolutions for add-on PDF output support.

    We do not have any plans to extend the 2GBdatabase size limit in Visual FoxPro for manyreasons, including the 32-bit architecture thatalready exists within the product. Besides

    using SQL Server 2000, an additional optionis upcoming: SQL Server 2005 Expressextends the 2GB limit of MSDE to 4GB total.

    Although Visual FoxPro will remain 32-bitand will not use 64-bit addressing natively, itwill run in 32-bit compatibility mode. VisualStudio 2005 will support creating native 64-

    bit applications.

    It is up to developers and installing organiza-tions to decide which .NET language is bestfor them. C# is generally for developers wholike to write and control all of their code. Its

    very source code-centric. Visual Basic is forRAD (rapid application development) andease-of-use while providing access to the fullpower of the .NET Framework. For a high-level overview of the language differences,refer to the Visual Studio Roadmap athttp://msdn.microsoft.com/vstudio/productinfo/roadmap.aspx.

    Visual FoxPro 9.0 Availability

    Until March 31st, 2005, the free public betaof Visual FoxPro 9.0 will be available for

    download at http://msdn.com/vfoxpro. Thcan be installed side by side with FoxPro 9.0 or previous versions of FoxPro. There is a time bomb built in

    beta that expires March 31st, 2005. Dcontact technical support for questiothe public beta is unsupported and isused as is.

    Visual FoxPro 9.0 is scheduled to be re

    to manufacturing near the end of 200will be included in all levels of MSubscriptions (Universal, EnterpriseProfessional). For more information MSDN Subscriptions, refer http://msdn.com/subscriptions/prodinfo/leveMSDN Subscription members will be obtain the released version of Visual F9.0 (within a few business days of relemanufacturing). The full product, upgand academic editions will be avapproximately six to eight weeks afteare released to manufacturing.

    Visual FoxPro 9.0 pricing will be the sit was for Visual FoxPro 8.0: the full pis $649US, the upgrade is $349US, aacademic edition is $75US. For a ltime, a $50 rebate will be offered with FoxPro 9.0 (for the upgrade version oU.S. and Canada only) for licensed uVisual FoxPro 8.0.

    To obtain Visual FoxPro, MSDN Subtions, FoxPro gear, and more, http://FoxToolbox.com. Additional informabout Visual FoxPro 9.0 including papers, samples, and links to thirdresources can be found

    http://msdn.com/vfoxpro.

    Visual FoxPro 9.0 System

    Requirements

    To install Microsoft Visual FoxPro 9.0 Psional, we recommend:

    A PC with a Pentium-class processor Windows 2000 with Service Pack 2 o

    operating system 64MB of RAM; 128MB or higher r

    mended

    165MB of available hard disk spacetypical installation, 165MB max20MB of additional hard-disk spaMicrosoft Visual FoxPro 9.0 Prerequi

    A CD-ROM or DVD-ROM drive A super VGA 800 X 600 reso

    monitor, or higher, with 256 colors Microsoft Mouse or compatible po

    device

    Walking on Cloud 9.0 of Visual FoxPro www.code-ma10

  • 5/20/2018 Vfp9 (Vfp9focus) Visual Foxpro 9 Code-Focus

    11/68

  • 5/20/2018 Vfp9 (Vfp9focus) Visual Foxpro 9 Code-Focus

    12/68What's New with Data in Visual FoxPro 9.0 www.code-ma

    What's New with Datain Visual FoxPro 9.0?The Microsoft Visual FoxPro team has a great reputation for

    responding to community requests and the next version is nexception. Most evident in several changes to the data engine, Visual FoxP

    9.0 includes many enhancements for data access and database application

    development.

    Visual FoxPro 9.0 contains more functionalenhancements to the data engine than anyrelease since 3.0. From the new and extended

    functionality in SQL to new data types and a binaryindex, this release demonstrates the power of amature development platform

    for data-centric solutions.

    Changes to the data engine canbe summarized in five majorareas:

    SQL Enhancements: Removalof most hard-coded limits,enhanced sub-query andcorrelation support, supportfor more complex expres-sions, and enhanced UNIONsupport.

    Performance: A new indextype, enhanced performance

    of filtered indexes andimproved SQL performance with TOP n,MIN()/MAX(), and LIKE.

    Commands and Functions: Greater ability tofine-tune how data is accessed and committed,functions to supplement SQL showplan, andeasier immediate expression nesting withICASE().

    New Data Types: Support for VarChar,VarBinary, and BLOB data types, a new CAST()function, and enhancements to existing functionsto control and convert data types.

    Remote Data: Enhanced control over transac-tions, better visibility regarding fetched records,

    rowsets returned from the provider, andCursorAdapter enhancements that bring behaviorin line with remote views.

    Many of these changes improve the Visual FoxPro9.0 client/server story by providing stronger inter-operability with SQL Server. With support for newdata types and removing many limits from the SQLlanguage, it's now easier to develop a single code

    base that works with the Visual FoxPro 9.0 nativedata engine and SQL Server.

    Enough overview, let's dig in!

    SQL Enhancements

    Certainly the best word to describe changes SQL sub-language is MORE! There are no hard-coded limits to the number of elements

    SQL statement. A single

    SELECT statement can cmore tables, moreJOINssub-queries, more nestequeries and more UNthan in previous versions

    There are also no hard-limits on the number ofin an SQL IN list. In veprior to Visual FoxPrSQL IN was mapped INLIST() function; that dency has been removedchange allows an increthe number of argumen

    IN and for better optimiVisual FoxPro 9.0 stops evaluating exprefrom the list as soon as the match is found. Thelpful if the IN condition is not Rushmormized, as performance can be improved by pthe most-likely-to-match values at the beginnthe list. The total number of items is still indlimited by the SYS(3055) function, which co

    buffer memory size, so the higher the settinmore items are supported via IN. (SeCommon Error Messages sidebar for moremation.)

    No Limits?

    No hard-coded limits does not mean limIssues such as available memory and exprcomplexity can still have an impact on whetnot a very long and complex statement can b

    but you'll have to work hard to find manworld limitations.

    Enhanced Sub-Query Support

    Sub-queries have always been powerful in thlanguage. They can be used as filters by pthem on the right side of a comparison

    David T. AndersonDavid is currently serving as acontract tester with the VisualFoxPro team at Microsoft,testing the data enhancementsmade to Visual FoxPro 9.0 andimplementing performancebenchmarks such as the Trans-action Processing Council's

    TPC-H.

    With 22 years of applicationdevelopment experience in thePC industry for government,military, educational institu-tions, and private industry,David uses his experiencerelating Enterprise Architectureand Organizational Maturity toassist organizations in deter-mining the most appropriatesoftware processes for theirneeds.

    You can reach David [email protected]

    Fast FactsChanges to the data engine in

    Visual FoxPro 9.0 provide

    developers with enhanced power,

    flexibility, and performance.

    From the greatly expanded SQL

    sub-language to new data types and

    Rushmore optimizations, this

    release demonstrates the FoxPro

    teams commitment to producing

    a world-class data-centric

    development language.

    12

    QUICK

    ID0404022

  • 5/20/2018 Vfp9 (Vfp9focus) Visual Foxpro 9 Code-Focus

    13/68

    WHERE clause. In Visual FoxPro 9, sub-queriescan also be used as part of the SELECT list (calleda projection) and in the FROM clause (often calleda derived table).

    When used as a projection, if the sub-query doesn'treturn any records, a NULL value is returned.Correlation is supported with projection (more onthis in a minute).

    A SQL statement that uses projection looks like this:

    SELECT ;

    C.CustomerID, ;

    C.CompanyName, ;

    (SELECT YTD_Sales FROM Sales_02 WHERE ;

    C.CustomerID = Sales_02.CustomerID) AS Y02,;

    (SELECT YTD_Sales FROM Sales_03 WHERE ;

    C.CustomerID = Sales_03.CustomerID) AS Y03,;

    (SELECT YTD_Sales FROM Sales_04 WHERE ;

    C.CustomerID = Sales_04.CustomerID) AS Y04 ;

    FROM Customers C

    This SELECT statement returns the customer IDand company name along with year-to-date salesfrom warehoused tables for the last three fiscalyears.

    A restriction on a projection is that the sub-queryshould return only one column and no more thanone record for each record in the containingSELECT.

    Another valuable use of a projection is when itsused as part of an expression.

    SELECT ;

    C.customerID, ;

    C.companyname, ;

    SUM(D.quantity*D.unitprice) AS CustTotal ,;

    (SUM(D.quantity*D.unitprice) / ;

    (SELECT SUM((quantity*unitprice)-discount) ;

    FROM OrderDetails D2) ;

    )*100 AS PctTotal ;

    FROM Customers C ;

    INNER JOIN Orders O ;

    ON C.customerID = O.customerID ;

    INNER JOIN OrderDetails D ;

    ON O.orderid = D.orderid ;

    GROUP BY C.customerID, C.companyname, O.orderID ;

    ORDER BY pctTotal DESC

    This SELECT statement returns customer ID,company name, total sales, and a percent of totalsales against all customer sales.

    Note that the sub-query in the SELECT list is partof a complex expression that includes an aggregatefunction. Now that's flexibility!

    A derived table as sub-query allows you to treat theresults of a sub-query as though it were its owntable.

    Consider the following example:

    SELECT ;

    C.customerid, ;

    P.product_count AS p_count;

    FROM Customers C, ;

    (SELECT c2.customerid, ;

    COUNT(DISTINCT D.productID) AS p_count ;

    FROM Customers C2 ;

    INNER JOIN Orders O ;

    ON C2.customerid = O.customerid ;

    INNER JOIN OrderDetails D ;ON O.orderid = D.orderid ;

    GROUP BY c2.customerid) AS P ;

    WHERE C.customerID = p.customerID ;

    AND P.p_count >= ;

    (SELECT (COUNT(*)*.50) FROM Products) ;

    ORDER BY p.product_count DESC

    This SELECT statement returns customer ID andproduct count for all customers who havepurchased at least 50% of the product line.

    Notice that the derived table has an alias of "P"

    that is designated the same way you would aliasa column, using the AS clause (required). It'salso important to note that the sub-query can becomplex (in this case, joining to two othertables) and that the results from the derivedtable can be used as a condition of the WHEREclause and in the ORDER BY of the top-mostSELECT.

    Unlike a projection, the derived sub-query canreturn more than one column and more than onerecord. It cannot be correlated. All sub-selects areexecuted before the top-most SELECT is evalu-ated.

    Sub-queries are also supported in the SET list of aSQL UPDATE statement. Only one sub-query isallowed in a SET clause and if there is a sub-queryin the SET clause, a sub-query in the WHEREclause is not allowed.

    Better Correlation Support

    The SQL UPDATE and SQL DELETE commandsnow support correlation. A correlated statementincludes a FROM clause to relate the records beingaffected to another table.

    Common ErrorMessages

    As your SQL statements glonger and more complexwill become familiar with tfollowing errors:

    Error # 18: Line is too long

    Error # 1812: SQL: Statemis too long

    Error# 1814:Queries of thtype are not supported.

    Error# 1845: Too Complex

    Error# 2189: SQL: Too mafields in final or intermediaresult have the same nam

    If you dynamically build Syou may want to consider

    adding traps for these errothat you can isolate them analysis.

    SYS(3055)

    If you are not bound by a memory environment, conusing SYS(3055) to set thcomplexity level of the FOWHERE clauses to itsmaximum value of 2040 wyou set up the environmenyour applications. This all

    more complex SQL statemand more values with IN. Sthe Help files for a list of ocommands and functions are affected by this setting

    What's New with Data in Visual FoxPrwww.code-magazine.com

    A single SQL SELECTstatement can contain more tables,

    more JOINs, more sub-queries,more nested sub-queries, and more

    UNIONs than ever before.

  • 5/20/2018 Vfp9 (Vfp9focus) Visual Foxpro 9 Code-Focus

    14/68

    For example:

    DELETE products ;

    FROM mfg ;

    WHERE mfg.productID = products.productID;

    AND mfg.discontinued = .t.

    This DELETE statement deletes all productsmarked as discontinued from a table provided bythe manufacturer.

    A correlated UPDATE looks similar:

    UPDATE products ;

    SET unitprice = mfg.msrp *.90 ;

    FROM mfg ;

    WHERE mfg.productID = products.productID

    This UPDATE statement sets the unit price for aproduct at 90% of the manufacturers suggestedretail price.

    You may be tempted to use a correlated sub-queryas this is also supported. Just be aware that whenusing a sub-query it's like doing an outer join. Forevery record that is not found in the sub-query, the

    value returned is NULL. This may not give thedesired results.

    UPDATE products ;

    SET unitprice = ;

    (SELECT ( msrp *.90 ) ;

    FROM mfg ;

    WHERE mfg.productID = products.productID)

    This UPDATE statement sets the unit price for aproduct at 90% of the manufacturers suggestedretail price for every product found in the Manufac-turers table. The price for products not found in the

    Manufacturers table is set to NULL.

    Note that this statement operates on every record inthe Products table; in the previous statement, onlyupdated records that matched in the Manufacturerstable were involved.

    View and Query Designers

    Unfortunately, due to the complexity of the SQLstatements you can write with these enhancements,the Query and View Designers do not support manyof the sub-query changes to SQL.

    Also, with the hard-coded limits of SQremoved, the Designers no longer convert INLIST(). The INLIST() function still has a l24 elements.

    Enhanced UNION Support

    In addition to having no hard-coded limits number of UNIONs, you can now use a Uinside the result set that is used by an IN

    INTO.

    You can now also ORDER BY using UNION. The referenced field must be pin the SELECT list for the last SELECT UNION.

    Performance

    Regardless of whether you are doing remotaccess or relying on the powerful nativeengine, performance has always been a priorVisual FoxPro. Visual FoxPro 9.0 enhances th

    engine even further.

    Binary Indexes

    This new index type is a specialized index, defor one thing:

    INDEX ON DELETED() TAG DELETED BINARY

    The new index type can be used with anyNULL logical expression. Other restrpreclude the use of a FOR expressionASCENDING, DESCENDING, UNIQUECANDIDATE keywords.

    SET ORDER TO is not supported and the INON command sets the current order to 0. Alscannot use a Binary index with any Seek ope

    The big advantage of a Binary index is its sBinary index for a table with 8,000,000 recapproximately 30 times smaller (1.1MB 31.5MB). Smaller means faster I/O and APPEND and REPLACE, all with the samemore optimization as a non-binary index osame expression.

    There is a trade-off to consider. Rushmoremization is faster if the amount of records re

    is more than 3% of the total records (aboufaster when all records match the condHowever, Rushmore optimization is sloweramount of records returned is less than 3% two times slower when 0 records match the tion). It is likely that the 3% threshold will bsmaller as the number of records in theincreases.

    Turning your DELETED indexes into indexes is an easy way to start taking immadvantage of Visual FoxPro 9.0 perforenhancements. Just be sure that all clients acc

    John KoziolTest Engineer,Visual FoxPro TeamMicrosoft

    An overall area of enhance-ments for Visual FoxPro 9.0includes more event hooks andfewer capacity limitations. You

    can now hook into WindowsAPI events with the BINDE-VENTS() function. Now onlylimited to available memory,you can create arrays largerthan 64K and nest DOs deeperthan 128 levels. Also, many ofthe limits on clauses in SQLstatements have beenextended. You can write yourown report handlers andenhance the Visual FoxProinterface via MemberData.Visual FoxPro 9.0 is a greatupgrade for Visual FoxPro

    developers who want to havefewer limits in building applica-tions!

    What's New with Data in Visual FoxPro 9.0 www.code-ma14

    Many of these changes improveFoxPro's client/server

    capabilities by providingstronger interoperability with

    SQL Server.

  • 5/20/2018 Vfp9 (Vfp9focus) Visual Foxpro 9 Code-Focus

    15/68

  • 5/20/2018 Vfp9 (Vfp9focus) Visual Foxpro 9 Code-Focus

    16/68What's New with Data in Visual FoxPro 9.0 www.code-ma16

    your data are upgraded, as this new index cannot beread by prior versions.

    Rushmore Optimizations

    There are a few new Rushmore optimizations thatdo not require changes to data and index structures.

    Top N [PERCENT], an optimization made to SQL,provides improved performance. This operation

    returns only the top number or percent of records ina result set as controlled in the ORDER BY clause.This change in Visual FoxPro 9.0 eliminates recordsfrom the sort process that don't belong in TOP N asearly as possible, reducing comparison operationsand decreasing file I/O in low memory situations.This also has the side-effect of only returningexactly N [PERCENT] records.

    In previous versions, if there was a tie for Nth place,all records that matched the tie were included,resulting in getting back more thanNrecords.

    If this change in behavior is not desired, consider

    bracketing the SQL call with SET ENGINEBE-HAVIOR 80.

    The only limitation to this optimization is that TOPN PERCENT cannot be used unless the entire resultset can be read into memory at once.

    When appropriate, Visual FoxPro 9.0 uses filteredindexes to optimize MIN() and MAX() aggregatefunctions in FOR DELETED() and FOR NOTDELETED() only. This improves MIN()/MAX()performance, if such an index exists.

    The Like sometext% operator is now fully opti-mizable when the string ends in a wildcard. (Note

    that this is not the case when the comparison valuebegins with a wildcard or when the wildcard isembedded within the string.) This optimizationscenario works like WHERE field = sometext.

    More INDEX Smarts

    Visual FoxPro 9.0 is even smarter in how it utilizesexisting indexes to achieve Rushmore optimization.For example:

    INDEX ON DELETED() TAG DELETED

    This index is used to optimize both NOT

    DELETED() and DELETED() conditions withoutthe presence of a tag created by INDEX ON NOTDELETED().

    Just like the MIN()/MAX() optimization, VisualFoxPro 9.0 uses a FOR NOT DELETED() filter onan index to optimize a DELETED() or NOTDELETED() query. Whenever it is possible to deter-mine that a condition should filter on DELETED()or NOT DELETED(), a filtered index FORDELETED() or FOR NOT DELETED() is used inthe event that no non-filtered indexes exist. Takethis upgrade opportunity to review the indexes you

    currently deploy. If you are unable to use a index, you may find that with these optimizyou can at least drop a few existing indexes.

    If only indexes filtered FOR NOT DELETED(used for Rushmore optimization andDELETED is ON, additional NOT DELEoptimization is unnecessary.

    Commands and FunctionsA few commands and functions have been exto provide greater control over how and Visual FoxPro reads and writes data to disk.

    Fine-Tune How Data is

    Accessed and Committed

    It is now possible to specify fractions of a secothe second parameter of the SET REFcommand. The second parameter is used to sthe number of seconds between refreshing

    memory buffers with current data from diskcan also specify a value of 1, which forces FoxPro to always read data from the hard drivlowest setting for the second parameter is .00

    Setting this value to a low number causesperformance degradation as the number of reincrease, especially across a network, so use iingly.

    The SYS(1104) function purges memory cacprograms and data, and it clears and ref

    buffers for open tables. In Visual FoxPro second parameter scopes the operation to a swork area or alias. This is valuable becauseSYS(1104) when a large number of bufferedare open can result in slow performance whil

    buffered table refreshes.

    The FLUSH command is used to ensurchanges made to tables, indexes, and files areto the disk. In Visual FoxPro 9.0, the Fcommand has been enhanced in two ways:fying FLUSH areas, and calling the FlushFileBfunction.

    You can now be specific about the filenamearea, or alias to be FLUSHed. Although thigranularity is handy, it's the FORCE keywordvery useful in scenarios where Visual FoxP

    A derived table,such as a sub-query, allows yo

    to treat the resultsof a sub-query as though it

    were its own table.

  • 5/20/2018 Vfp9 (Vfp9focus) Visual Foxpro 9 Code-Focus

    17/68What's New with Data in Visual FoxPrwww.code-magazine.com

    writes data to the disk but the operating systemkeeps the writes cached.

    When you use the FORCE keyword, Visual FoxPro9.0 includes a call to the Windows API FlushFile-Buffers function. This ensures that even operatingsystem buffers are written to disk.

    Some examples of using the enhanced FLUSHcommand include:

    FLUSH "c:\data\customers.dbf"

    FLUSH "c:\data\customers.dbf" FORCE

    FLUSH IN 1 FORCEFLUSH IN customer FORCE

    FLUSH "c:\test.txt" FORCE

    FLUSH FORCE

    In versions prior to Visual FoxPro 9.0, using a SQLSELECT statement meant that the results werealways pulled from disk. This meant that if youwanted to query uncommitted changes from a

    buffered table, you were forced to use proceduralcommands. Now it's possible to specify for eachtable in a SELECT statement whether to read fromthe disk or from the local buffer using SETSQLBUFFERING and SELECT WITH

    (Buffering = ).

    Some examples of how to use WITH (BUFFERING) include:

    SELECT * FROM Customer WITH (BUFFERING = .t.)

    SELECT * FROM Orders WITH (BUFFERING = lUseBuffer)

    SELECT DISTINCT c.city, o.shipcity ;

    FROM customers C WITH (BUFFERING=.T.) ;

    JOIN orders O WITH (BUFFERING=.T.) ;

    ON c.customerID = o.customerID

    Notice that each table referenced has its own WITHBUFFERING clause. If no BUFFERING clause isused, Visual FoxPro 9.0 respects the SETSQLBUFFERING value (whose default is .f.).

    Support for BUFFERING is only available on localVisual FoxPro 9.0 data. It is not supported on datafrom back-end databases, so it should not be usedwith SQL Pass Through.

    When working with a table that is involved in ROWbuffering, using the WITH BUFFERING command

    causes the current record to be committed beforethe statement is executed.

    The SET SQLBUFFERING command is scoped tothe current data session. When the WITHBUFFERING clause is used, it overrides the SETstatement.

    CAST()

    The new CAST() function is modeled after the SQLServer function by the same name. It is useful bothin and out of SQL. Used inside a SQL statement,you can write SQL code that is more TSQLcompliant. As you might expect, this functionconverts a data expression to another data type.

    Used within a SQL statement, the CAST() functionlooks like this:

    SELECT CustomerID, ;

    CAST(nAmount*nRate AS N(8,2)) ;

    FROM SALES

    SELECT CustomerID, ;CAST(nAmount*nRate AS B NOT NULL) ;

    FROM SALES

    SELECT CustomerID, ;

    CAST(nAmount*nRate AS C(10)) ;

    FROM SALES

    SELECT foo.*, ;

    CAST(NULL as I) AS IntegerField ;

    FROM foo

    Notice that there is the ability to specify whether

    NULLs are acceptable. If not specified, CAST()inherits NULL behavior from the expression, ifpossible.

    ICASE()

    Another function, ICASE() emulates TSQLs CASEbranching construct. This function is similar toIIF(), the immediate IF function. The value ofICASE() is that it doesn't require the kind of uglyand verbose nesting syntax of IIF().

    ICASE() works by requiring condition/result para-meter pairings. The first parameter is the condition

    expression to evaluate, and the second parameter isthe result if the condition provided in the first para-meter evaluates to True. If the condition evaluates toFalse, the second parameter is skipped and the nextcondition/result parameter pair is evaluated. Thiscontinues for each parameter pairing. If the parame-ters are not passed in pairs, Error # 11 is thrown.

    Just like the CASE/ENDCASE syntax, there is anOtherwise option that can be passed as the lastparameter to the function. If this parameter is notpassed and all other condition parameters evaluateto False, ICASE() returns a NULL.

    Regardless of whetheryou are doing remote data access

    or relying on the powerfulnative data engine, performance

    has always been a priority.

    Calvin Hsia

    Lead Developer,Visual FoxPro TeamMicrosoft

    One of the many cool thinVFP 9.0 allows you to creabetter photo database app

    tions without using the gefield using the new BLOB type and enhancements toimage properties. There amany new features in theProperty Sheet includingcustom font and color conas well as a custom Favortab for categorizing propeand methods. There are nfunctions and events in VFspecifically designed forbuilding even more advanTablet PC based applicatio

  • 5/20/2018 Vfp9 (Vfp9focus) Visual Foxpro 9 Code-Focus

    18/68

    Here is an example of ICASE() used outside of aSQL statement:

    nHour = HOUR(DATETIME())

    ? ICASE( nHour = 8, "breakfast" , ;

    nHour = 10, "caffeine" , ;

    nHour = 12, "lunch" , ;

    nHour = 15, "caffeine" , ;

    nHour = 18, "dinner" , ;

    "snack" ;

    )

    Up to 100 condition/result parameter pairs can bepassed to the ICASE().

    SYS(3092) Output to a File

    This new SYS() function works in conjunction withSYS(3054), the SQL Showplan function. WithSYS(3092), you can specify a filename to which theresults of SYS(3054) output are sent.

    An example of how to use these functions togetheris listed here:

    SYS(3054,12,"dummyVar")

    SYS(3092,"ShowPlan.txt")OPEN DATABASE HOME(2)+"Northwind\Northwind"

    SELECT * ;

    FROM Customers INTO CURSOR temp1

    SELECT * ;

    FROM summary_of_sales_by_year ;

    INTO CURSOR temp2

    SYS(3092,"")

    CLOSE DATA ALL

    MODIFY FILE Showplan.txt NOWAIT

    If you don't include a variable name as theparameter for SYS(3054), results are echoedcurrent window.

    New Datatypes

    In an effort to provide better compatibilitback-ends such as SQL Server, Visual FoxPhas added three new data types, VaVarBinary, and BLOB. These data types cused as part of a local table, which is creausing the CAST() function or mapped to retrieving results from remote data.

    VarChar

    The VarChar is a character data type that padded with spaces to the length of theThis provides similar functionality as ANSI_PADDING ON in SQL Server.

    In addition, if spaces are included with the ovalue, they are not trimmed.

    It's important to note that when using exprecombining VarChar with Character data typresult is always of the type VarChar.

    Because a VarChar is a fixed length field in FoxPro 9.0, the maximum field length is 255acters. In SQL Server, it is possible for a VarChar field to have a length

  • 5/20/2018 Vfp9 (Vfp9focus) Visual Foxpro 9 Code-Focus

    19/68

  • 5/20/2018 Vfp9 (Vfp9focus) Visual Foxpro 9 Code-Focus

    20/68

    Like the VarBinary type, Visual FoxPro 9.0 does notperform any code page translation and its content istreated as binary content.

    The BLOB datatype is an ideal candidate to replacethe legacy General field. Pictures and other mediacan be stored in a BLOB and then rendered usingthe Image control PictureVal property.

    MODIFY MEMO of a BLOB displays a HEX dumpof the binary data.

    SET EXACT & Binary Comparison

    With Binary data types comes a difference inbehavior with SET EXACT and SET COLLATE.

    SET EXACT ON specifies that expressions mustmatch exactly to be equal. However, with VarBinarytypes whose values are padded with CHR(0), thetrailing bytes are ignored for the comparison. Theshorter of the two expressions is padded on theright with CHR(0) bytes to match the length of thelonger expression.

    SET EXACT OFF specifies that expressions mustmatch up exactly to the length of the expression onthe right side of the comparison.

    The == operator requires that both sides of theexpression contain exactly the same number of

    bytes, including CHR(0) bytes.

    Further, because Binary data is case-sensitive,comparisons are always case-sensitive regardless ofSET COLLATE. This is different than a comparisonwith a Character type, which is case-insensitive ifSET COLLATE is set to GENERAL.

    Learn to Type

    Prior to version 9.0, Visual FoxPro allowed a SQLCREATE TABLE statement to include a long type-

    name, although only the first letter of the type-name was respected. This resulted in issues withdata types such as Character and Currency. Thereis now full support for long typenames with bothCREATE and ALTER TABLE/CURSOR as well asthe new CAST() function. Table 1 provides a list ofFoxPro data types with their long name, singleletter, and, in some cases, abbreviations,supported.

    Just like with the new Binary index datatype, usingthese new datatypes requires that all clientsaccessing the data be upgraded to Visual FoxPro

    9.0. Tables that include these new types canread by prior versions.

    Remote Data

    Visual FoxPro has always had a strong remostory, and Visual FoxPro 9.0 adds evencontrol over how remote data is manipulateretrieved.

    Transactions and Connections

    A new property, DisconnectRollBack hasadded to control whether pending transashould be rolled back when the connectdisconnected. This property is available throuSQLSetProp, SQLGetProp, DBSetProp,DBGetProp functions.

    SQLIdleDisconnect() is a new function that used to temporarily disconnect a connectimost cases, this is controlled through theTimeOut property of a connection. But in

    threaded run-time (MTDLL), idle tasks are diCalling this function releases the connectionthe next command requiring a connection is

    Fetching and Processing Informati

    CursorGetProp() receives two new propRecordsFetched and FetchIsComplete. Theseerties allow you to determine the number of rfetched and when a fetch is completed duriexecution of SQL Pass Through statements.

    The RecordsFetched value might not reflenumber of records in the cursor in the evensome records in the cursor were locally app

    or deleted. The number of records reported dorespect filters that may be on the cursor.

    The number of records affected by the SQThrough can be determined using the addparameter aCountInfo available with

    What's New with Data in Visual FoxPro 9.0 www.code-ma20

    Data Type Long Name IniCharacter Char, CharacterDate Date DDateTime DatetimeNumeric Num, Number NFloating Float

    Integer Int, IntegerDouble DoubleCurrency Currency YLogical LogicalMemo Memo MGeneral General GPicture PictureVarChar Varchar VVarBinary Varbinary QBLOB Blob W

    Table 1: Here are some FoxPro data types with theported long names and initials.

    Many of the changesmade to the CursorAdapter were

    done to bring behaviorin line with remote views.

  • 5/20/2018 Vfp9 (Vfp9focus) Visual Foxpro 9 Code-Focus

    21/68

    SQLEXEC() and SQLMORERESULTS() functions.ACountInfo is a two column array containing thealias and count.

    Rowsets from the Provider

    Three functions have been added to supportreturning result sets from stored procedures whenaccessed via the provider.

    SetResultSet() is used to specify which work area inthe current DataSession is to be used as the resultset. Only one cursor in a DataSession can bemarked.

    GetResultSet() returns the work area for the cursormarked by SetResultSet.

    ClearResultSet() sets the marked result set to 0 andreturns the work area for the previously markedcursor.

    Within a stored procedure, you create a cursor withthe results you want returned and use SetRe-

    sultSet() to identify the work area for the cursor.When executed by the provider, return values arenot respected, but a rowset is created based on thecursor you provided.

    CursorAdapter and XMLAdapter

    Enhancements

    Changes to the CursorAdapter and XMLAdapterclasses are worthy of another multi-page article. But forthe purpose of this overview, it's important to brieflynote some of the more significant enhancements.

    Many of the changes made to the CursorAdapterbring behavior in line with remote views. Theseenhancements include:

    Support for Timestamp fields. This allows

    UPDATE/DELETE commands to use Timestampfields as part of the WhereType method.

    Auto-Refresh support. Several new propertieshave been added so that remote data managed bythe CursorAdapter is automatically refreshed afteran INSERT or UPDATE operation. This is valu-able for retrieving auto-incremented or defaultfield values and timestamps.

    On Demand Record Refresh support. Moreproperties and events have been added toCursorAdapter to support the same kind of func-tionality provided by the REFRESH() function forlocal and remote views.

    In addition, properties have been added to supportDEFAULT and CHECK constraints and formapping remote data to the new VarChar andVarBinary data types.

    XMLAdapter changes include support for:

    Hierarchical XML XPath expressions XML encoding and decoding enhancements

    Upgrading

    Visual FoxPro 8.0 included changes to FoxPro'sSQL commands, and brought it into greater compli-ance with ANSI SQL standards. These changes mayhave discouraged you from upgrading to version 8

    because of the impact on existing code. If you'vebeen putting off fixing some of those ambiguousqueries or at least bracketing them with SETENGINEBEHAVIOR, Visual FoxPro 9.0 providesmany compelling reasons to make the investment toupgrade.

    Fortunately, the kinds of changes made in VisualFoxPro 9.0 won't require the kind of recoding youmay have found necessary for 8.0.

    As in prior versions, using the SET ENGINEBE-HAVIOR command allows you to isolate legacycode that may be problematic.

    SET ENGINEBEHAVIOR 90 impacts the behaviorof TOP N and the behavior of aggregate functionswithout a GROUP BY clause. In versions prior to 9,if such a statement resulted in no matching criteria,0 records were returned. To be more ANSIcompliant in version 9.0, FoxPro returns a single

    record resultset with NULL value(s) for aggregatecolumns.

    Final Thoughts

    In this article, youve seen that the changes to thedata engine in this release are substantial. Acommitment to backward compatibility and an easyupgrade path has made these changes nearly trans-parent when moving from 8 to 9. Once you've madethe move, you can start taking advantage of thesegreat enhancementssome without changing asingle line of code. Other enhancements ensure that

    code based on the new features is more compatible,powerful and maintainable than ever before.

    David T. Anderson

    Ken LevyProduct Manager,Visual Studio Data TeamMicrosoft

    With all the great new featincluded in Visual FoxPro my favorite feature remainworld-wide FoxPro comm

    There is a list of great VisuFoxPro community resourat http://msdn.com/vfoxprocommunity. Posting a queon a community Web site free and you usually get a response from somebodyknows the answer. Interacwithin the FoxPro commuis not only educational, bube fun and it can result infinding employees oremployers.

    Information from the Visu

    FoxPro team is regularlyincluded in the monthly leathttp://msdn.com/vfoxpro/leFor even more up-to-date and information, refer to mblog athttp://blogs.msdn.com/kleCalvin Hsia's blog athttp://blogs.msdn.com/cal

    sia, and the Visual Studio Team blog athttp://blogs.msdn.com/vsdAll of this information Visu

    FoxPro 9.0 whitepapers ansamples can be found on tVisual FoxPro home page http://msdn.com/vfoxpro.

    What's New with Data in Visual FoxPrwww.code-magazine.com

    As in prior versions,using the SET ENGINEBEHAVIOR

    command allowsyou to isolate legacy codethat may be problematic.

  • 5/20/2018 Vfp9 (Vfp9focus) Visual Foxpro 9 Code-Focus

    22/68The Visual FoxPro 9.0 Report Writer www.code-ma

    The Visual FoxPro 9.0Report WriterMicrosoft has significantly improved the Report Writer in

    Visual FoxPro 9.0. They also recognized the significant investment in exisFRX-based reports and designed the new Visual FoxPro 9.0 Report Writer to b

    compatible with previous versions of Visual FoxPro Reports. This makes it a g

    blend of the old and the new. In this article, you'll learn about some of the new

    features, including the new reusable data environments, report protection, and

    several user interface enhancements. Youll also learn about enhancements to

    layout objects and data groups. Finally, youll learn about one of the best

    improvements to the Visual FoxPro 9.0 Report Writer: multiple detail bands.

    Before I explain the new features, you need tounderstand how to use the new Report Designerand how to run reports using the new output

    engine.

    The Report Designer: By default, the new VisualFoxPro 9.0 Report Writer uses the new XbaseReport Designer. It providesnewer dialog boxes and is easierto use than the old version. Italso provides access to many ofthe new features that are notavailable through the oldReport Designer. You can easilycontrol which Report Designer

    is used by changing the value ofthe new _REPORTBUILDERsystem variable.

    *-- Use the new Report Builder

    _REPORTBUILDER = HOME() + 'ReportBuilder.app'

    *-- Use the old Report Builder

    _REPORTBUILDER = ''

    The Output Engine: Just as with the ReportDesigner, you can control whether the new or oldoutput engine is used. Unlike the Report Designer,

    which defaults to the new style out of the box,Visual FoxPro 9.0 defaults to the older outputengine. The reason for this is that GDI+ is used inthe new engine, and renders slightly differently thanthe GDI used by the old engine. Therefore, some ofyour existing reports could render differently inVisual FoxPro 9.0, which means you'd have totweak them to make them appear correctly. Youcan switch between the output engines with thefollowing command:

    *-- Use the new output engine

    SET REPORTBEHAVIOR 90

    *-- Use the old output engine

    SET REPORTBEHAVIOR 80

    The rest of this article assumes that the new RDesigner and the new output engine are both

    Data Environments

    The Visual FoxPro 9.0 Writer can now shareEnvironments with

    reports. Data Environcan also be saved as a clathen loaded into repo

    needed. This offers a great reuse scenardefining common reporting needs.

    Save As Class

    To save a Data Environment as a class, stdefining the Data Environment in a report asWhile the Data Environment window is still select the newSave As Classoption from the

    File menu.

    After selectingthe Save AsClass option,the Save AsClass dialog boxappears, asshown in Figure1. The DataEn-vironment

    button of theSave option

    Cathy PountneyCathy Pountney is a MicrosoftVisual FoxPro MVP and hasbeen developing software forover 22 years, thirteen of whichwere as an independentconsultant specializing inFoxPro. In 2001 she had theprivilege of spending six

    months as a contractor onsitein Redmond with the MicrosoftFox Team. Currently she worksfor Optimal Solutions devel-oping Visual FoxPro applica-tions for schools. Cathy hasspoken at many FoxPro confer-ences and user groups acrossthe U.S., written articles forvarious magazines, and herbook, The Visual FoxPro ReportWriter: Pushing it to the Limitand Beyond, is available fromHentzenwerke Publishing(www.hentzenwerke.com).

    [email protected]

    www.frontier2000.com

    www.optimalinternet.com

    Fast Facts

    The new

    Visual FoxPro 9.0 Report Writer

    is compatible with previous

    versions of Visual FoxPro,

    making it a great blend of the oldand the new.

    22

    QUICK

    ID0404042

    Figure 1: Use the Save As Clasbox to declare the name of t

    class and the class library forthe Data Environment of a repo

  • 5/20/2018 Vfp9 (Vfp9focus) Visual Foxpro 9 Code-Focus

    23/68

    group is the only option button-enabled whensaving a Data Environment of a report.

    Enter a name for the class in the Name textbox.Next, enter the name of the class library you want

    the new class saved in. If you enter the name of aclass library that does not exist, the new class libraryis created for you. You can also use the ellipse

    button to brows for the location of an existing classlibrary. Finally, you may optionally enter a descrip-tion of the new class.

    Loading a DE

    In addition to manually defining the Data Environ-ment for a new report, Visual FoxPro 9.0 also givesyou the option to load the Data Environment froman existing report or from a saved DataEnvironmentclass. The Load Data Environment option on theReport menu allows you to select which Data Envi-

    ronment to load.

    From a Report

    When loading the Data Environment from anotherreport, all the code and members of the original DataEnvironment are copied into the new report. Thismeans any changes made to the original report'sData Environment after the fact are not propagatedinto reports created from the original report.

    The Report Properties dialog box, as shown inFigure 2, appears after selecting Load Data Envi-ronment from the Report menu. Use this menu to

    select the report from which you wish to copy theData Environment.

    Select the Copy from another report file optionbutton and then click the Select button. Thisinvokes the Open dialog box so you can choosewhich report to copy from. Once you chose areport, a confirmation dialog box appears.

    Visual FoxPro 9.0 is about to copy the Data Envi-ronment from another report to the current report.Visual FoxPro 9.0 notifies you that it's about tooverwrite the current Data Environment, and you

    must click Yes to continue. This helps remind youthat anything you have defined in the Data Envi-ronment of the current report is about to be over-written. If you click No, changes are not made andthe process is aborted. When you click Yes, theData Environment is copied and you are notified byanother dialog box.

    You are now finished copying the Data Environ-ment. You may manipulate the Data Environment

    as needed. However, remember that any changesmade to the original report's Data Environmentafter this point are not propagated to this newreport.

    From a DE Class

    When loading the Data Environment from a class,code is added to the Data Environment of the newreport to bind to the original DataEnvironmentclass and instantiate it at runtime. This means thatfuture changes made to the DataEnvironment classwill propagate into any reports using the DataEnvi-ronment class.

    Using the Report Properties dialog box, shown inFigure 2, click the Link to a visual DE classbutton.Next, click the Selectbutton to invoke the Opendialog box that you can use to choose which classlibrary and which class to use. After confirmingyour intentions, the Data Environment is updatedand you are notified of its completion.

    At this point, code has been added to five DataEnvironment methods: Init(), BeforeOpenTables(),AfterCloseTables(), Destroy(), and Error(). Some ofthe methods have very simple code with nothingmore than a DODEFAULT() command. The reasonfor this is that BindEvents() does not function

    unless the method contains at least one line of code.Look at the code in these methods to see what itdoes, but I do not recommend that you change it.

    ProtectionIn Visual FoxPro 9.0, you can create protection forone or more layout objects when using ReportDesigner or Label Designer. This lets your usermodify a report, yet keeps them from makingcertain changes.

    Layout objects have five protection modes you canset, and Field objects have an additional protectionoption. Bands have two protection modes you canset. The report itself has a variety of different protec-tion modes you can set.

    www.code-magazine.com The Visual FoxPro 9.0 Report W

    Just like the Report Designer,you can control whether the new or

    old output engine is used.

    Figure 2: Use the Data Environment tab of the Report Prop-

    erties dialog box to choose which report you want to copy aData Environment from.

  • 5/20/2018 Vfp9 (Vfp9focus) Visual Foxpro 9 Code-Focus

    24/68

    Protecting an Object

    To protect a layout object in the Report Designer,select the Properties dialog box for the object. TheProperties dialog box can be invoked from theReport menu after selecting the object from theright-click menu of the object, or by double-clickingthe object. Figure 3 shows the Protection tab of theProperties dialog box for a field object. You can setthe following five protection modes for layoutobjects:

    Object cannot be moved or resized prevents usersfrom moving this layout object to a different posi-tion on the design surface and prevents users fromresizing this object.

    Object cannot be edited prevents the user from

    making changes to the properties of this layoutobject.

    Object cannot be deleted prevents the user fromdeleting this object.

    Object cannot be selected prevents users fromselecting this object. When this option is selected,the protection behaviors of Object cannot bemoved or sized. Object cannot be edited andObject cannot be deleted are also imposed.

    Object is not visible in Designer prevents thisobject from appearing in the Report Designer inprotected mode. When this option is selected, theprotection behavior of the other four options isalso imposed.

    The Design-time caption portion of this dialog boxonly applies to Field objects. The literal stringentered into this textbox is displayed in the ReportDesigner, instead of the Expression. This gives youthe opportunity to display something that is user-friendly instead of a complicated expression.

    Protecting a Band

    To protect a band in the Report Designer, select theProperties dialog box for the band. The Propertiesdialog box can be invoked from the Edit Bands

    option on the Report menu, from the righmenu of the band, or by double-clicking th

    bar of the band. Figure 4 shows the Protectiof the Properties dialog box for a band. You cthe following two protection modes for band

    Band cannot be edited prevents the Band Pties dialog box from being accessible to the

    Band cannot be resized prevents the useresizing the band.

    Protecting a Report

    To set overall report protection, select the RProperties dialog box. You can invoke this

    box by selecting Properties from the Reportor from the right-click menu of the report. Fishows the Protection tab of the Report Propdialog box.

    The top portion of this dialog box allows define which tabs of the Report Properties

    box are unavailable to the user. For each selections made in this area, the applicable

    the Report Properties dialog box is disableProtection option is always checked and disThe Ruler/Grid option is disabled because tcannot be protected, although it appears odialog box so that the selections are consistenthe tabs on the Report dialog box.

    The bottom portion of this dialog box allowsdefine which menu options are unavailable user. For each of the selections in this areapplicable menu option is disabled.

    Honoring Protection Flags

    To invoke protection during a Report Desig

    Label Designer session, use the PROTEkeyword, as shown in the following example

    CREATE REPORT MyReport PROTECTED

    MODIFY REPORT MyReport PROTECTED

    CREATE LABEL MyLabel PROTECTED

    MODIFY LABEL MyLabel PROTECTED

    If the PROTECTED keyword is not use

    SUMMARY Issues

    Using the SUMMARY clause ofthe REPORT FORM commandprevents the Detail band fromprinting, yet all the PageHeaders and Footers, ColumnHeaders and Footers, andGroup Headers and Footers areprinted. Any On Entry or OnExit expressions in a Detailband are not processed whenthe SUMMARY clause is used.When issuing SUMMARY on a

    Multiple-Detail band report, theDetail Headers, Detail Footers,and Detail bands are notprocessed.

    The Visual FoxPro 9.0 Report Writer www.code-ma24

    Figure 3: Use the Protection tab of the Properties di-alog box to set protection modes of a layout object.

    Figure 4: Use the Protection tab of the Band

    Properties dialog box to set protection modesof the band.

    Figure 5: Use the Protection tab of the Report Propealog box to set overall protection modes of a report.

  • 5/20/2018 Vfp9 (Vfp9focus) Visual Foxpro 9 Code-Focus

    25/68

  • 5/20/2018 Vfp9 (Vfp9focus) Visual Foxpro 9 Code-Focus

    26/68

    Yair Alan Griver

    Group Manager,Visual Studio Data TeamMicrosoft

    The new data enhancementsparticularly those that targetSQL Serverare among my

    favorite new capabilities inVisual FoxPro 9.0. I really likebeing able to use CAST(), opti-mized LIKE, and some of thenew features that give mebetter control over SQLhandles. I especially love theenhanced SQL syntax. Beingable to more closely modelVisual FoxPro and SQL Serverstatements is an awesomecapability!

    The Visual FoxPro 9.0 Report Writer www.code-ma26

    Report Designer functions as if no protection wereapplied to the layout objects.

    UI Enhancements

    Many changes have been made to the user interfaceto make designing reports easier and more intuitive.Menus have been overhauled, context menus have

    been changed, and new options have been added to

    the Report Designer toolbar. The ExpressionBuilder dialog box and Expression Builder Optionsdialog box have new behaviors, and a few othermiscellaneous user interface enhancements have

    been added to the Visual FoxPro 9.0 Report Writer.

    Menus

    The report menu system has been overhauled inVisual FoxPro 9.0 to accommodate new options. Inaddition, some options have been relabeled forclarity and some options have been repeated onseveral menus to allow easier access.

    The new Save As Class option appears on theFile menu.

    A new option has been added for the ReportDesigner Toolbar and horizontal lines have beenadded to separate the Grid Lines and Show Posi-tion options from the other options.

    Many changes appear on the Report menu,including relabeled options, new options, and theaddition of the Print Preview option.

    Context Menus

    Existing context menus have been improved withadditional items and are now more consistent with

    the dialog boxes they invoke. Items in the ReportDesigner that previously didn't have context menusnow do.

    The Global Context menu has new options andone relabeled option.

    Invoke the new Band Context menu by right-clicking on the gray bar of any band.

    Invoke the new Layout Object context menu byright-clicking on any layout object.

    Toolbar

    The improved Report Designer toolbar, shown in

    Figure 6, has two new buttons: The Page Setupbutton and the Font Propertiesbutton.

    Expression Builder Dialog Box

    A few changes have been made to the ReportExpression dialog box, including a taller Expressionfor Field editing box, which allows more room forentering a report expression.

    When the _REPORTBUILDER system variable isempty, the native behavior of the ExpressionBuilder dialog box is specific. Only tables defined in

    the Data Environment are listed in the Fielbox. Tables opened outside of the Data Enment are not available in the list box.

    When the _REPORTBUILDER system variset to ReportBuilder.app , the behavior Expression Builder dialog box is quite difFirst of all, the Expression Builder defin

    _GETEXPR is invoked instead of the native Esion Builder.

    This Expression Builder dialog box has a cbox for choosing which table should bewhen listing fields in the Fields list boxtables that are currently in use are listed combo box. This is an important poremember because tables defined in theEnvironment are not automatically opened Report Designer, and do not automatically ain the combo box.

    This gives you the ability to control which tabavailable to end-users when you allow thmodify reports within your application. Yo

    have defined some tables in the Data Envirothat you need, but to which you don't wanaccess. Because you have to specifically optables you want users to access, you can omtables you want to keep from them.

    Expression Builder Options Dialog

    The Field aliases option group is now enabthe Expression Builder Options dialog boxoption group allows you to indicate whetheryou want the table alias added to the report esion when picking fields from the ExprBuilder dialog box.

    TheAlways add alias and Never add aliasbuttons cause Visual FoxPro 9.0 to automaadd the table alias, or to not add the table aliall fields. The behavior of the Add non-sealias only option button depends on theof the _REPORTBUILDER system variable.

    _REPORTBUILDER system variable is empfield chosen from a table that is not the InilectedAlias is prefixed with the table alias. from the InitialSelectedAlias table are not prwith the table alias.

    If the _REPORTBUILDER system variable isReportBuilder.app, theAdd non-selected alia

    option uses slightly different logic. The curselected alias is used instead of the InilectedAlias for determining whether or not tothe field with the table alias.

    In addition to selecting a field from the ExprBuilder dialog box, dragging a field from thEnvironment to the Report Designer shonors the setting of the Field aliasesgroup. Also, a new option exists on the Repof the Options dialog box to determine whdefault Field aliases setting is for all newly creports.

    Figure 6: New options for PageSetup and Font Properties have

    been added to the Report Design-er toolbar.

  • 5/20/2018 Vfp9 (Vfp9focus) Visual Foxpro 9 Code-Focus

    27/68The Visual FoxPro 9.0 Report Wwww.code-magazine.com

    Mouse Cursor

    The mouse cursor now changes to provide a visualcue when an object can be resized (see Figure 7).

    Multiple Selection Dialog Box

    Visual FoxPro 9.0 has a Multiple Selection dialogbox, which allows you to set the Protection andPrint when properties for more than one layout

    object at a time. It also allows you to change any ofthe other properties of any individual layout object.To use this new feature, select more than one layoutobject, and then double-click any one of the objectsto invoke the Multiple Selection dialog box, asshown in Figure 8.

    The layout objects that were selected when thisdialog box was invoked are listed in the first tab ofthis dialog box. To work with all layout objectsdefined in a report, use CTRL + A to select alllayout objects before invoking this dialog box.

    The Sort by option allows you to sort the list of

    layout objects by Type or Location within thereport. The Remove from listbutton removes theselected layout objects from the list. Double-click onany item in the list and the applicable Propertiesdialog box for the individual object is invoked. TheProperties tab of the Multiple Selection dialog box,shown in Figure 9, is used to change the propertiesof all the items listed in the Selection tab.

    Select theApply these protection settings to theselected objects checkbox to enable theProtec-tion options. Select the Apply this condition tothe selected objects upon saving checkbox toenable thePrint when option. Change the Protec-tion and Print when settings as needed, and then

    select OK to close the dialog box and apply thechanges to all the layout objects listed on the firsttab.

    More Zoom Levels

    The Preview window now has more Zoom levels,ranging from 10% up to 500%.

    Layout Object Enhancements

    A few improvements have been added for layoutobjects, including an option to control template

    characters, a trim mode for character expressions,and relative and absolute positioning.

    Template Characters

    The Field Properties dialog box has a new sectionfor Template characters. The two available optionsare Overlay and Interleave. These determine howspecial characters are used in the format.

    When the Overlay option is used, special charactersare treated as part of the data and overlay any otherspecific character in a specified position. For

    example, when the Format expression is "999-999",and the data contains "123456", the report shows"123-56". Notice that the "4" is replaced by the dashin the format expression.

    When the Interleave option is used, the specialcharacter is inserted in between existing charactersin the data. For example, when the Format expres-sion is "999-999", and the data contains "123456",the report shows "123-456". Notice that the dash is

    inserted between the "3" and the "4".

    Trim Mode for Character Expressions

    Prior to Visual FoxPro 9.0, field objects werealways trimmed to the nearest word when the textwas too long. In Visual FoxPro 9.0, a new optionon the Field Properties dialog box allows you todetermine how the text is trimmed. The six trimoptions are:

    Default trimming uses the defaultbehavior, which is the same as theTrim to nearest word, append

    ellipsis option. This behavior issimilar to prior versions of VisualFoxPro, with the exception ofappending the ellipsis.

    Trim to nearest character trims textto the last full character that fits inthe defined area.

    Trim to nearest word trims text tothe last full word that fits in thedefined area.

    Trim to nearest character, appendellipsis trims text to the last fullcharacter that fits in the definedarea, after an ellipsis is added to thetext that prints.

    Trim to nearest word, appendellipsis trims text to the last fullword that fits in the defined area,after an ellipsis is added to the textthat prints.

    Filespec: Show inner path asellipsis replaces the inner directo-ries of a long path and filenamewith an ellipsis when the full textdoes not fit in the defined area.

    Size and Position

    Another new feature available on

    Layout objects is better control of thesize and position of the object. Whenan object is added to the report, thevalues for From page top, From left,Height, and Width are automaticallyset. It's important to note that theFrom page top property is relative tothe top of the page in the ReportDesigner, which means it takes intoaccount the height of any gray barsabove the object. Changing the Frompage top property may inadvertentlymove the object to another band.

    Figure 7: Use the new mous

    sor to know when an objebe resized.

    Figure 8: Use the Selection tab of the Multiple tion dialog box to choose which layout object

    want to work on.

    Figure 9: Use the Properties tab of the Multiple tion dialog box to change the Protection propertie

    the Print When logic of the selected layout objeat once.

  • 5/20/2018 Vfp9 (Vfp9focus) Visual Foxpro 9 Code-Focus

    28/68

    Relative Positioning: The From page top propertyand the Height property work together to deter-mine whether absolute positioning or relative posi-tioning is used. When the From page top propertyis set to a value that falls within the Report Designersurface, and the value of the Height property is lessthan or equal to the height of the band in which theobject is located, relative positioning is used. Rela-tive positioning is needed for objects in bands otherthan the Page Header and Page Footer.

    Absolute Positioning: When the From page topproperty is set to a value that falls outside the

    Report Designer surface, orthe value of the Height prop-erty is greater than the heightof the band in which theobject is located, absolutepositioning is used. Absolutepositioning means the object isprinted in exactly the samelocation on each and everypage.

    Absolute Positioning can beused to create a watermark ona report. Place a graphic image

    in the Page Header band, andset it to Scale contents, retainshape. Change the From pagetop property and the From leftproperty to indicate the upper-left corner of where you wantthe watermark to begin.Change the Height and Widthproperties to indicate theoverall size of the watermark,making sure not to extend

    beyond the printable margins ofthe printer.

    Data Group Enhancements

    A few enhancements have been made toGroups in the Visual FoxPro 9.0 Report Wincluding maximum Data Groups and horicolumns.

    Maximum Data Groups

    The maximum number of Data Groups haincreased from 20 to 74. In actuality, the maxof 74 was always true, but the user interfacallowed 20 Data Groups to be entered.

    Horizontal Columns

    Previously, reports with more than one cdefined as horizontal with a Data Group walot of space. The first position (row 1, coluwas left blank and data began in column 2 of Also, a blank band was wasted in between eaof Data Groups, as shown in Figure 10. Evenheight of the Data Group Header band isVisual FoxPro still reserved the space, as shoFigure 11.

    In Visual FoxPro 9.0, the behavior of Data G

    and horizontal columns has been changed. Wnew Data Group is encountered, it is princolumn 1 of the next full row. The remainder row is left blank and not used for printing dThe details belonging to the Data Group becolumn 1 of the row immediately after the roData Group is printed in, as shown in FiguAlso, no extra space is reserved if the heightData Group Header band is zero, as shoFigure 13.

    The new behavior, although avoiding the prevdescribed situation, may break some existing r

    The Visual FoxPro 9.0 Report Writer www.code-ma28

    Figure 10: Prior versions of Visual FoxPro wasted a lot of

    space when using horizontal columns with Data Groups.Figure 11: Prior versions of Visual FoxPro reserve

    for Data Group Headers, even when none were defin

    Figure 12: Visual FoxPro 9.0 does not waste as much space

    as prior versions when horizontal columns and Data Groupsare used.

  • 5/20/2018 Vfp9 (Vfp9focus) Visual Foxpro 9 Code-Focus

    29/68

  • 5/20/2018 Vfp9 (Vfp9focus) Visual Foxpro 9 Code-Focus

    30/68

    However, an added benefit of the new behavior isthat the Data Group band can be stretched across allthe columns, as shown in Figure 14.

    Multiple-Detail Bands

    The new multiple-detail band feature is one of thebiggest, and most often requested, improvements. Itallows you to process multiple child tables for eachrecord in a parent table. An example of this type ofreport is shown in Figure 15.

    Tables and Relationships

    Understanding how the parent and child tableswork together are key to understanding how to usethis new feature. As an example of a Multiple-Detailscenario, assume you are writing the report shownin Figure 15. The database for this scenario is:

    The Customer table is the parent table andcontains one record for each insurance customer.

    The Members table holds one record for eachfamily member of the customer. The Memberstable is a child table of the Customer table.

    The Vehicles table holds one record for each

    vehicle insured by the customer. The Vehiclestable is a child table of the Customer table.

    The Homes table holds one record for each homeinsured by the customer. The Homes table is achild table of the Customer table.

    Driving the Report

    One table is necessary to drive the report. In thisexample, the Customer table is the driving table. Ifyou use the report's Data Environment to define thetables, set the InitialSelectedAlias property to thistable. If you are using code to define the tables,

    make sure the Customer table is the currentarea at the time the report runs.

    The Target Alias

    The target alias is the term used to describe table is the driving table for a particular detailIn this example, the Members table is the alias for Detail 1 band, the Vehicles table target alias for Detail 2 band, and the Homeis the target alias for Detail 3 band.

    If no target alias is defined for a Detail ban

    behavior it takes on is that of prior versiVisual FoxPro. In other words, one detail bprocessed per parent record. However, if youthe name of the parent table as the targetyou'll get very different results. For each recthe parent table, Visual FoxPro processes thall records in the entire parent table, printinparent record in the Detail band. If you have with 10 parent records, and you set the targeof a detail band to the parent table, the final prints 10 sets of 10 records, or a total orecords.

    Relationships

    Relationships play a big part in how multiplebands operate. Visual FoxPro uses the relatiobetween the parent table and the child tabnavigate through the records. You may usRELATION or SET SKIP to define these reships. If you're opening the tables in the Dataronment, and relationships are already defithe database, these relationships are honored

    If you're opening the tables in code, Listing 1how to set up the tables for the Insurance CusListing shown in Figure 15.

    The Visual FoxPro 9.0 Report Writer www.code-ma30

    Figure 13: Visual FoxPro 9.0 does not reserve extra space

    when the Data Group Header band is 0" tall.Figure 14: In Visual FoxPro 9.0, you can expand t

    Group Header band across multiple columns.

  • 5/20/2018 Vfp9 (Vfp9focus) Visual Foxpro 9 Code-Focus

    31/68

    Defining Multiple-Detail Bands

    By default, new reports are created with one Detailband. Additional Detail bands are added throughthe Optional Bands dialog box. To invoke thisdialog box, select Optional Bands from theReport menu. This is the same dialog box that wasformerly named Title/Summary.

    Click theAddbutton to add another Detail band tothe report. You may define up to 20 Detail bandsfor each report.

    Defining the Target AliasThe target alias is assigned to a Detail bandthrough the Detail dialog box. This dialog box can

    be invoked by selecting Edit Bands from theReport menu and selecting the applicable Detail

    band. You can also invoke this dialog box bydouble-clicking the gray bar of the applicableDetail band.

    The Target alias is an expression and you mustwrap the table name in quotes. Once you have eachtarget alias defined, the gray bars representing theDetail bands show the target alias.

    The Visual FoxPro 9.0 Report Wwww.code-magazine.com

    When creating Multiple-Detail band reports, it'simportant to prefix field names with the applicablealias name. This prevents any confusion as to whichtable a field comes from.

    Headers and Footers

    Another enhancement of the Multiple-Detail bandis the ability to add Headers and Footers to eachDetail band. These are similar to Group Headers

    and Footers in some ways, yet different in others.For each parent record that is processed, thefollowing occurs:

    The Detail 1 Header band is processed. The Detail 1 band is processed once for each

    child record in the associated target alias. The Detail 1 Footer band is processed. The Detail 2 Header band is processed. The Detail 2 band is processed once for each

    child record in the associated target alias. The Detail 2 Footer band is processed. The Detail 3 Header band is processed. The Detail 3 band is processed once for each

    child record in the associated target alias. The Detail 3 Footer band is processed. And so on

    To turn on Detail Headers and Footers, place acheck mark in the selection box for DetailHeader/Footer in the Detail dialog box for each ofthe Detail bands. To help sort out the Detail bandsfrom other bands, the triangle preceding the bandname is solid and the other triangles are clear.

    It's important to note that even if no detail recordsexist for a particular Detail band, the associatedDetail Header and Detail Footer bands still print.If you do not want the Detail Header and Detail

    Footer bands under this condition, you may usethe following Print when logic in each layoutobject defined in the bands to suppress theirprinting.

    NOT EOF()

    In addition to manuallydefining the Data Environment for a

    new report, you have theoption to load the Data Environment

    from an existing reportor from a saved

    DataEnvironment class.

    Figure 15: This sample Multiple-Detail band report has three

    separate detail bands for each customer.

    Listing 1: Setting the relationship between the parent and child tables.

    *-- Open the child tables

    USE Members IN 0 ORDER CustomerFK

    USE Vehicles IN 0 ORDER CustomerFK

    USE Homes IN 0 ORDER CustomerFK

    *-- Open the parent table

    SELECT 0

    USE customer ORDER CustomerPK

    *-- Set the relations between the parent and children

    SET RELATION TO CustomerPK INTO Members

    SET RELATION TO CustomerPK INTO Vehicles ADDITIVE

    SET RELATION TO CustomerPK INTO Homes ADDITIVE

    *-- Run the report

    REPORT FORM Insurance PREVIEW

  • 5/20/2018 Vfp9 (Vfp9focus) Visual Foxpro 9 Code-Focus

    32/68

    Be sure to place a check mark in the selection boxfor Remove line if blank for these layout objects aswell.

    Similar to Group Headers and Footers, DetailHeaders and Footers have some of the sameoptions.

    Start on a new column: Causes the Detail set tostart on a new column of the report. Note that this

    option allows you to assign a Detail set to aspecific column. If one Detail set has enoughinformation to overflow the column, it iscontinued in the next column.

    Start on a new page: Makes the Detail set start ona new page.

    Reset page number to 1 for each detail set: Withthe Start on a new page option, resets the pagenumber to 1 for each new Detail set.

    Start detail set on new page when less than:Helps prevent orphans. The detail set begins on anew page if the indicated amount of space is notavailable.

    Detail Header/Footer: Adds a Detail Header and

    Detail Footer band around this Detail band. Reprint detail header on each page: With theDetail Header/Footer option, makes the DetailHeader band reprint whenever the Detail set over-flows to a new page.

    Report Variables and Calculations

    With the introduction of Multiple-Detail bands,variables and calculations have some new twthem. You need to fully understand how thprocessed in order to use them effectively. Othyou may not get the results you're expecting.

    The Reset at prompt on the Report Variablesbox has been renamed Reset based on. Thi

    clearly defines that the variable is reset based change in value of the selected option. In adto renaming the control, if more than one

    band is defined in the report, each Detail badded to the drop-down list.

    SelectingDetail n as the Reset based on valuVisual FoxPro to only process this calculationprocessing the detail records in the target aliasDetail band. The report variable is not alteredrecords in other target aliases are being procThis allows you to tie a report variable to one ular Detail band. The value of the report varinot cleared until the Detail Header band of thi

    Detail set is processed for the next parent reco

    If you chose a Reset based on value other thof the Detail bands, the calculation is processeveral places. First, for each parent record, the

    The Visual FoxPro 9.0 Report Writer www.code-ma32

  • 5/20/2018 Vfp9 (Vfp9focus) Visual Foxpro 9 Code-Focus

    33/68

    lation is applied. Next, the calculation is applied foreach record in the target alias of the first Detail band.Then the calculation is applied for each record in thetarget alias of the second Detail band, and so on.

    Tricks with Multiple-Detail Bands

    The previous section showed how to print datafrom three different child tables on the same report.But a multiple detail band report doesn't necessarilyhave to have multiple child tables. The same childtable can be used in more than one detail band.

    Group Totals

    Prior to Visual FoxPro 9.0, printing subtotals in theData Group Header band (shown in Figure 16) wasvery difficult. The data had to be preprocessed tocalculate the totals prior to running the report. WithVisual FoxPro 9.0, no preprocessing is required.Follow these steps to create this report:

    1. Create the Data Environment: Add theCustomer and Vehicles tables. Set the InitialSe-lectedAlias property to the Customer table.

    2. Create a Data Group: Set the Data Groupexpression to the Customer PK. Do not place anyobjects in the Data Group Header or the DataGroup Footer bands.

    3. Create the multiple detail bands: SelectOptional Bands from the Report menu. ClicktheAddbutton to add one more detail band tothe report. Click OKto exit the dialog box.

    4. Define the Detail #1 band: Double-click the graybar of the Detail #1 band to invoke the Properties

    dialog box. Set the target alias to "Vehicles",remembering to use the quotes. Check theAsso-ciated header and footer bands checkbox. Donot place any objects in the Detail 1 band.

    5. Define the Detail #1 Footer band: Add theCustomer Name and Address objects to the band.Add the total vehicles and total premiums Labelobjects to the band. Add a Field object for the totalvehicles; set the expression to vehicles.premium,set the Calculation type to Count, and set theReset based on toDetail1. Add a Field object forthe total premiums; set the expression to vehi-cles.premium, set the Calculation type to Sum,

    and set the Reset based on toDetail1.6. Define the Detail #2 band: Double-click the

    gray bar of the Detail 2 band to invoke theProperties dialog box. Set the target alias to"Vehicles", remembering to use the quotes.

    Check theAssociated header and footer bandscheckbox. Add any other objects needed inDetail 2 band.

    The above report definition tells the Visual FoxPro9.0 Report Writer to process the Vehicles tabletwice for each customer in the Customer table. Thefirst time, it calculates the total records and dollaramount for the customer and then prints them.The second pass of the Vehicles table prints thedetails. This process repeats for each customer inthe Customer table.

    Percentages

    Another reporting concept is to show percentagesof totals of each detail line, as the detail line prints.This can also be handled with Multiple-Detail

    bands, as shown in Figure 17. Follow these steps tocreate this report:

    1. Define the Data Environment: Add theCustomer and Vehicles tables. Set the InitialSe-lectedAlias property to the Customer.

    2. Create a Data Group: Set the Data Groupexpression to the Customer PK. Add theCustomer Name and Address objects to the DataGroup Header band.

    3. Create the multiple detail bands: Select

    Optional Bands from the Report menu. ClicktheAddbutton to add one more detail band tothe report.

    The Visual FoxPro 9.0 Report Wwww.code-magazine.com

    Figure 16: Use a Multiple-Detail report to print group subto-tals at the beginning of the group.

    Figure 17: Use a Multiple-Detail report to print percentagesalong with each detail line.

    The Visual FoxPro 9.0 Report Writerincludes one of the

    most often requested features:Multiple Detail Bands.

    Randy Brown

    Lead Program Manager,Visual FoxPro TeamMicrosoft

    With Visual FoxPro 9.0,the Fox team brings you thbest desktop database app

    tion software on the markAs one who has always apciated all the great extensihooks that Fox has to offeI am very excited about soof the new capabilities inVFP 9.0 such as the abilityhook in your own customMenu Designer. You can nextend your cla