Application Development on Power System (IBM i )

85
Application Development on Power Application Development on Power System (IBM System (IBM i i ) ) Application Development on Power System (IBM i) School of Software Engineering Tongji University HUANGJie

description

Application Development on Power System (IBM i). Application Development on Power System (IBM i ). School of Software Engineering Tongji University HUANGJie. Syllabus. 2014/8/21. 2. Unit 3 IBM i Application Development. Chapter 7 Application Development. Outline. - PowerPoint PPT Presentation

Transcript of Application Development on Power System (IBM i )

Page 1: Application Development on Power System (IBM  i )

Application Development on Power System (IBM Application Development on Power System (IBM ii))

Application Development on Power System (IBM i)

School of Software Engineering Tongji University

HUANGJie

Page 2: Application Development on Power System (IBM  i )

No Subject Hours Abstract Instructor

1 Overview of IBM i 2 Server, Power System and Power System IBM i Huangjie

2 iOS fundamental 4 i OS & Basic Operation Huangjie

3 File system & object management 4 Object management concept and integrated file system Huangjie

4 Message management 2 Message & Its management Huangjie

5 Work management 4 Concepts of job, subsystem and library, job routing Huangjie

6 Administration ABC 2 Security, Storage & Restore Management Huangjie

7 Application Development 6 ILE development enviroment , RPG programming Huangjie

8 Database Development 4 Database on IBM i Huangjie

9 IBM i & SOA 2 SOA approach on IBM i Huangjie

10 Case Study 2 Csae Study Huangjie

11 Examination 2 Examination Huangjie

Syllabus

23/4/22 2

Page 3: Application Development on Power System (IBM  i )

Chapter 7 Chapter 7 Application DevelopmentApplication Development

Unit 3 IBM i Application Development

23/4/22 3

Page 4: Application Development on Power System (IBM  i )

Outline

•This module consists of:– RPG Introduction– Coding RPG– Structured Operation Codes– Indicators and Built-in-Functions (BIFs)– Using Files in RPG

Page 5: Application Development on Power System (IBM  i )

RPG Introduction

Page 6: Application Development on Power System (IBM  i )

RPG - Report Program Generator• RPG is not just a report generator. In fact, a fully fledged, high level language suited for processing and updating database files, performing complex calculations, interacting with users and creating reports.• RPG IV is a business-oriented, high level language that makes use of structured programming, subfiles, and other RPG built-in functions such as the RPG cycle and indicators.• Many parts of RPG are no longer commonly used

– e.g. the RPG Cycle – has evolved to a "structured" language

•There are many flavors of RPG– in "real life" you will find programs whose original structure (and

coding) date back to the inception of RPG!

Page 7: Application Development on Power System (IBM  i )

A Brief History•RPG – 1960s (System/360 mainframes)

– High Level Language, Fixed-Logic Cycle, Indicators, Batch Oriented, Card based machines

– Still in use today!•RPG II (System/3, System/32, System/34, System/36)

– Interactive applications• Disk processing support, Workstation support

•RPG III (System 38)– Structured program design for efficiency– DBMS grew in sophistication

•RPG/400 (AS/400)– RPG/400 is RPG III on the System i family (i.e. AS/400. iSeries, i5)– Enhancements

• New operation codes, Named constants, Initialization subroutines– Embedded SQL statements

Page 8: Application Development on Power System (IBM  i )

RPG IV•RPG IV

– First available with OS/400 V3R1 in 1994 – Component of ILE RPG/400 Program Product– Expanded or eliminated many RPG III language limits– Fulfilled many long-standing requirements

• Longer field names• Free form expressions• Date/time calculations

– Positioned for future growth– Participates in Integrated Language Environment (ILE)

•ILE – Integrated language environment – First available with V2R3– Greater modularity– Better performance

Page 9: Application Development on Power System (IBM  i )

Data Storage

Instruction Set

I/O Buffers

Standard Representation of an RPG Program

Page 10: Application Development on Power System (IBM  i )

Standard Representation of an RPG Program•Data Storage:

– Contains all data used by the program

•Instruction Set: – Sequence, logic, manipulation of data storage

•File Buffers: – I/O to and from the program

Page 11: Application Development on Power System (IBM  i )

Editor

QRPGLESRC*FILE (PF-SRC)

CRTBNDRPG

MYPGM*PGM

MYPGMMember Type

RPGLE

Coding and Compiling a Program

Page 12: Application Development on Power System (IBM  i )

.... ....1.... ....2.... ....3.... ....4.... ....5 /Free Dsply 'Hello World'; *InLR = *On; /End-Free

Hello World•The ubiquitous “Hello World”.

– A very simple program– Uses Free Form RPG

•Basic Rules for Free Form– Starts with /Free in position 7 of a line– Ends with /End-Free in position 7 of a line– All statements must be coded within positions 8 to 80– A statement must end with a semi-colon (;)– A statement may be on multiple lines

Page 13: Application Development on Power System (IBM  i )

Coding in RPG

Page 14: Application Development on Power System (IBM  i )

Program Development Cycle

•The program development cycle is the same for all languages– Define the problem– Design the solution– Design and Code the program– Compile, Test and debug the program– Document the program– Maintain the program

Page 15: Application Development on Power System (IBM  i )

RPG Code•RPG specifications stem from punched cards

– i.e. each line was 80 characters long•First five characters were for a sequence number

– No longer used– May be used as required - e.g. to identify modified lines

•Sixth position contains a “specification” identifier – Identifies the type of RPG line being entered– Defines how the rest of the line is interpreted– Not used in /Free style RPG

•Code may be entered in "mixed" case– Traditional RPG was upper case only– But code and variable names are not case sensitive

• e.g. FieldName = fieldname = FIELDNAME•In 2001, RPG Calculation specifications became "free format“

– But most existing code still has the traditional columnar look and feel

Page 16: Application Development on Power System (IBM  i )

RPG Specification Types•The specification types are:

– H(eader) Compiler directives and execution information.– F(ile) Declares files used in the program.– D(efinition) Defines data items used in the program.

• Arrays, tables, data structures, subfields, constants, standalone fields, procedure interfaces, and prototypes.

– I(nput) Input record layouts. (Rarely, if ever, used today)– C(alculation) What the program does!

• Fixed Form• Extended Factor 2• Free Form

– O(utput) Declares output record layouts. (Rarely, if ever, used).– P(rocedure) Marks the beginning and end of a subprocedure.

•Specifications, when used, must be in the order above.– Except that D-specs and C-Specs are permitted within

subprocedures•Blank lines are permitted - so use them.

Page 17: Application Development on Power System (IBM  i )

Flavors of RPG•There are now three flavors of RPG program

– Based on the way “calculation lines” are entered– Fixed Format

• Traditional RPG. Everything in the correct column– Extended Factor 2

• More flexible than Fixed Format. Still requires some column positioning

– Free Format• Most recent, so tends to appear mainly in new programs

•For the most part, on this course you will be using Free Format

.....CL0N01Factor1+++++++Opcode(E)+Factor2+++++++Result++++++++Len++D+HiLoEq C b Add c a

.....CL0N01Factor1+++++++Opcode(E)+Extended-factor2+++++++++++++++++++++++++++++ C Eval a = b + c

a = b + c;

Page 18: Application Development on Power System (IBM  i )

....+... 1 ...+... 2 ...+... 3 ...+... 4 ...+... 5 ...+... 6 ...+...

*---------------------------------------------------------------- * These are comments entered * using an asterisk * in position 7 of the line

*----------------------------------------------------------------

// These are comments entered // using a double slash // anywhere on the line

a = b + c; // This is a comment on a line with code

Comments•Comment lines may be placed anywhere in a program.

– “Traditional” style - Identified by an * in position 7 • The rest of the line contains any required comments• Does not require a line identifier in position 6 – although often

coded– “Modern” style - Comment may follow a double slash

• Must be used in free format• Also used for end-of-line comments following the “;” at the end of the line

Page 19: Application Development on Power System (IBM  i )

Program Variables and Basic Data Types•Program Variable

– Refers to a location in memory that can store data– RPG uses the term Field rather than variable

•Must have a name, length and data type– Fields are defined on D Specs

• May also be externally defined (more later)• May also be defined on fixed form Calc specs (more later)

•All fields in RPG are fixed in length– Even Varying length character fields occupy a fixed amount of memory

Type Description

A Character (default) – Fixed and Varying Length

S Zoned Decimal

P Packed Numeric (default)

I Integer

U Unsigned Integer

Page 20: Application Development on Power System (IBM  i )

Zoned and Packed Numbers

•Zoned – a digit is represented by a byte5 1111 0101 F5

6 1111 0110 F6

7 1111 0111 F7

8 1111 1000 F8

9 1111 1001 F9

0 1111 0000

F0

1 1111 0001

F1

2 1111 0010

F2

3 1111 0011

F3

4 1111 0100

F4F F F F F

1 2 3 4 5

F F F F D

1 2 3 4 5

1 3 5

2 4 F

1 3 5

2 4 D

Half byte (high) of right most digit indicates sign (D is negative)

Packed – a digit is represented by a half byte (nibble) Low order (right most) nibble of right most digit indicates sign

12345 12345-

12345 12345-

Page 21: Application Development on Power System (IBM  i )

Integers

RPG Bytes Range

3I 0 1 -128 to 127

5I 0 2 -32,768 to 32,767

10I 0 4 -2,147,483,648 to

2,147,483,647

20I 0 8 -9,223,372,036,854,775,807 to

9,223,372,036,854,775,807

3U 0 1 0 to 256

5U 0 2 0 to 65535

10U 0 4 0 to 4,294,967,295

20U 0 8 0 to 18,446,744,073,709,551,615

Page 22: Application Development on Power System (IBM  i )

DName+++++++++++ETDsFrom+++To/L+++IDc.Keywords+++++++++++++++++++++++++

D Spec (Definition)•D spec entries are “column specific”

– With the exception of the keyword area•D Specs are used to define fields

– Also used to define other items (more later)•Name

– The name of the field.– It is recommended that you leave a space between the D

(specification) and the beginning of the name.•Type of Definition (Ds)

– S for Stand Alone Field•Length (To/L), Internal Data Type (I) and Decimal Positions (Dc)

– The From entry is rarely used in modern RPG programs•Keywords

Page 23: Application Development on Power System (IBM  i )

.....DName+++++++++++ETDsFrom+++To/L+++IDc.Keywords++++++++++++++++++++ D Character S 30A D CharacterDft S 20 D Packed S 9P 0 D PackedDft S 11 2 D Integer S 10I 0 D UnsignedInt S 5U 0

D Spec (Definition)

•To define a standalone field, enter– Field name– Definition type of S– Length of field (number of characters or digits)– Internal data type (blank, A, P, S, I, U)

• Defaults to A if Decimal Positions is blank• Defaults to P If Decimal Positions is entered

– Decimal positions • Positions are implicit

Page 24: Application Development on Power System (IBM  i )

DName+++++++++++ETDsFrom+++To/L+++IDc.Keywords++++++++++++... D ThisIsAFieldWithAVeryVeryVeryVeryVeryVeryVery... D LongName S 20 D Count S 5I 0 Inz(1) D CountB S Like(Count)

D Spec (Definition)

•Long Names– Continue the name along the line and end with an ellipse (…)– Continue the name on the next line

•Basic Keywords– INZ (Initialize) allows you to specify an initial value for a field– LIKE allows you to define a field whose length and type are the same

as ("like“) another field’s. – There are many more keywords that we will meet later

Page 25: Application Development on Power System (IBM  i )

Names•Uniquely identify specific entities in a program or procedure

– Fields, Arrays, Key Field Lists, Named Constants, Parameter Lists, Data Structures, Subroutines, Subprocedures et al.

•Naming rules:– First character must be alphabetic (including $, #, and @)

• Use of special characters not recommended– Remaining characters must be alphabetic, numeric or underscore

(_)– The name can be from 1 to 4096 characters – External names can be from 1 to 10 (a restriction of DDS)– Names must be unique– Must not be a reserved word

• It is not hard to avoid these in RPG, there are very few• While not technically reserved words, it is good to avoid field names that

are operation codes

Page 26: Application Development on Power System (IBM  i )

Literals

•Literals are used to specify an actual value

•Character – Enclose the contents in single apostrophes

• Or as a hex literal e.g. X’F1’– Can be repeated by prefixing with *ALL

• E.g. *ALL’ABC’ •Numeric

– Must not be enclosed in apostrophes – May include digits 0 thru 9 – May include a decimal point and/or sign.

• The sign must be the left most character of the literal– May not contain commas, currency signs or percent sign

Page 27: Application Development on Power System (IBM  i )

Simple Arithmetic Expressions (1 of 3)

•Set the value of a numeric field equal to the result of a numeric expression•Based on an EVAL operation

– The actual EVAL op-code is optional unless an extender such as half-adjust is in use

•Extender of H (half adjust) required for rounding– There are other extenders which will be covered in later units

D a S 7 2 D b S 7 5 Inz(1.79766) D c S 5I 0 Inz(750) D d S 5 3 Inz(2.101)

a = b + c; // a = 751.79 a = b + d; // a = 3.89 Eval(H) a = b + d; // a = 3.90

Page 28: Application Development on Power System (IBM  i )

Simple Arithmetic Expressions (2 of 3)

•Arithmetic Expression Rules– Operands and result field must be numeric– Operators may be + (add), - (subtract), * (multiply), / (divide) or

** (exponentiation)– Parentheses should be used to

• ensure components are calculated in the correct sequence• Ensure accurate results• Remove ambiguity from an expression

– Numeric overflow or division by zero will cause a run time error• Result fields must be large enough to hold the calculated result of the

expression– Such errors can be trapped through the use of the MONITOR

op-code which will be covered in later units

Eval(H) Pay = (Rate*39) + ((Hours-39)*(Rate*1.5));

Page 29: Application Development on Power System (IBM  i )

Simple Arithmetic Expressions (3 of 3)

•Components are calculated in the following sequence– Parentheses– Exponentiation– Multiply and Divide– Add and Subtract

•In this example, what is the value of Result?

D x S 5I 0 Inz(1) D y S 5I 0 Inz(2) D a S 5I 0 Inz(3) D b S 5I 0 Inz(4) D c S 5I 0 Inz(5) D Result S 5I 0 /Free Result = a + b * c ** (x*y);

Page 30: Application Development on Power System (IBM  i )

Simple Character Expressions (1 of 2)

•Set the value of a character field equal to the result of a character expression•Based on an EVAL or an EVALR operation

– EVAL is assumed if no op-code is coded– EVAL means the result of the expression will be

left justified– EVALR means the result of the expression will be

right justified– The “+” operator is used for concatenation

D PhoneNo S 13 D AreaCode S 3 Inz('1') D Exchange S 3 Inz('234') D Suffix S 4 Inz('5678') /Free PhoneNo = '(' + AreaCode + ') ' + Exchange + '-' + Suffix; // PhoneNo = (1 ) 234-5678

Page 31: Application Development on Power System (IBM  i )

Simple Character Expressions (2 of 2)

•Character Expression Rules– Operands and result field must be character– Operator may be + (concatenate)– Result field may be smaller than result of expression

• Result is justified depending on use of EVAL or EVALR

– If result field is larger it will be padded with leading (EVALR) or trailing (EVAL) blanks

D Small S 6 D Char1 S 4 Inz('AAAA') D Char2 S 4 Inz('BBBB') /Free Small = Char1 + Char2; // Small = 'AAAABB' EvalR Small = Char1 + Char2; // Small = 'AABBBB'

Page 32: Application Development on Power System (IBM  i )

The DSPLY Operation•DSPLY { message { output-option { response} } }

– Can display up to 52 characters of text• This limit includes the length of any response field involved• Can display character or numeric field or literal

– But numeric display is primitive– Allows for the entry of a single response field

• May be character or numeric• If a response is used specify a single space (‘ ‘) as the output option

– Very useful when starting to program in RPG– Very useful when writing “test” programs

D Entered S 10 D Over S 10 Inz('All Done!') /Free Dsply 'This is some text'; Dsply 'Enter a value:' ' ' Entered; Dsply ('You Entered ' + Entered); Dsply Over;

Page 33: Application Development on Power System (IBM  i )

Indicators•Logical switches or Boolean fields

– on/off, true/false – set to indicate a condition

•RPG has built-in indicators– 01-99 - General Purpose RPG Indicators

• Referenced as *IN01 or *IN(01)– LR - Last Record

• Used to specify that the program is to close all files etc. on return to its caller

– There are others, however their use is not covered in this unit.•You can define your own indicators - with meaningful names

– RPG IV is far less dependent on built-in indicators– You should avoid using the built in indicators

• But they are used extensively in legacy applications• You will need to know how to use the built in indicators – more later

Page 34: Application Development on Power System (IBM  i )

Exiting a Program

•A program exits– When a RETURN operation is used– When the end of the Mainline is reached and the LR indicator is on

• It is irrelevant where in the logic the LR indicator was set on

•Recommendation:– Always end your mainline with a RETURN operation

*InLR = *On; Return;

Page 35: Application Development on Power System (IBM  i )

Structured Operation Codes

Page 36: Application Development on Power System (IBM  i )

Structured Operation Codes•RPG supports the standard structured operation codes.

– IF/ELSE/ELSEIF Condition code– FOR Loop a number of times– DOW (Do While) Loop while a condition is true – DOU (Do Until) Loop until a condition is true

•Plus a form of case statement– SELECT/WHEN/OTHER

•Every structured op-code must have a corresponding END– ENDIF, ENDFOR, ENDDO, ENDSL

• A simple END operation may be used but is not advisable

Page 37: Application Development on Power System (IBM  i )

If a <= b; Dsply 'The condition is true'; EndIf; If ((a = b) and (c = d)) OR (a > c); Dsply 'The condition is true'; EndIf; If x = y; Dsply ‘x and y are the same’; ElseIf x > y; Dsply ‘x is bigger than y’; Else; Dsply ‘x is smaller than y’; EndIf;

IF, ELSE, ELSEIF•Causes a group of statements to be executed if a conditional expression is true.

– The logical expression uses standard relational operators• = (equal), > (greater then), < (less then), >= (greater then or equal to). <=

(less then or equal to), NOT (negate), OR/ AND• Parentheses may be used for precedence

Page 38: Application Development on Power System (IBM  i )

If a <= b; Dsply 'The first condition is true'; If c = d; Dsply 'The second condition is true'; Else; Dsply 'The second condition is true'; EndIf

EndIf

Nested IFs

•IF groups may be nested one within another– Each IF requires an ENDIF.

Page 39: Application Development on Power System (IBM  i )

For x = 1 to 10; Dsply x; EndFor;

For x = 1 by 2 to 10; Dsply x; EndFor;

For x = Start By Step To Until; Dsply x; EndFor;

For x = 10 DownTo 1; Dsply x; EndFor;

FOR

FOR index { = start-value } { BY increment } { TO|DOWNTO limit }

• Processes a group of operations a number of times

Page 40: Application Development on Power System (IBM  i )

x = 5; DoW x > 0; Dsply x; x = x – 1; EndDo;

x = 0; DoW x > 0; Dsply x; x = x – 1; EndDo;

DOW (Do While)

•Processes a group of statements while a conditional expression is true

– Code within the loop must cause the conditional expression to be false or the loop will never end

Page 41: Application Development on Power System (IBM  i )

DOU (Do Until)

•Processes a group of statements until a conditional expression is true

– Code within the loop must cause the conditional expression to be false or the loop will never end

•Unlike a DOW, a DOU group is always executed at least once

x = 5; DoU x = 0; Dsply x; x = x – 1; EndDo;

x = 0; DoU x <= 0; Dsply x; x = x – 1; EndDo;

Page 42: Application Development on Power System (IBM  i )

DoW x > 0;

If x = y; Iter; EndIf;

If x = z; Leave; EndIf;

EndDo;

ITER (Iterate) and LEAVE

•ITER (Iterate) transfers control to the END statement– The conditional expression for the loop is re-tested

•LEAVE transfers control to the statement following the END statement.

Page 43: Application Development on Power System (IBM  i )

Indicators and Built-In-Functions (BIFs)

Page 44: Application Development on Power System (IBM  i )

D BadRate S N /Free If Rate < 0; BadRate = *On; Else; BadRate = *Off EndIf;

Defining and Setting Indicators•Indicators may be defined on D Specs

– Data type is N– You do not need to specify a length

• But it must be 1 if specified

•Indicators are true or false– May use figurative constants *ON and *OFF– May use character literals '1' and '0'

Page 45: Application Development on Power System (IBM  i )

D BadRate S N /Free BadRate = (Rate < 0);

If BadRate; Dsply 'The rate is negative'; EndIf;

If Not BadRate; Dsply 'The rate is positive'; EndIf;

Using Indicators

•Can be set by assigning the result of a logical expression– Since a logical expression is true (*On) or false (*Off)

•No need to specify a test value when testing an indicator – Since an indicator is true or false

•Use the NOT operator to test for an indicator being false

Page 46: Application Development on Power System (IBM  i )

*In30 = *In31 or *In32; If Not *In30; *In51 = *On; *In52 = *Off; EndIf;

RPG’s Built-In Indicators

•Used extensively in legacy applications– Dependent on comments or standards to know what they

mean•The built-in indicators can be referred to as fields

– The compiler maintains 99 one byte alpha fields which exactly reflect the settings of the 99 general purpose indicators.

– They are called *IN01 to *IN99. – The field contains a "1" for On and a '0' for Off. – There is also a compiler maintained array of 99 elements called *IN

which fulfils the same function.•e.g. Indicator 55 is *IN55 is *IN(55)

Page 47: Application Development on Power System (IBM  i )

Built-In Functions (BIFs)

•BIFs are one of the most versatile features of RPG– As of V5R4 there are 70 BIFs available

•BIFs are commonly used in expressions– They return a value– BIFs may also be used in other places

• Such as with keywords on the D specs

•We will cover some of the more commonly used in the next few charts

Page 48: Application Development on Power System (IBM  i )

D FirstName S 15 Inz('Paul') D LastName S 15 Inz('Tuohy') D PrintName S 25

PrintName = FirstName + LastName; // PrintName = 'Paul Tuohy '

PrintName = %TrimR(FirstName) + ' ' + LastName; // PrintName = 'Paul Tuohy '

%TRIM – Trim Blanks

•%TRIM( string ) %TRIML( string ) %TRIMR( string )– %TRIM strips leading and trailing blanks from character fields– %TRIML strips leading blanks only– %TRIMR strips trailing blanks only

Page 49: Application Development on Power System (IBM  i )

D InpString 20 Inz('Dr. Doolittle') D Position 3 0

Position = %Scan('tt‘ : InpString);

// Position = 10

Position = %Scan('D‘ : InpString : 2);

// Position = 5

%SCAN – Search for Character String

•%SCAN( needle : haystack { : start } )– Returns the position of the first occurrence of the string needle in

string haystack starting the search at position start• The optional start parameter is useful when searching a string which may

contain multiple instances of the target string

– Returns zero (0) if no match was found

Page 50: Application Development on Power System (IBM  i )

D NameField S 20 INZ ('Paul Tuohy ') D FirstName S 10 D LastName S 10 D x S 5I 0

x = %Scan(' ' : NameField); FirstName = %SubSt(NameField :1 : x-1); // FirstName = 'Paul '

LastName = %SubSt(NameField : X+1); // LastName = 'Tuohy ' %SubSt(NameField : X+1 : 4) = 'Huth' // NameField = 'Paul Huthy '

%SUBST – Return or Set Substring•%SUBST( basestring : start { : length } )

– Returns the substring of the basestring• If optional length not specified, the rest of the string from the start to the

end of the string is returned

– %SUBST can also be used when specifying the result field• i.e. To control which part of the field is to be changed

Page 51: Application Development on Power System (IBM  i )

D Name S 20 INZ ('Paul Tuohy ') D Reverse S 20 D x S 5I 0

x = %SCAN(' ' : Name); Reverse = %TrimR(%Subst(Name : x+1)) + ', ' + %SUBST(Name : 1 : x-1); // Reverse = 'Tuohy, Paul '

Reverse = %TrimR(%SUBST(Name : %Scan(' ' : Name) + 1) ) + ', ' + %SUBST(Name: 1 : %Scan(' ' : Name)- 1);

Putting it All Together

•Combining %TRIM, %SUBST, %SCAN– Second example combines the operations into a single statement but

is more difficult to read

Page 52: Application Development on Power System (IBM  i )

D Text S 50a

Text = 'Your balance of ' + %Char( Balance ) + ' is now seriously overdue‘;

Numeric Conversion and Editing BIFs

•%CHAR is the most basic editing BIF– It returns a character field containing the edited value of a numeric

field or expression– Leading zeros are removed and a decimal point inserted if required– Negative values will be preceded by a minus sign

•%EDITC and %EDITW provide more sophisticated editing– They are based on the Edit codes (%EDITC) and Edit words (%EDITW)

used when defining output on O-specs

Page 53: Application Development on Power System (IBM  i )

Using Files in RPG

Page 54: Application Development on Power System (IBM  i )

Terminology•File (Database) Hierarchy

– File (Table)• Collection of data about a given kind of entity or object• Set of data elements (values) that is organized using a model of

horizontal rows and vertical columns.

– Record (Row)• Represents a set of related data about one specific instance of the

entity• Every record in the table has the same structure

– Field (Column)• An element of data in the record.

Page 55: Application Development on Power System (IBM  i )

Creating a File from DDS

Data

Access Path

Format

Access Path

Format

DDS SourceQDDSSRC

FormatsFormats

CRTPFCRTLF

CRTDSPFCRTPRTF

Display FilePrint File

Logical FilePhysical File

Page 56: Application Development on Power System (IBM  i )

Files in RPG•An RPG program processes a *FILE object

– Opens a file– Gets records from a file– Puts records to a file– Closes a file

•*FILE objects may be for – disk (Physical - PF, or Logical - LF)– display (DSPF)– printer (PRTF)– All of these are *FILE objects with a different attribute

•All *FILE objects may be defined using traditional Data Description Specifications (DDS)

– SQL may also be used to define disk files•Files are normally externally described for RPG programs

Page 57: Application Development on Power System (IBM  i )

.....A..........T.Name++++++RLen++TDpB......Functions++++++++++++++++++ A REF(FLDREF) A R CUSTREC TEXT('Customer Record')

A CCODE R

File

Record

Field

Data Description Specifications (DDS)•DDS format is similar to RPG

– It is a “fixed” form– Column Based

•DDS is divided into three levels:– File Level identifies information about the file

• Introduced by blank Type (T) and Name entries – Record Level identifies information about a record format

• Introduced by the “R” prior to the name – Field Level identifies information about a field.

• Introduced by a blank Type (T) entry and a non-blank Name•Keywords apply to the level where they appear

Page 58: Application Development on Power System (IBM  i )

Data Description Specifications•The meaning of the headings are:

– Type of entry (T)• Record (R), Field (blank), Key (K)

– Name. The name of the record, field, or key field– Reference field (R)

• R if referencing another field (more later)– Length (Len++). Length of the field– Data Type (T). Data type of the field– Decimal Positions (Dp). Decimal precision for a numeric field– Usage (B).

• Input (I), Output (O), Both (B – default for database files)– Functions. Used to supply keywords to refine the definition

• The real strength of DDS

A..........T.Name++++++RLen++TDpB......Functions++++++++++++++++++

Page 59: Application Development on Power System (IBM  i )

DDS for a Physical File

•This is the DDS for a simple Physical File name EMPLOYEE– It defines a record format named EMPLOYEER– It defines the fields EMPID, NAME, BIRTH and JOINED

• The TEXT, COLHDG and EDTWRD keywords do not affect the data • They are used to provide default headings etc. when the data is

displayed.....A..........T.Name++++++RLen++TDpB......Functions++++++++++++++++++ A R EMPLOYEER A EMPID 5 0 TEXT('Employee Id.') A COLHDG('Employee' ' Id.') A NAME 25 COLHDG('Name') A BIRTH 8 0 TEXT('Date of Birth') A COLHDG('Date of' ' Birth') A EDTWRD(' 0- - ') A JOINED 8 0 TEXT('Date Joined') A COLHDG(' Date' 'Joined') A EDTWRD(' 0- - ')

Page 60: Application Development on Power System (IBM  i )

DDS for Logical Files•This is the DDS for a simple Logical File named EMPLOYEE1

– This file is sequenced by the Employee Id (EMPID)

.....A..........T.Name++++++.Len++TDpB......Functions++++++++ A R EMPLOYEER2 PFILE(EMPLOYEE) A EMPID A NAME A BIRTH A K BIRTH DESCEND A K EMPID A S BIRTH COMP(GT 19800101)

.....A..........T.Name++++++.Len++TDpB......Functions++++++ A R EMPLOYEER PFILE(EMPLOYEE) A K EMPID

This is a more complex example named EMPLOYEE2 It is sequenced on Date of birth (BIRTH) and Employee Id (EMPID) Only the fields EMPID, NAME and BIRTH are included

Page 61: Application Development on Power System (IBM  i )

DDS Keywords•Keywords are essential to the use of DDS

– Some keywords are common to all file types• e.g. TEXT, COLHDG

– Some keywords may be used at all levels (File, Record and Field) • e.g. SPACEA, SPACEB

– Some keywords are specific to file types• e.g. DSPATR for Display Files

•By externally defining a file, a program is protected from needing to know about device specific information

•For a complete description of the DDS coding rules and keywords, please refer to the Data Description Specification Reference manual.

Page 62: Application Development on Power System (IBM  i )

Additional DDS columns for DSPF and PRTF

•Additional columns are used for Display and Print files– i.e. PRTF and DSPF

•Conditioning indicators– Control the inclusion of a field or keyword(s)

•Field Usage (B)– For Print files - Output (O – Default)– For Display files - Input (I), Output (O), Both (B), Hidden (H)

•Lin. – The line number

•Pos. – The column starting position

.....A..........T.Name++++++RLen++TDpB......Functions+++++++++++++++++

.....AAN01N02N03T.Name++++++RLen++TDpBLinPosFunctions+++++++++++++++++

Page 63: Application Development on Power System (IBM  i )

.....AAN01N02N03T.Name++++++RLen++TDpBLinPosFunctions+++++++++++++++++ A R HEAD SKIPB(3) A 100DATE EDTCDE(Y) A 120PAGNBR EDTCDE(Z) A SPACEA(1) A 1'A/c Code' A 10'Name' A 41'Address' A 85'Balance' A 95'Department' A 117'Classification'

A R DETL SPACEB(2) A CCODE 6 2

Example - DDS for a Print File (PRTF)•Keywords specific to print files

– SKIPx and SPACEx keywords control where the line is printed• x = B for Before printing and A for After printing

•Len entry supplies start position for fields and literals

Page 64: Application Development on Power System (IBM  i )

.....AAN01N02N03T.Name++++++RLen++TDpBLinPosFunctions+++++++++++++++++ A DSPSIZ(24 80 *DS3) A CA03(03 'Exit') A R FORMAT1 A 1 24'Maintain Customer Master' A 3 3'Customer Code :' A CCODE 6 B 3 20 A 31 COLOR(RED)

Example - DDS for a Display File (DSPF)•Differences are:

•Keywords specific to DSPF– DSPSIZ and CA03

•Specification of both the row and column for a field or literal

Page 65: Application Development on Power System (IBM  i )

Creating Files

•Create the DDS source

•Source members may be created/maintained using:– An editor– CODE Designer for Display and Print Files– One of the older design tools

• Screen Design Aid (SDA) for Display Files• Report Layout Utility (RLU) for Print Files

•Then create the file object using the appropriate command– CRTPF for a Physical file– CRTLF for a logical– CRTDSPF for a Display file– And CRTPRTF for a Print file– There are many other CRTxxx commands for creating other file types

Page 66: Application Development on Power System (IBM  i )

Field Reference File

•A Field Reference File is just another file– Contains one record format– Contains the definition of ALL fields in the application

• Usually listed alphabetically– Never contains actual data

• Although there is no rule that says you cannot use a conventional file as a Field Reference File

•Sometimes referred to as a Data Dictionary

Page 67: Application Development on Power System (IBM  i )

DDS for a Physical File using a Field Reference File

•This is an alternative DDS definition for the EMPLOYEE file– In this version all columns are specified by referencing the master

definitions in a file named FIELDREF– Note the R in the Reference column for the fields

• It tells the DDS compiler to get the field definition from FIELDREF

.....A..........T.Name++++++RLen++TDpB......Functions++++++ A REF(FIELDREF) A R EMPLOYEER A EMPID R A NAME R A BIRTH R A JOINED R

Page 68: Application Development on Power System (IBM  i )

Field Reference Files and External Definitions

Field Reference Physical

Logical

Print

Display

RPGCompiler

Page 69: Application Development on Power System (IBM  i )

.....FFilename++IPEASFRLen+LKLen+AIDevice+.Keywords+++++++++++++++++++++ FCUSTMR0 UF A E K DISK USROPN

FREPORT O E PRINTER OFLIND(*IN96)

FSCREEN CF E WORKSTN

F Spec (File) (1 of 2)•F Specs identify the files that will be used by the program

– Each file requires an F spec.•The main points to note are:

– File Name• Note the 10 character restriction

– File Type (I) • I = Input, O = Output, U = Update, C = Combined (WORKSTN Files

only)– File Designation (P)

• Blank = Output• F = Full Procedural (for Types I, U and C)• Other types not commonly used in modern RPG programming (see

notes)

Page 70: Application Development on Power System (IBM  i )

F Spec (File) (2 of 2)– Record Addition (A)

• Disk Files Only• Must be specified as A if records are to be added to the file

– Format (F) • Specify as E if file is Externally Described

– Record Address Type (Heading A - just before the Device entry) • Disk Files Only• If left blank file will be read in physical • Specify K if Keyed access is to be used

– Device• DISK, PRINTER, WORKSTN

– Keywords• “Extend” the definition of how the file is used in the program

.....FFilename++IPEASFRLen+LKLen+AIDevice+.Keywords+++++++++++++++++++++ FCUSTMR0 UF A E K DISK USROPN

FREPORT O E PRINTER OFLIND(*IN96)

FSCREEN CF E WORKSTN

Page 71: Application Development on Power System (IBM  i )

External Definitions

•An RPG program requires an F spec for each file it will use•The example below shows the F specs for four files

– Each of these files is externally described

•Compiler will search the library list to locate the file– It then generates all required record formats and field definitions– We will see an example of the generated field definitions later

.....FFilename++IPEASFRLen+LKLen+AIDevice+.Keywords+++++++++++++++++++++ FCust IF E K Disk FAddr IF E K Disk FList O E Printer OflInd(OverFlow)

Page 72: Application Development on Power System (IBM  i )

15 FCust IF E K Disk *------------------------------------------------------------- * RPG name External name * File name. . . . . . . . . : CUST RPGIVLAB/CUST * Record format(s) . . . . . : CUSTR CUSTR *-------------------------------------------------------------16 FAddr IF E K Disk *------------------------------------------------------------- * RPG name External name * File name. . . . . . . . . : ADDR RPGIVLAB/ADDR * Record format(s) . . . . . : ADDRR ADDRR *-------------------------------------------------------------17 FList O E Printer OflInd(OverFlow) *-------------------------------------------------------------- * RPG name External name * File name. . . . . . . . . : LIST RPGIVLAB/LIST * Record format(s) . . . . . : HEAD HEAD * DETL DETL * FOOTR FOOTR

Compiler picks up the External Definition

External definitions retrieved are shown in the compile listing

Page 73: Application Development on Power System (IBM  i )

26=ICUSTR *----------------------------------------------------- * RPG record format . . . . : CUSTR * External format . . . . . : CUSTR : RPGIVLAB/CUST * Format text . . . . . . . : Customer Master *----------------------------------------------------- 27=I A 1 6 CCODE28=I P 7 11 2CBAL 29=I A 12 14 CDEPT30=I A 15 17 CCLAS

Example of automatically defined input fields

•For the file CUSTR the following fields are defined– CUSNO is a 6 character field.– CBAL is a 9 digit numeric field with 2 decimal positions– CDEPT is a 3 character field.– CCLAS is a 3 character field.

Page 74: Application Development on Power System (IBM  i )

D LastCust S Like(CCode)

LIKE Revisited

•The LIKE keyword simplifies the definition of work fields– A work field can be defined as being LIKE an Externally Defined field– If the external field’s definition changes, then on recompile, the work

field will also be redefined

Page 75: Application Development on Power System (IBM  i )

"PUT" and "GET" Operations•A program “PUTs” a record to a file

•A program “GETs” a record from a file• •All PUTs and GETs are record based

– i.e. A program will PUT or GET a single record at a time•There are many PUT operation codes

– WRITE, UPDATE, DELETE, EXFMT, EXCEPT•There are many GET operation codes

– CHAIN, EXFMT, READ, READE, READP, READPE, READC•Notice that EXFMT combines both a PUT and a GET

– First it performs a WRITE to the display file– Then performs a READ once the user has provided input

Page 76: Application Development on Power System (IBM  i )

A “PUT” Operation

1234

Paul

Y

1234 Paul

Y

1201MaryY

1234PaulY

1202FredN

1204MikeY1203JoanN

Write Record;

Page 77: Application Development on Power System (IBM  i )

A “GET” Operation

1201MaryY

1234PaulY

1202FredN

1204MikeY1203JoanN

Chain '1234' Record;

1234PaulY

1234PaulY

Page 78: Application Development on Power System (IBM  i )

26=ICUSTR *----------------------------------------------------- * RPG record format . . . . : CUSTR * External format . . . . . : CUSTR : RPGIVLAB/CUST * Format text . . . . . . . : Customer Master *----------------------------------------------------- 27=I A 1 6 CCODE28=I P 7 11 2CBAL 29=I A 12 14 CDEPT30=I A 15 17 CCLAS

External Definitions for a “GET”

•On a “GET” operation to CUST– Copy positions 1 to 6 to the CCODE field.– Copy positions 7 to 11 to the CBAL field.– Copy positions 12 to 14 to the CDEPT field– Copy positions 15 to 17 to the CCLAS field

Page 79: Application Development on Power System (IBM  i )

FCust IF E K Disk FDept IF E Disk /Free Chain KeyFld Cust; If %Found(Cust); Chain 25 Dept; EndIf;

CHAIN search-key file-or-record {data-structure}

•CHAIN randomly retrieves a record by key– K must have been specified for Record Address Type on the F spec

•Or by relative record number

•Use %FOUND( ) to determine whether a record was retrieved– %FOUND( ) must specify the file name

• Even if a record format name was used on the CHAIN

Page 80: Application Development on Power System (IBM  i )

READ name {data-structure}

•READ reads the next record from a file– The name entry can specify a file or record format

•Use the %EOF( ) BIF to determine when end of file is reached– i.e. There are no more records to read

•Note the “K” entry on the F spec– This ensures that the file is processed in key sequence– Without it the file would be processed in physical sequence

FCust IF E K Disk /Free Read Cust; If Not %EOF(Cust); // Process record EndIf;

Page 81: Application Development on Power System (IBM  i )

FCust IF E K Disk /Free Read Cust; DoW Not %EOF(Cust); // Process record Read Cust; EndDo;

READ All Records

•Use a DOW loop to READ all records from a file– READ the first record from the file– DOW loop condition on Not %EOF– Last statement of loop reads next record

1201MaryY

1234PaulY

1202FredN

1204MikeY1203JoanN

1234PaulY

Page 82: Application Development on Power System (IBM  i )

WRITE name {data-structure}

•Writes a record of the specified format to the file

•WRITE is used to: – Add records to Disk files – Display formats on Workstation files– Print records on Printer files.

•For externally described files record format must be specified

FReport O E Printer OflInd(OverFlow) /Free Write Detail;

Page 83: Application Development on Power System (IBM  i )

FReport O E Printer OflInd(OverFlow) /Free ... Write Detail; If OverFlow; Write Header; OverFlow = *Off; EndIf;

Page Overflow•A means of determining when to print page headings

– A print file has an overflow line– F spec keyword OFLIND associates an overflow indicator with the

file– Indicator is set when overflow line is passed– Program logic must set off the overflow indicator

Page 84: Application Development on Power System (IBM  i )

Who Knew You Could Do That with RPG IV?

A Sorcerer's Guide to System Access and More

SG24-5402

International Technical Support OrganizationRochester, Minnesota

Reference materials

•Two RPG Manuals in the Information Center:– ILE RPG Reference– ILE RPG Programmers Guide

•ILE RPG Reference available as online help in WDSC•The RPG Redbook

– "Who Knew You Could Do That With RPG IV? A Sorcerer's Guide to System Access and More" (SG24-5402)

– Go to http://www.redbooks.ibm.com/

Page 85: Application Development on Power System (IBM  i )

Questions & Answers?