11
Wed, Dec
4 New Articles

Are We There Yet? Find Out with the RPGLE Progress Bar

RPG
Typography
  • Smaller Small Medium Big Bigger
  • Default Helvetica Segoe Georgia Times
Eliminate user frustration by giving them feedback about long-running jobs.

If you've ever created an interactive application that processes a lot of data, and as a result runs for a long time, you've probably had situations where a user thought that the application was hung. While your first instinct might be to go into a long explanation of how applications on the System i don't "hang" like Windows applications do, there is another option. Giving simple user feedback for situations like this can help prevent the perception that your code is inefficient and takes too long. In this article, we'll examine how to do this with a simple RPGLE subprocedure.

Making Progress

 

The key to an application that can realistically support a progress bar is that the application itself has to be processing the data. What I mean by this is that an application that hands off reading and processing of the data to another application or that experiences a long wait time on an SQL EXEC, for example, wouldn't be a good candidate for this type of approach. Ideally, you would want to present a progress bar for a process that reads data from either a database file or another source, such as a Web service or Excel file, and performs some sort of processing with that data.

In each circumstance, you would have to have some way to determine the number of records to be processed prior to beginning your processing. This would be used to determine how far through the process you are. An example might be a process that generates and sends statements to customers. Prior to executing the process, you would determine the number of records in the statements database file and pass that into the RPGLE program that generates the statements. This value would then be used to determine, based on the number of records read, what percent of the process is complete. This information can then be passed to the progress bar subprocedure to generate and update the progress bar display.

 

The complete source for this example can be found here.

PROGBAR Subprocedure

 

To start off, let's examine the code for the procedure prototype for the PROGBAR subprocedure. This code is shown below.

 

      * Subprocedure prototypes for PROGBAR service program.

 

      *

 

      *   These prototypes are used to create and display a progress bar

 

      *   within an RPGLE program.

 

      *

 

 

      * Constants

 

     d COLOR_RED       c                   CONST(x'A9')

 

     d COLOR_WHITE     c                   CONST(x'A3')

 

     d COLOR_BLUE      c                   CONST(x'BB')

 

     d COLOR_PINK      c                   CONST(x'B9')

 

     d COLOR_GREEN     c                   CONST(x'A1')

 

 

      * Create a new progress bar

 

     d createProgressBar...

 

     d                 PR              *

 

 

      * Display a previously defined progress bar

 

     ddisplayProgressBar...

 

     d                 PR             1N

 

     d barObjOPtr                      *

 

 

      * Remove a previously created progress bar

 

     d destroyProgressBar...

 

     d                 PR

 

     d barObjPtr                       *

 

 

     d prgBars         DS                  dim(10) qualified

 

     d  barActive                     1N

 

     d  barIndex                      5  0

 

     d  Percent                       3  0 inz(0)

 

     d  StatusMessage                75

 

     d  WindowTitle                  20

 

     d  Color                         1A   inz(COLOR_GREEN)

 

     d  ShowPercent                   1N   Inz(*ON)

 

     d  WindowTop                     2  0 inz(1)

 

 

Note that this prototype member contains constant definitions for colors to be used to define the color of the progress bar itself. This source also defines the procedure prototype for the following three subprocedures:

 

  • createProgressBar--This routine simply creates a pointer for a new progress bar object.
  • displayProgressBar--This procedure is used to display or update the display of our progress bar object.
  • destroyProgressBar--This procedure removes the progress bar from memory. If no active progress bars remain, this procedure also closes the screen containing the progress bar window.

 

Because of the way that the progress bar objects are defined, it's actually possible to have multiple progress bars active within the same program; for example, you may want to have one bar that indicates progress for subtasks within a larger process and another that indicates progress for the entire process. The prgBars data structure is used to define the attributes of our progress bar. These attributes are listed in the table below.

 

Attributes Used to Define a Progress Bar

 

Attribute Name

 

Description

 

Type

 

Length

 

barActive     

An indicator that identifies whether or not the progress bar is still in use

Indicator (on/off)

1

barIndex      

Counter used as the unique identifier for the progress bar

Numeric

5,0

Percent       

Percent value (0-100) used to define the length of the progress bar shown to indicate task completeness

Numeric

3.0

StatusMessage 

Text value used to display an optional status message within the progress bar window

Alphanumeric

75

WindowTitle   

Text used as the title for the progress bar window.

Alphanumeric

20

Color         

Used to indicate the color for the progress bar itself using one of the defined color constants

1-character hex value

1

ShowPercent   

An indicator used to identify whether or not to display the percentage value within the progress bar

Indicator (on/off)

1

WindowTop      

Indicates top line position for the status bar window. Note this must be set to a value small enough to allow the entire window to fit on the display.

Numeric

2,0

 

The data structure containing these values can be associated with multiple program variables, effectively giving you the ability to display multiple progress bars from within a single program. Some of these values, like the Color and ShowPercent values, will be set when the bar is initially created. Others, such as the Percent and StatusMessage values, can be changed each time the status bar is displayed. Note that the Color attribute is defined using one of the five color constant values shown in the table below:

 

Color Constant Values

 

Color Constant

 

Description

 

COLOR_RED      

 

Red progress bar

COLOR_WHITE     

 

White progress bar

COLOR_BLUE

Blue progress bar

COLOR_PINK

Pink progress bar

COLOR_GREEN

Green progress bar (default value)

 

 

The source for the PROGBAR service program is shown below:

 

     h nomain BNDDIR('PROGBAR')

 

 

     fprogbarfm cf   e             workstn USROPN

 

     f                                     infds(scr_infds)

 

 

      /copy qrpglesrc,progbarpr

 

     d pos             s              3  0

 

     d bars            S                   like(prog) inz(*ALLx'4f')

 

     d rtnVal          S              1N

 

     d scr_close       S              1N

 

     d barCount        S             10I 0

 

     dscr_infds        ds

 

     d scr_open                9      9N

 

 

     P createProgressBar...

 

     P                 B                   EXPORT

 

 

     d createProgressBar...

 

     d                 PI              *

 

     d rtnVal          S               *

 

     d ix              S              5  0

 

      /free

 

       rtnval = *NULL;

 

       for ix = 1 to %elem(prgBars);

 

         if not prgBars(ix).barActive;

 

           prgBars(ix).barActive = *ON;

 

           prgBars(ix).barIndex = ix;

 

           rtnval = %addr(prgBars(ix));

 

           leave;

 

         endif;

 

       endfor;

 

       if not scr_open;

 

         open progbarfm;

 

       endif;

 

       return rtnVal;

 

      /end-free

 

     p createProgressBar...

 

     P                 E

 

 

     PdisplayProgressBar...

 

     P                 B                   EXPORT

 

 

     ddisplayProgressBar...

 

     d                 PI             1N

 

     d barObjPtr                       *

 

     d objProgBar      DS                  based(barObjPtr) Likeds(prgBars)

 

      /free

 

         if not scr_open;

 

           open progbarfm;

 

           scr_close = *ON;

 

         endif;

 

         // create new bar

 

         if objProgBar.barActive;

 

           COLOR = objProgBar.Color;

 

           sline = objProgBar.WindowTop;

 

           title = objProgBar.WindowTitle;

 

           if title = '';

 

             title = 'Progress Bar';

 

           endif;

 

           pos = (objProgBar.Percent/100)*75;

 

           prog = %subst(bars: 1: pos);

 

           status = objProgBar.StatusMessage;

 

           if pos<1;

 

              pos = 1;

 

           endif;

 

           if objProgBar.ShowPercent = *ON;

 

             %subst(PROG:37:4) = %EDITW(objProgBar.Percent:'  0%');

 

           endif;

 

           %subst(PROG:pos:1) = x'24';

 

           write progbarw;

 

         endif;

 

         if scr_close;

 

           close progbarfm;

 

         endif;

 

         Return rtnVal;

 

      /end-free

 

     PdisplayProgressBar...

 

     P                 e

 

 

     P destroyProgressBar...

 

     P                 B                   EXPORT

 

 

     d destroyProgressBar...

 

     d                 PI

 

     d barObjPtr                       *

 

     d lclBar          DS                  BASED(barObjPtr) likedS(prgBars)

 

     d

 

     d rtnVal          S              1N

 

     d ix              S              5  0

 

     d activeBars      S              1N

 

      /free

 

        activeBars = *OFF;

 

        if barObjPtr <> *NULL;

 

          lclBar.barActive = *OFF;

 

          for ix = 1 to %elem(prgBars);

 

            if prgBars(ix).barActive;

 

              activeBars = *ON;

 

            endif;

 

          endfor;

 

          if scr_open and not activeBars;

 

            close progbarfm;

 

            *INLR = *ON;

 

          endif;

 

        endif;

 

        return;

 

      /end-free

 

     P destroyProgressBar...

 

     P                 e

The functionality performed by this service program is fairly straightforward. We use a 75-byte field as the progress display. That field is manipulated using the hex codes for specific reverse-image color attributes. The hex display attribute value used to turn off reverse-image is then used to end the progress bar. The result is that we end up with a portion of the 75-byte field displayed in reverse-image to indicate percent of completeness.

 

To utilize this functionality, we must first initialize our new progress bar using the createProgressBar subprocedure. The subprocedure accepts no parameters, but returns a pointer to the newly created progress bar object. Next, we define the values for our progress bar using a data structure defined like the prgBars data structure. Note that this data structure is what the pointer created by the createProgressBar subprocedure points to. Each time we want to display (or update) our progress bar, we use the displayProgressBar subprocedure. This subprocedure accepts a single parameter, which is the resulting pointer returned by the createProgressBar subprocedure. Once a given progress bar is no longer needed, use the destroyProgressBar subprocedure to deactivate the progress bar itself and perform any additional cleanup task, including closing the display file and setting on LR when all progress bars have been destroyed.

Putting It to Use

 

To better illustrate how to utilize the PROGBAR service program, I've included the sample program shown below:

 

     H DFTACTGRP(*NO) BNDDIR('PROGBAR')

 

     Ftestscr   cf   e             workstn

 

      /copy qrpglesrc,progbarpr

 

     D x               s              3  0

 

     D x1              s             13  0

 

     D pcta            s              5

 

     D progBar1Obj     S                   like(createProgressBar)

 

     D progBar2Obj     S                   like(createProgressBar)

 

     D progBar3Obj     S                   like(createProgressBar)

 

     D progBar1        DS                  likeDS(prgBars) based(progBar1Obj)

 

     D progBar2        DS                  likeDS(prgBars) based(progBar2Obj)

 

     D progBar3        DS                  likeDS(prgBars) based(progBar3Obj)

 

      /free

 

        progBar1Obj = createProgressBar();

 

        if progBar1Obj <> *Null;

 

          progBar1.WindowTop = 3;

 

          progBar1.WindowTitle = 'Test # 1';

 

          progBar1.Color = COLOR_BLUE;

 

          progBar1.ShowPercent = *ON;

 

        endif;

 

        progBar3Obj = createProgressBar();

 

        if progBar3Obj <> *Null;

 

          progBar3.WindowTop = 17;

 

          progBar3.WindowTitle = 'Window 3';

 

          progBar3.Color = COLOR_RED;

 

          progBar3.ShowPercent = *ON;

 

        endif;

 

        progBar2Obj = createProgressBar();

 

        if progBar2Obj <> *Null;

 

          progBar2.WindowTop = 10;

 

          progBar2.WindowTitle = 'Test # 2';

 

          progBar2.Color = COLOR_PINK;

 

          progBar2.ShowPercent = *OFF;

 

        endif;

 

 

        for x = 1 to 25;

 

          progBar1.Percent = x;

 

          pctA = %editw(progBar1.Percent: '  0%');

 

          progBar1.StatusMessage = 'This process is at '+ pctA;

 

          displayProgressBar(progBar1Obj);

 

          progBar2.Percent = x*4;

 

          pctA = %editw(progBar2.Percent: '  0%');

 

          progBar2.StatusMessage = 'Saving changed objects '+pctA+' Complete.';

 

          displayProgressBar(progBar2Obj);

 

          progBar3.Percent = x*3;

 

          pctA = %editw(x:'   ');

 

          progBar3.StatusMessage = 'Generic Status Message # ' + pctA;

 

          displayProgressBar(progBar3Obj);

 

        endfor;

 

        destroyProgressBar(progBar1Obj);

 

        destroyProgressBar(progBar2Obj);

 

        destroyProgressBar(progBar3Obj);

 

        exfmt tests01;

 

        *INLR = *ON;

 

        Return;

Note that this example actually creates multiple progress bars concurrently. We define both a pointer and a data structure associated with that pointer for each progress bar created.

 

As described earlier, we first create the bar using createProgressBar and then identify the associated attributes for that bar, including the color, title, and top position along with the indicator identifying whether or not to show the percentage. Next, we simulate the data processing using a for/endfor loop and incrementing the percent value for each bar along with the status message for each prior to executing the displayProgressBar subprocedure to display each progress bar window. Once all processing is complete, destroy each bar using destroyProgressBar. Upon execution of the final destroyProgressBar, the application will automatically close the display file and set on *INLR. Our sample application then does an exfmt to output its own display file simply to wait for the user to press Enter before exiting. Figure 1 below illustrates what the final screen looks like prior to pressing the Enter key.

 

 120308Faustprogbarfigure6.png

Figure 1: Here, you see the output from the PROGBAR service program.

 

Note that each bar is updated independent of the other two. The application can support a maximum of 10 active progress bars at any given time. Also note that in this example I've associated the PROGBAR service program with a binding directory by the same name to simplify compiles of any programs utilizing this functionality. To compile the service program, use the following two commands:

 

CRTRPGMOD MODULE(mylib/PROGBAR) SRCFILE(mylib/QRPGLESRC) SRCMBR(PROGBAR)

 

CRTSRVPGM SRVPGM(mylib/PROGBAR) EXPORT(*ALL) 

 

Once you've added this service program to the PROGBAR binding directory (or the appropriate binding directory of your choice), the sample program (TESTPRGBAR) can be compiled using the standard CRTBNDRPG command shown below:

 

CRTBNDRPG PGM(mylib/TESTPRGBAR) SRCFILE(MFDEV/QRPGLESRC) SRCMBR(TESTPRGBAR)       

 

 

Note that the binding directory containing the PROGBAR service program should be in your library list at compile time.

Are We There Yet?

 

Using a routine like this can help to curb user frustration during long-running interactive jobs by giving them feedback that indicates how much longer it should take. So maybe you won't have to feel like the tortured parent with the kids in the back seat repeatedly asking, "Are we there yet? Are we there yet?"

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: