25
Thu, Apr
1 New Articles

Remembrance of Things Last

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

Common Gateway Interface (CGI) is a standard method of programming for Web browsers. It is a client/server architecture by which a Web browser client communicates with a host-based server program. CGI is a new twist to the ancient technology on which UNIX and PC operating systems are based. Many of us did our first PC programming in some version of BASIC, probably BASICA or GW-BASIC. I wrote PRINT commands to write to the screen and INPUT statements to read from the keyboard. CGI programming works much the same way, except that the screen and keyboard are on a different computer than the one running the program and the Web browser replaces the old scrolling text-based display.

Green-screen lovers can think of the browser as a cutesy replacement for the dumb terminal. RPG doesn’t have equivalents for BASIC’s PRINT and INPUT commands, but the ILE version of RPG does have access to two bindable APIs that do the same things. Like BASIC’s PRINT command, the QtmhWrStout API writes to the screen, and like BASIC’s INPUT command, the QtmhRdStin API reads (albeit indirectly) from the keyboard.

However, you do not have to write AS/400 CGI programs in RPG. You can use other ILE languages (such as COBOL or C), scripting languages (such as REXX and Perl), Java, or C++. The basic idea of CGI is to create HTML dynamically from host- based application data. User input comes from fields of HTML forms, whose values are read by QtmhRdStin, and output comes from HTML generated by your language of choice and is passed back to the user by QtmhWrStout. I’ve written the example program in this article in RPG, and I direct my discussion toward RPG programmers.

The CGI standard has what I consider to be two glaring faults. The first fault is that CGI programs handle stream I/O, not record I/O. Although stream I/O has its place in computing, record I/O is much easier to work with, especially in typical data processing applications.

The second fault is that, on most server platforms, CGI programs treat every request as a brand-new interactive session. Whenever you click a Web browser’s Submit button, you execute a script or program that that goes through initialization (which may include opening files), runs until the end of the job, shuts down (which includes closing files), and is removed from memory. The AS/400, however, is no ordinary server platform. With activation groups and not setting on LR, the RPG CGI program is available

to handle remote requests iteratively. The problem with CGI programs is that they indiscriminately service Web requests from multiple users and don’t remember you from one time to the next. During your “think/wait” time, other Internet users can invoke the same instance of that RPG CGI program, thus repositioning file cursors and changing the value of program variables.

IBM and others have been working on this second fault. In this article, I show you how you can make CGI applications work like the green-screen apps I so love, in which you open one instance of a CGI specifically for one user. Consequently, you maintain cursors, and variables retain their values between responses from the user. In short, you can make a Web browser converse with an AS/400 the way a dumb terminal converses with an interactive RPG or COBOL program. This is known as persistent CGI.

Persistent CGI

Making a CGI program persistent is not difficult. You just have to send a little more code to the Web browser, change the program as necessary so you can enter it repeatedly without reactivation, and compile the program to run in a named activation group. I’ll examine each of these steps in more detail.

Sending a Little More Code

Whereas the first data a typical CGI program sends to a Web browser is the phrase “Content-type: text/html” followed by two end-of-line sequences, a persistent CGI program precedes this with two other strings of text. The first is “Accept-HTSession:” followed by a series of characters that serves as a session identifier. (Each instance of the persistent CGI program should have a unique identifier.) The method I have used is to store a number in a data area and increment it by one every time the program is activated. That is, in the onetime calcs, I generate a new session ID that must be sent to the browser and placed both after the Accept-HTSession header and at the end of the URL for the Submit button, which the user must click to reenter the program. A slash (/) separates the session ID.

Following the Accept-HTSession: header appears the text “HTTimeout:” followed by a nonnegative integer specifying the timeout interval for the session in minutes. The HTTimeout header is ignored if it does not follow the Accept-HTSession header.

Figure 1 shows part of the HTML code produced by program TKTINQ02RG. The session ID is the string “0000021,” and the timeout interval is 5 minutes. The FORM tag refers to the same program and session ID, causing the same instance of the program to be entered again when the user clicks Submit on the browser page.

Changing the Program

Changing a CGI program so you can reenter it without reactivation should be a no-brainer for RPG programmers because they are used to writing programs that are called repeatedly and exited without setting on the LR indicator. The first time a program is called, files must be opened, variables must be initialized, etc. On subsequent calls, however, the program skips those tasks. Persistent CGI programs should behave similarly.

Compiling the Program

Compiling a CGI program into a named activation group is also no problem. Pick a name, any name. In working up the examples for this article, I had roaring success using BBBBB as an activation group name. I could carry out separate conversations with the server from different browsers at the same time, and even though they used the same activation group name, neither interfered with the other, because they had separate session identifiers.

An Example

I worked up an example that you can download from the Midrange Computing Web site at www.midrangecomputing.com/mc/. It’s an order inquiry program based on a CGI application I wrote for a client of mine. The RPG IV program, portions of which are shown in Figure 2, reads two database files: an order header file called TKTHDR and an order detail file called TKTITM. (My client refers to a sales order as a ticket, hence the TKT prefixes.) Each order has one record in TKTHDR and a line in TKTITM for each item purchased. The one-time-only code executed in subroutine *INZSR generates a new session ID, and the LR indicator is not set on.

The program prompts the user for an order number, which the user sends back to the CGI program through standard in. The program looks up the order and displays it on the browser along with another prompt for an order number.

The code isn’t pretty, but I wanted to make it as simple as possible for you to run. I combined all the source members, prototypes and modules, into one source member for your convenience and used character literals to build everything to be sent to the Web browser instead of using my usual method of storing HTML in an array or file. I also removed all the JavaScript from the HTML. The routine that extracts the order number has no intelligence, so rather than extract the order number from a free-format string, it assumes the number is exactly five characters long and begins at position 8. For production programming, I have service programs that do all these things. IBM’s CGIDEVD library, which you can find on the Web at www.as400.ibm.com/net.data/tstudio/ workshop/snippets/newsnip.mac/viewsavf, is a save file containing plenty of code that handles these tasks and more.

Compilation and Execution

To install the example application, upload source member TKTINQ02RG to an RPGLE source file member of your choice and follow the compilation instructions at the beginning of the program. Then, create a data area for assigning session IDs by running the following Create Data Area (CRTDTAARA) command: Running the program may take some tweaking of the HTTP configuration via the Work with HTTP Configuration (WRKHTTPCFG) command. I had never run a CGI program on Midrange Computing’s 170 box, so I had to create my own HTTP configuration and server instance. The configuration I copied had Map directives like the following: However, I did not have to specify the .PGM suffix, because the Map directives would append .PGM to any URL with path CGI-BIN and look for those programs in library MYCGILIB.

Those Map directives would not work for persistent CGI, though, because the session ID must follow the URL, including the .PGM portion. I modified the Map directives as follows, meaning I would have to specify the .PGM suffix on all programs from that point forward:

CRTDTAARA DTAARA(xxx/SESSIONSEQ) +

TYPE(*DEC) LEN(7 0)

Map /cgi-bin/* /QSYS.LIB/MYCGILIB.LIB/*.PGM
Map /CGI-BIN/* /QSYS.LIB/MYCGILIB.LIB/*.PGM

Map /CGI-BIN/* /QSYS.LIB/MYCGILIB.LIB/*
Map /cgi-bin/* /QSYS.LIB/MYCGILIB.LIB/*

The other issue is how to terminate the program. Well, you don’t; it just times out according to the HTTimeOut: header.

Insist on Persistence

In addition to the RPG program, I’ve included in the code on the Web a CGI program written in C from the end of Chapter 4 of the Web Programming Guide V4R3. I started my investigation of persistent CGI by trying to make this program run. I figured I should begin with bug-free code so I wouldn’t have to worry about programming errors and could concentrate on making the program run persistently. Boy, was I surprised! The program had several bugs in it, at least some of which I found and removed. Once I had the C program working, making RPG do the same thing was easy. If you’ve tried to get that program to work without success, maybe the debugged version will work for you.

I’ve not been a big fan of CGI, but persistent CGI makes more sense to me than plain old vanilla CGI. The only downside of persistent CGI is that new CGI program instances are created for each remote user, potentially overworking main memory. In contrast, with standard CGI, one program instance handles all remote requests. Nevertheless, I like persistent CGI because it works more like the interactive RPG programs I’ve been writing since my System/34 days. I don’t know how much success I’ll end up having with CGI in my consulting practice, but if CGI is to be successful for me, I suspect it will be persistent CGI.

Reference

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

Related Materials

• “CGI Template Programming with IBM’s Snippets Library,” Don Denoncourt, AS/400 Internet Expert, August/September 1998
• “Persistent CGI and RPG,” Randy Dufault, AS/400 NetJava Expert, April/May 1999

Accept-HTSession: 0000021
HTTimeout: 5
Content-type: text/html

Order Inquiry

Jack’s Sales

Order Inquiry


... (more HTML code omitted)

FTktHdr if e k disk rename(TH: TicketHdr)
FTktItm if e k disk rename(TI: TicketLine)

... (procedure prototypes omitted)
D sds
D Proc *proc

D Color s 10
D NewLine c const(X'15')
D SessionID s 7
D SessionSeq s 7p 0
D Ticket s 5p 0
D ViewedCounter s 10u 0
D X s 1024 varying
D XPrice s 9p 2

C TicketKey klist
C kfld THORDR
C
C callp GetTicketNbr (Ticket)
C exsr PrtHeadings

Figure 1: Persistent CGI programs refer to themselves through session identifiers.

C if Ticket > *zero
C eval THORDR = Ticket
C TicketKey chain TicketHdr 90
C if *in90
C eval X = '

Ticket ' + %editc(Ticket: '3') +
C ' was not found; please re-enter .'
C callp WrtStdOut (X + NewLine)
C else
C exsr DspTicket
C endif
C endif
C exsr PrtFooter
C
C return *****

C DspTicket begsr
C
C eval ViewedCounter = ViewedCounter + 1 ... (code to display the order header info omitted)
C callp WrtStdOut (X + NewLine)
C exsr PrtDetails ... (code omitted)
C
C endsr *****

C PrtDetails begsr
C
C eval Color = 'red'
C TicketKey chain TicketLine 92
C dow *in92 = *off
C eval Xprice = TIQTY * TIUPRC
C eval X = '+
C '+
C TIPART +'
+
C +
C '+
C %editc(TIQTY: 'J') +'
+
C +
C '+
C %editc(TIUPRC: 'J') +'
+
C +
C '+
C %editc(XPRICE: 'J') +'
+
C '
C callp WrtStdOut (X + NewLine)
C if Color = 'red'
C eval Color = 'blue'

C else
C eval Color = 'red'
C endif
C TicketKey reade TicketLine 92
C enddo
C
C endsr ***************

C PrtHeadings begsr
C
C eval X = 'Accept-HTSession:' + SessionID
C callp WrtStdOut (X + NewLine)
C eval X = 'HTTimeout: 5'
C callp WrtStdOut (X + NewLine)
C eval X = 'Content-type: text/html'
C callp WrtStdOut (X + NewLine + NewLine)
C eval X = '+<BR>C Order Inquiry'
C callp WrtStdOut (X + NewLine)
C eval X = 'C LINK="#CC0033" VLINK="#330066" +
C ALINK=#FF0000>'
C callp WrtStdOut (X + NewLine)
C eval X = '

Jack''s Sales

+
C

Order Inquiry

'
C callp WrtStdOut (X + NewLine)
C eval X = '
C %trim(PROC) + '.PGM/' + SessionID +'>'
C callp WrtStdOut (X + NewLine)
C eval X = 'Enter a ticket number: +
C +
C '
C callp WrtStdOut (X + NewLine)

C
C endsr
C*****
C PrtFooter begsr
C eval X = '

Orders viewed:' +
C %editc(ViewedCounter: '1')
C callp WrtStdOut (X + NewLine)
C eval X = ''
C callp WrtStdOut (X + NewLine)

C
C endsr

*****

C *inzsr begsr
C
C *dtaara define SessionSeq SessionSeq
C *lock in SessionSeq
C eval SessionSeq = SessionSeq+ 1
C out SessionSeq
C move SessionSeq SessionID
C
C endsr *****

* Write to Standard Output
P WrtStdOut b
D pi
D OutDta 1024 value varying ... (code omitted)
P e *****

* Read from Standard Input
P RdStdIn b
D pi
D RcvRec 4096
D RcvLen 10i 0 ... (code omitted)
P e *****

P GetTicketNbr b
D GetTicketNbr pi
D Ticket 5p 0

D InData S 4096
D InLen s 10i 0
D TicketChar s 5
C
C eval Ticket = *ZERO
C callp RdStdIn (InData: InLen)
C if InLen > *zero
C eval TicketChar = %subst(InData: 8: 5)
C move TicketChar Ticket
C endif

P e

Figure 2: The RPG CGI program is similar in structure to a called program that remains active between invocations.

TED HOLT

Ted Holt is IT manager of Manufacturing Systems Development for Day-Brite Capri Omega, a manufacturer of lighting fixtures in Tupelo, Mississippi. He has worked in the information processing industry since 1981 and is the author or co-author of seven books. 


MC Press books written by Ted Holt available now on the MC Press Bookstore.

Complete CL: Fifth Edition Complete CL: Fifth Edition
Become a CL guru and fully leverage the abilities of your system.
List Price $79.95

Now On Sale

Complete CL: Sixth Edition Complete CL: Sixth Edition
Now fully updated! Get the master guide to Control Language programming.
List Price $79.95

Now On Sale

IBM i5/iSeries Primer IBM i5/iSeries Primer
Check out the ultimate resource and “must-have” guide for every professional working with the i5/iSeries.
List Price $99.95

Now On Sale

Qshell for iSeries Qshell for iSeries
Check out this Unix-style shell and utilities command interface for OS/400.
List Price $79.95

Now On Sale

BLOG COMMENTS POWERED BY DISQUS

LATEST COMMENTS

Support MC Press Online

$0.00 Raised:
$

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: