03
Thu, Oct
2 New Articles

Using OLE with AS/400 Data

Microsoft
Typography
  • Smaller Small Medium Big Bigger
  • Default Helvetica Segoe Georgia Times

Are the complexities of printing AS/400 data driving you insane? Are you finding it difficult to change fonts in the middle of a line or draw a border around the page? Do you look with envy at the people who can format reports on a PC quickly and easily?

Well, now it's your turn. Using a PC word processor, you can create dazzling reports from your AS/400 data automatically, and we'll show you how.

For this article, we'll focus on some techniques that not only allow you to accomplish this feat, but also teach you some important concepts that you can use in the future. The techniques we'll use are a virtual alphabet soup of acronyms: OLE, ODBC, and VB (Object Linking and Embedding, Open Database Connectivity, and Visual Basic, respectively). Since we've covered client/server VB programming and ODBC in the past (see "Custom Controls: The Muscle Behind Visual Basic," MC, December, 1994 and "ODBC Overview," MC, February 1995), the main focus will be on the concepts of OLE (pronounced "oh-LAY") and OLE automation (OA). Microsoft Word will be used to demonstrate these concepts, but they should apply to any OLE-enabled application.

To demonstrate the concepts of OLE and OA, we will use VB to gather and format AS/400 data and pass it on to the sample purchase order template that comes with Word. You could really impress your boss by modifying this template to add your company's information and artwork. Before we show you the nuts and bolts of the code, let's explore some of the concepts of OLE and how it has evolved.

The Oil of OLE

In OLE's original incarnation, Version 1.0, its primary purpose was to allow data (objects) from one source to be either linked to or embedded within data from another source. The most common use for OLE was to create compound documents; that is, documents created from several different programs.

The advantage of compound documents is the ability to use the appropriate tool for the job. For instance, to include an illustration in a document, you could create the illustration in your favorite drawing program and link it to or embed it in your word processing document.

Today, OLE has migrated from a compound document strategy to a more ambitious standard for defining the way that programs and data can interact with one another. The OLE 2.0 standard enhanced the original functionality of OLE 1.0 for both users and developers. For users, it made working with compound documents easier and more seamless. For developers, it defined a standard (OA) for interapplication communication, making it easier for applications to control each other and share data.

OLE Automation

Many OLE-enabled applications can control each other through OA. When one application is controlling another, the application being controlled is the server; the application doing the controlling is the client (these terms shouldn't be confused with general client/server terminology). The following is a list of just a few of the applications that are OLE-enabled:

* Microsoft's Excel

* Visio's Visio

* Novell's WordPerfect

* Pinnacle Publishing's Graphics Server

OLE objects can be thought of as a unit of work for a particular program. OA server applications expose objects for the client programs to manipulate. When an object is exposed, it is effectively "published" for other applications to use. For example, a word processor might expose a document object, a spreadsheet might expose a cell or range of cells, or a drawing program might expose the drawing and the figures that make up the drawing. Only the objects that are exposed by a server program are available to OLE clients.

OLE servers also expose methods and properties that allow the client to manipulate objects. For instance, if a spreadsheet application exposed a cell object, an example of a property might be the alignment of the text within the cell?left, right, or center. A method might be clear, which would clear the contents of the cell. To get a listing of the objects a particular application exposes and the methods and properties for those objects, consult the application's manuals.

Word currently only exposes the Basic object, which is the WordBasic command language. This means that, in order to program Word using OA, you must know a little about WordBasic. In contrast, Visio, an OLE-enabled drawing package by Visio Inc., exposes its documents and the elements of those documents and allows you to manipulate them directly by properties and methods. This is a subtle difference, but it makes Visio easier to control and more object-oriented. Future versions of Word should be better OA servers.

Know the Code

Word comes with many sample templates that can be used as a basis for creating your own documents. One of these templates is a company purchase order (PURCHORD.DOT). We will use this as the foundation for our example.

1 shows the VB code that was used to generate the purchase order in 2. This code is not complete and is meant to serve as a framework around which you could build a working program. Sample database names were used for this example. To make it a complete working project, you will have to substitute your database files and fields.

Figure 1 shows the VB code that was used to generate the purchase order in Figure 2. This code is not complete and is meant to serve as a framework around which you could build a working program. Sample database names were used for this example. To make it a complete working project, you will have to substitute your database files and fields.

The code at Label A retrieves the data from the AS/400 database using ODBC. Two snapshots are used (a snapshot is a nonupdateable reference to a set of records in a database). The first snapshot retrieves vendor information from the vendor master file. The second snapshot retrieves the purchase order line items. This data is then used to fill in Word form fields on the purchase order template.

The code at Label B establishes an OA session with Word. The CREATEOBJECT command creates an instance of the object specified in its parameter. (Some of the terminology used here is discussed in "Object-Oriented Programming Concepts," MC, September 1994.) The parameter to the CREATEOBJECT command is a combination that specifies the application, the type of object to be created (class), and, optionally, the version of the application. For instance, to specify a Word 6.0 Basic class, the class parameter would be Word.Basic.6.

After the OA session is established, we can begin issuing commands to the word processor. In this case, the primary command we are using is the SETFORMRESULT WordBasic command (see Label C). This command sets the text of the specified form field. This command is used to fill in each field on the form. The FILEPRINTPREVIEW command (see Label D) is used to display the document as it will look when it is printed.

Caf? OLE

One problem with the current generation of OA applications is the large amount of system resources they require. For instance, when the program in 1 is run, both the program and Word must be loaded into memory at the same time. This shouldn't be a problem, but if you try to do complex applications with multiple large OLE servers, you could find yourself running out of resources. OA servers don't necessarily use a large amount of resource; much depends upon the OA tools that you use in your application.

One problem with the current generation of OA applications is the large amount of system resources they require. For instance, when the program in Figure 1 is run, both the program and Word must be loaded into memory at the same time. This shouldn't be a problem, but if you try to do complex applications with multiple large OLE servers, you could find yourself running out of resources. OA servers don't necessarily use a large amount of resource; much depends upon the OA tools that you use in your application.

Another nuisance of programming OA with Visual Basic 3.0 is VB's lack of support for named arguments. VB supports only positional arguments, so if you have a command with many parameters, you have to get them in the right order and in the correct position. For example, to turn off background printing in Word, you have to issue the command

wp.ToolsOptionsPrint , , , , , , , , ,0

The zero, for off, is the tenth parameter to this command. Future versions of VB should be able to handle named arguments, so the command would be similar to

wp.ToolsOptionsPrint.Background=0

A Word About OCXs

OLE controls (OCXs) are an extension of OA servers. They are aimed at being a replacement for VBXs, which are closely tied to VB. OLE controls are component objects that can be easily used in many different development tools. The idea behind OLE controls is the same as that for VBXs?create objects or components that can be reused to speed the development process. OLE controls are currently only supported in a limited number of applications, but that number is certain to grow, as is the number of OCX controls on the market.

Is OLE in Your Future?

OLE and OA are cornerstone strategies in Microsoft's vision of the future of computing. In fact, the company is relying upon the technology in its forthcoming object-oriented version of Windows NT, code-named Cairo. Other major vendors are incorporating OLE into their development plans as well. One thing is for sure, component-based software development is here to stay, and since OLE and OA are viable, working architectures for the component-based software model, they'll be around for quite some time.

Brian Singleton is an AS/400 client-server programmer/analyst. He can be reached through Midrange Computing or Internet E-mail at This email address is being protected from spambots. You need JavaScript enabled to view it..


Using OLE with AS/400 Data

Figure 1: Visual Basic Code Sample to Generate Purchase Order

 Sub Command1_Click () Dim wp As object ' Allocate an object pointer Dim db As database ' Pointer to AS/400 database Dim ssVendorMaster As snapshot ' Vendor master table Dim ssPurchases As snapshot ' Purchase order table '-------------------------------------- ' First get the data from the AS/400 '-------------------------------------- Set db = OpenDatabase("", False, False, "ODBC;")' Point to AS/400 database Set ssVendorMaster = db.CreateSnapshot("Select * from VndMstr where VndNbr=15", 64) ' Use passthrough for speed Set ssPurchases = db.CreateSnapshot("Select * from Purchord where PoNbr=12345", 64) '-------------------------------------- ' Then open Word for OLE Automation '-------------------------------------- Set wp = CreateObject("Word.basic") '-------------------------------------- ' Note that everything after the "wp." is ' WordBasic syntax. ' Create a new document based ' on the "purchord" template '-------------------------------------- wp.FileNew "purchord" '-------------------------------------- ' Now we will assign the data retrieved from ' the AS/400 to our Word form fields using ' the WordBasic command "SetFormResult" '-------------------------------------- wp.SetFormResult "PO_Number", ssPurchases("PoNbr") wp.SetFormResult "Quantity_1", ssPurchases("Qty") wp.SetFormResult "Description_1", ssPurchases("Desc") wp.SetFormResult "Price_1", ssPurchases("Price") wp.SetFormResult "Unit_1", ssPurchases("Unit") wp.SetFormResult "Requisitioner", ssPurchases("Reqstr") wp.SetFormResult "SalesTax", ssPurchases("STax") wp.SetFormResult "Ship", ssPurchases("Ship") wp.SetFormResult "To_1", ssVendorMaster("TName") wp.SetFormResult "To_2", ssVendorMaster("TAddr1") wp.SetFormResult "To_3", ssVendorMaster("TAddr2") wp.SetFormResult "To_4", ssVendorMaster("TCSZ") wp.SetFormResult "Ship_1", ssVendorMaster("SName") wp.SetFormResult "Ship_2", ssVendorMaster("SAddr1") wp.SetFormResult "Ship_3", ssVendorMaster("SAddr2") wp.SetFormResult "Ship_4", ssVendorMaster("SCSZ") wp.SetFormResult "Terms", ssVendorMaster("Terms") wp.SetFormResult "Shipping", ssPurchases("Ship") '-------------------------------------- ' Show me '-------------------------------------- wp.FilePrintPreview '-------------------------------------- ' Wait for user input '-------------------------------------- MsgBox "Alt-Tab to the Word document" '-------------------------------------- ' Clear the memory used by Word '-------------------------------------- Set wp = Nothing End Sub 
Brian Singleton
Brian Singleton is former editor of Midrange Computing. He has worked in the IBM midrange arena for many years, performing every job from backup operator to programmer to systems analyst to technology analyst for major corporations and IBM Business Partners. He also has an extensive background in the PC world. Brian also developed a line of bestselling Midrange Computing training videos, authored the bestselling i5/OS and Microsoft Office Integration Handbook, and has spoken at many popular seminars and conferences.

MC Press books written by Brian Singleton available now on the MC Press Bookstore.

i5/OS and Microsoft Office Integration Handbook i5/OS and Microsoft Office Integration Handbook
Harness the power of Microsoft Office while exploiting the iSeries database.
List Price $79.95

Now On Sale

BLOG COMMENTS POWERED BY DISQUS

LATEST COMMENTS

Support MC Press Online

$

Book Reviews

Resource Center

  • SB Profound WC 5536 Have you been wondering about Node.js? Our free Node.js Webinar Series takes you from total beginner to creating a fully-functional IBM i Node.js business application. You can find Part 1 here. In Part 2 of our free Node.js Webinar Series, Brian May teaches you the different tooling options available for writing code, debugging, and using Git for version control. Brian will briefly discuss the different tools available, and demonstrate his preferred setup for Node development on IBM i or any platform. Attend this webinar to learn:

  • SB Profound WP 5539More than ever, there is a demand for IT to deliver innovation. Your IBM i has been an essential part of your business operations for years. However, your organization may struggle to maintain the current system and implement new projects. The thousands of customers we've worked with and surveyed state that expectations regarding the digital footprint and vision of the company are not aligned with the current IT environment.

  • SB HelpSystems ROBOT Generic IBM announced the E1080 servers using the latest Power10 processor in September 2021. The most powerful processor from IBM to date, Power10 is designed to handle the demands of doing business in today’s high-tech atmosphere, including running cloud applications, supporting big data, and managing AI workloads. But what does Power10 mean for your data center? In this recorded webinar, IBMers Dan Sundt and Dylan Boday join IBM Power Champion Tom Huntington for a discussion on why Power10 technology is the right strategic investment if you run IBM i, AIX, or Linux. In this action-packed hour, Tom will share trends from the IBM i and AIX user communities while Dan and Dylan dive into the tech specs for key hardware, including:

  • Magic MarkTRY the one package that solves all your document design and printing challenges on all your platforms. Produce bar code labels, electronic forms, ad hoc reports, and RFID tags – without programming! MarkMagic is the only document design and print solution that combines report writing, WYSIWYG label and forms design, and conditional printing in one integrated product. Make sure your data survives when catastrophe hits. Request your trial now!  Request Now.

  • SB HelpSystems ROBOT GenericForms of ransomware has been around for over 30 years, and with more and more organizations suffering attacks each year, it continues to endure. What has made ransomware such a durable threat and what is the best way to combat it? In order to prevent ransomware, organizations must first understand how it works.

  • SB HelpSystems ROBOT GenericIT security is a top priority for businesses around the world, but most IBM i pros don’t know where to begin—and most cybersecurity experts don’t know IBM i. In this session, Robin Tatam explores the business impact of lax IBM i security, the top vulnerabilities putting IBM i at risk, and the steps you can take to protect your organization. If you’re looking to avoid unexpected downtime or corrupted data, you don’t want to miss this session.

  • SB HelpSystems ROBOT GenericCan you trust all of your users all of the time? A typical end user receives 16 malicious emails each month, but only 17 percent of these phishing campaigns are reported to IT. Once an attack is underway, most organizations won’t discover the breach until six months later. A staggering amount of damage can occur in that time. Despite these risks, 93 percent of organizations are leaving their IBM i systems vulnerable to cybercrime. In this on-demand webinar, IBM i security experts Robin Tatam and Sandi Moore will reveal:

  • FORTRA Disaster protection is vital to every business. Yet, it often consists of patched together procedures that are prone to error. From automatic backups to data encryption to media management, Robot automates the routine (yet often complex) tasks of iSeries backup and recovery, saving you time and money and making the process safer and more reliable. Automate your backups with the Robot Backup and Recovery Solution. Key features include:

  • FORTRAManaging messages on your IBM i can be more than a full-time job if you have to do it manually. Messages need a response and resources must be monitored—often over multiple systems and across platforms. How can you be sure you won’t miss important system events? Automate your message center with the Robot Message Management Solution. Key features include:

  • FORTRAThe thought of printing, distributing, and storing iSeries reports manually may reduce you to tears. Paper and labor costs associated with report generation can spiral out of control. Mountains of paper threaten to swamp your files. Robot automates report bursting, distribution, bundling, and archiving, and offers secure, selective online report viewing. Manage your reports with the Robot Report Management Solution. Key features include:

  • FORTRAFor over 30 years, Robot has been a leader in systems management for IBM i. With batch job creation and scheduling at its core, the Robot Job Scheduling Solution reduces the opportunity for human error and helps you maintain service levels, automating even the biggest, most complex runbooks. Manage your job schedule with the Robot Job Scheduling Solution. Key features include:

  • LANSA Business users want new applications now. Market and regulatory pressures require faster application updates and delivery into production. Your IBM i developers may be approaching retirement, and you see no sure way to fill their positions with experienced developers. In addition, you may be caught between maintaining your existing applications and the uncertainty of moving to something new.

  • LANSAWhen it comes to creating your business applications, there are hundreds of coding platforms and programming languages to choose from. These options range from very complex traditional programming languages to Low-Code platforms where sometimes no traditional coding experience is needed. Download our whitepaper, The Power of Writing Code in a Low-Code Solution, and:

  • LANSASupply Chain is becoming increasingly complex and unpredictable. From raw materials for manufacturing to food supply chains, the journey from source to production to delivery to consumers is marred with inefficiencies, manual processes, shortages, recalls, counterfeits, and scandals. In this webinar, we discuss how:

  • The MC Resource Centers bring you the widest selection of white papers, trial software, and on-demand webcasts for you to choose from. >> Review the list of White Papers, Trial Software or On-Demand Webcast at the MC Press Resource Center. >> Add the items to yru Cart and complet he checkout process and submit

  • Profound Logic Have you been wondering about Node.js? Our free Node.js Webinar Series takes you from total beginner to creating a fully-functional IBM i Node.js business application.

  • SB Profound WC 5536Join us for this hour-long webcast that will explore:

  • Fortra IT managers hoping to find new IBM i talent are discovering that the pool of experienced RPG programmers and operators or administrators with intimate knowledge of the operating system and the applications that run on it is small. This begs the question: How will you manage the platform that supports such a big part of your business? This guide offers strategies and software suggestions to help you plan IT staffing and resources and smooth the transition after your AS/400 talent retires. Read on to learn: