29
Fri, Nov
0 New Articles

Untangle the Web with RPG and CGI

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

A few articles have dealt with using RPG to write Common Gateway Interface (CGI) applications, which allow midrange programmers to use tools already available to produce e-commerce solutions for companies. Those articles dive right into using APIs to produce nifty HTML output, something every IT shop will soon have to deal with.

As a writer, I am sometimes so excited to share new technology that I don’t realize how fast I may be going. I hope I can make up for that in this article, in which I show you, step by step, how to take an everyday program and convert it into a CGI application. Keep in mind that the only real difference between RPG programs and CGI applications is the way they read input and write output. To make this transition as painless as possible, I use a basic invoice-printing program, an application many people are familiar with. With this program, the user can enter either the number of an invoice to be printed or a customer number that prints all open invoices. An extra parameter allows the user to specify an invoice reprint. In this article, I discuss the files used and the RPG and CGI applications. I also show you the similarities and differences between these applications. You can download the source for all the files and both applications at www.midrangecomputing.com/mc/.

The Data Files

Because the data files used in this article are exactly the same for each application, let me give you a quick rundown of what they are. The Order Header file (ORDHDRPF) contains basic order information, such as the invoice and customer numbers, and a flag that tells the system whether the invoice has been printed. The Order Detail file (ORDDETPF) contains line-item information, such as the item number, description, and invoice quantity. Finally, the Order Shipment file (ORDSHPPF) contains address information for the invoice.

The RPG Application

RPG program PRTINV1RG prompts the user for an invoice number or customer number and asks if the user wants to reprint the invoice(s). PRTINVDF1 is the display file that goes along with this program. PRTINV1RG checks errors to make sure that either an

invoice or customer number has been entered and verifies that the Reprint Invoices field contains either Y or N.

After the data is validated, the invoice number, customer number, and reprint flag are passed to RPG program PRTINV2RG, which uses these parameters to build an Open Query File (OPNQRYF) command that selects records from ORDHDRPF for printing. The files are then processed, and the invoices are printed. Printer file PRTINV2PT contains the DDS source for the printer file.

The CGI Application

HTML file CGIINV.HTML lets the user enter the invoice or customer number and the reprint flag. (Figure 1 shows how this entry screen appears in a browser.) CGIINV.HTML also performs error checking to ensure that an invoice or customer number is entered and uses JavaScript to verify that the Reprint Invoices field contains either Y or N. Don’t let this scare you off, however. CGIINV.HTML is not Java and does not require compilation or loading of classes onto your machine. JavaScript is an interpreted scripting language that can be embedded in HTML documents.

When a user clicks on Print, control is passed to CGI program CGIINVRG if no errors are found. This program uses the Get Environment Variable (QtmhGetEnv) API to read the query string environment variables. The Convert to Database (QtmhCvtDB) API parses the received data into a data structure that you provide. Once you have these values, an OPNQRYF command is built and run on ORDHDRPF. The data retrieved is then read, and the Write to Standard Output (QtmhWrStout) API uses that data to write the invoice information to a Web page.

Compare and Contrast

These RPG and CGI applications perform the same functions yet use different methods of input and output. The RPG application uses a display screen for input, an RPG program for processing, and a printer file for output. In contrast, the CGI application uses an HTML file (Web page) for input and initial error checking, an RPG program for processing, and a dynamically created Web page for output. To show the differences and similarities in these applications, let me walk you through each section step by step.

In each application, a front-end allows the user to input data, verifies that the data is correct, and passes it to the processing program. Figures 2 and 3 contain partial source for the RPG program and HTML file, respectively. Each section is labeled and color-coded to relate each section together. For example, section A represents error checking, and section B represents passing parameters and control to the processing program.

All the action in the HTML file takes place when the user clicks the Print button. The Print button is associated with the onClick event, which tells the browser to execute the Validate() function when the user clicks Print. The parameter this.form tells the browser to pass the values from the form to the JavaScript function. Validate() uses properties from the form to retrieve the invoice number, customer number, and reprint flag from each element and performs a series of checks, building an error message if it encounters any errors. When error checking is done, Validate() uses the Alert() method to prompt a dialog box to appear with the errors listed if the error field contains anything but blanks. Alert() is best compared to the DISPLAY op code in RPG; it’s built into JavaScript and doesn’t need to be declared anywhere. The data it receives is the data it displays.

An error field with no value tells Validate() that no errors were encountered. Validate() then uses the window.location method to redirect the page to the URL of the CGI program you wish to run (CGIINVRG, in this case). The data collected from the form is also passed as a parameter in the form of query string environment variables.

Now, I’ll examine the processing programs. These programs receive the parameters passed into them and display the invoice. However, the RPG program prints the invoice, whereas the CGI program displays the invoice on a browser. Figures 4 and 5 are partial

representations of the RPG and CGI code for each application. The important source for each application is labeled and color-coded as before. Label C represents the parameter processing, and Label D represents the code that processes data and produces output.

The major differences between these code examples are evident. Again, because you are probably already familiar with the RPG program, I will focus on the CGI program CGIINVRG.

Section C shows the code for two subroutines. The first, $GetQS, uses the QtmhGetEnv API to read the query string data passed into it. This API reads environment variables, such as query string data in this case. The second subroutine, $CvtDB, converts this data into data structure EnvDS so the CGI program can use it. Because the field names on the HTML form match the field names in the EnvDS data structure, this API knows to parse the data into the correct fields. For more information on how these APIs work, see the Web Programming Guide V4R3.

Section D contains code used to output the information. In the case of CGIINVRG, information appears on a Web browser via the QtmhWrStout API, which writes the data passed into it to the Web browser. This data can be any type of code that can be written to a browser (usually JavaScript or HTML). Figure 6 shows a sample of the invoice produced by CGIINVRG.

The similarities between the two applications are obvious. Both perform the same operations: display, error checking, record selection, and display of information. If you download the complete source code for this article, you will notice that the code that creates the OPNQRYF command and reads the data files is nearly identical in each example. This is the meat and potatoes of the application and doesn’t change from RPG to CGI applications, making the learning curve smaller for CGI applications written in RPG.

Time for a Change?

The point is, despite all the new technology available, RPG may still be your best bet. You can use most of the tools you’re familiar with, and you have to learn only the basics of HTML and JavaScript, both of which have countless resources available on the Internet. Providing information via a browser is much more versatile than trying to format it into an email and distribute it to multiple users. With the Internet, you can create it once and simply point people to it. If you are creating output-only applications, you need only the QtmhWrStout API, and if you require input, you need a minimum of two more APIs.

Use the applications provided here to start your CGI programming. Once you get the hang of it, dig into IBM’s books and the many articles written on the subject to get even more results from your CGI applications. After all, managers and users dig Web pages!

Reference

Web Programming Guide V4R3 (GC41-5435-02, CD-ROM QB3AEQ02)

Related Materials

• “RPG and CGI: Code Word—Dynamic!” Bradley V. Stone, MC, April 1999
• “RPG and HTML: Another Winning Team,” Bradley V. Stone, MC, May 1999




Figure 1: The HTML file lets the user enter the invoice or customer number and the reprint flag.


C if (WSINV 0) and (WSCUST 0)
C eval ERROR = ‘Cannot enter both Invoice Number ‘ +
C ‘and Customer Number’
C ITER
C endif
C if (WSINV = 0) and (WSCUST = 0)
C eval ERROR = ‘Enter an Invoice Number or a ‘ +
C ‘Customer Number’
C ITER
C endif
C if (WSREPRT ‘Y’) and (WSREPRT ‘N’)
C eval ERROR = ‘Reprint Invoice(s) must be Y or N’
C ITER
C endif

C CALL ‘PRTINV2RG’
C PARM WSINV
C PARM WSCUST
C PARM WSREPRT



Untangle_the_Web_with_RPG_and_CGI04-00.png 858x554

A

B

Figure 2: The RPG program contains code for input and error checking.

function Validate(form) {
var error = “”;
if ((form.wsinv.value != “”) && (form.wscust.value != “”)) {
error = “Cannot enter both Invoice Number and Customer Number ”;
}

if ((form.wsinv.value == “”) && (form.wscust.value == “”)) {
error = “Enter an Invoice Number or a Customer Number ”;
}

if ((form.wsreprt.value.toUpperCase() != “Y”) &&

(form.wsreprt.value.toUpperCase() != “N”)) {
error = error + “Reprint Invoice(s) must be Y or N ”;
}

if (error != “”) {
error = “The following error(s) exist: ” + error;
alert(error);

}

else {
window.location=”/cgi-bin/cgiinvrg?wsinv=” +
form.wsinv.value + “&wscust=” +
form.wscust.value + “&wsreprt=” +
form.wsreprt.value.toUpperCase();
}

}

A

B

Figure 3: The HTML file also contains code for input and error checking.

C *ENTRY PLIST
C PARM WSINV 9 0
C PARM WSCUST 9 0
C PARM WSREPRT 1

C $PRINT BEGSR
C OPEN ORDHDRPF
C READ ORDHDRPF
C dow (not %eof)
C eval GRDTOT = 0
C OHINV CHAIN ORDSHPPF
C WRITE HDG
C OHINV SETLL ORDDETPF
C OHINV READE ORDDETPF *

C dow (not %eof)
C eval EXTPRICE = (ODQTY * ODPRICE)
C eval GRDTOT = (GRDTOT + EXTPRICE)
C WRITE DET
C OHINV READE ORDDETPF
C enddo *

C WRITE BOT
C READ ORDHDRPF
C enddo *

C CLOSE ORDHDRPF
C ENDSR

C

D

Figure 4: The RPG program handles processing and printing.

C $GetQS BEGSR
C CALLB 'QtmhGetEnv'
C PARM EnvRec
C PARM EnvRecLen
C PARM EnvLen
C PARM EnvName
C PARM EnvNameLen
C PARM WPError
C ENDSR
C $CvtDB BEGSR
C if (EnvLen = 0)
C eval EnvLen = %size(EnvRec)
C endif
C CALLB 'QtmhCvtDb'
C PARM EnvFile
C PARM EnvRec
C PARM EnvLen
C PARM EnvDS
C PARM CvtLen
C PARM CvtLenAv
C PARM CvtStat
C PARM WPError
C ENDSR

C $PRINT BEGSR
C OPEN ORDHDRPF
C READ ORDHDRPF
C dow (not %eof)
C eval GRDTOT = 0
C OHINV CHAIN ORDSHPPF
C EXSR $HDG
C OHINV SETLL ORDDETPF
C OHINV READE ORDDETPF *

C

D

C dow (not %eof)
C eval EXTPRICE = (ODQTY * ODPRICE)
C eval GRDTOT = (GRDTOT + EXTPRICE)
C EXSR $DET
C OHINV READE ORDDETPF
C enddo *

C EXSR $BOT
C READ ORDHDRPF
C enddo *

C CLOSE ORDHDRPF
C ENDSR

*************************************************

C $HDG BEGSR
C eval WrtDta = '

' +
C '
' +
C '
' +
C '
' +
C '
' +
C '
' +
C '
' +
C '
' +
C '
' +
C '
' +
C '
Customer:' + %editc(OHCUST:'Z') +
C '
Invoice:' + %editc(OHINV:'Z') +
C '
' + %trim(OSNAME) + 'Rec Date:' +
C %editw(OHRECDAT:' / / ') +
C '
' + %trim(OSADDR1) + 'Due Date:' +
C %editw(OHDUEDAT:' / / ') +
C '
' + %trim(OSADDR2) + 'Total Due:' + %editc(OHTOTDUE:'3') +
C '
' + %trim(OSCITY + OSSTATE + OSZIP) +
C '
' + NewLine
C EXSR $WrStout
C eval WrtDta = '' +
C '' +
C '' +
C '' +
C '' +
C '' +
C NewLine
C EXSR $WrStout
C ENDSR
*************************************************

C $DET BEGSR
C eval WrtDta = '

' +
C NewLine
C EXSR $WrStout
C ENDSR
*************************************************

C $BOT BEGSR
C eval WrtDta = '

' +
C '
QtyItemDescriptionPriceTotal Due
' +
C %editc(ODQTY:'3') + '
' +
C %trim(ODITEM) + '
' +
C %trim(ODDESC) + '
' +
C %editc(ODPRICE:'3') + '
' +
C %editc(EXTPRICE:'3') + '
Grand Total:' +
C %editc(GRDTOT:'3') + '
' +
C NewLine
C EXSR $WrStout
C ENDSR
*************************************************

C $WrStout BEGSR
C eval WrtDtaLen = %len(%trim(WrtDta))
C CALLB 'QtmhWrStout'
C PARM WrtDta
C PARM WrtDtaLen
C PARM WPError
C ENDSR

D

Figure 5: The CGI program also handles processing and printing.


Figure 6: This is what an HTML invoice looks like.





Untangle_the_Web_with_RPG_and_CGI09-00.png 899x647
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: