Dot Net Fluke: Getting by on C# for iSeries RPG Developers

Useful tutorials on C# and .NET for RPG iSeries AS/400 developers. Brought to you from the folks at AranRock Consulting

1/26/08

RPG Subroutine = C# Method?

Someone asked me the other day if RPG subroutines are the same as C# methods.
The answer is yes - like C# static methods but RPG Procedures are even more similar to C# static methods.
The reason being is that while C# methods are discrete named blocks of code you can call from within a program (C# Class) - just like an RPG Subroutine; C# methods allow parameters in the call - just like RPG procedures do. Methods have lots of other features that I’ll get in to but first lets draw comparisons.
Here’s an example:
Both applications read a table called ‘People’ and print out the name of each person on the console.
They both call a subroutine/method called Get_People that takes no parameters from the main block of code.

RPG
Fpeople IF E K DISK
/FREE
exsr Get_People ;
*inlr = *on;

BegSr Get_People;
read People ;
dow not %eof ;
Dsply name ;
Read People
Enddo;
Endsr;


C#


using System;
using System.IO;
namespace ConsoleApplication1
{
class ProgramClass
{
static void Main() // Main block of code 'Main' must be in the class
{
get_People();
}
static public void get_People( )
{
using (FileStream fileStream = new FileStream(@"C:\csharp\people.txt",
FileMode.Open,
FileAccess.Read,
FileShare.None))
{
using (StreamReader streamReader = new StreamReader(fileStream))
{
string text = streamReader.ReadLine();
while (text != null)
{
Console.WriteLine(text);
text = streamReader.ReadLine();
}
}
}
Console.ReadLine(); // Pause the screen
}
}
}



As you can see, RPG is easier to read and less verbose than its C# counterpart. To be fair DB2 is part of the iSeries operating system so all the file handling is already part of the DB.

Remember these are Static methods shown in C#. A static method in C# is where there is only one instance of the method. Believe it or not you can multiple instances of a method in C#. These are called instance methods and are used more often than static methods. I'll get into the difference but the purpose of this post is to show some similarity between RPG and C# first.

Labels: , , , , , ,

1/18/08

Comparing RPG code to C# : The For Loop

There are similarities between free format RPGIV and C#. In the example below I show a small program that accomplishes the same task in both languages. The task is to find the first blank character in a string from the end to the beginning. I'm well aware there is a single method available for this on String in C# but the purpose here is to show the similarities.
RPG is below:


















Now C#:
























You can see some basic similarities:
  • Statements end with a ';' ,

  • the For loop is similar.

  • 'Leave' gets you out of an RPG loop while 'Break' exits a C# loop.

  • Assigning values is the same in both.

  • Declaring variables in RPGIV requires both type and how many characters (you can declare varying length variables but do define an initial length). To define a variable you must put values in fixed positions in a special kind of statement block called 'Definition Specifications' or D-specs. In C# you simply declare the type. The type of the index 'i' is denoted by a zero in the decimal placess position.

  • C# requires a 'Main' method. RPG just executes from the first executable line.

  • C# variables are local by default. I can't access that 'i' variable outside of that For loop - the program wouldn't even compile. RPG variables are global unless used in procedures.


  • C# requires a class definition, namespace and you define what other namespaces in .Net you want to refer to in your program with the 'Using' statements. The using just means you don't have to refer to the full name like 'System.Console.Readline()'.


  • C# doesn't need 'EndFor' or 'EndIf'. Coding is accomplished in blocks between curly braces '{' and '}'.


  • The biggest difference is that C# strings and objects have a multitude of methods and properties on the string itself - not part of the language. RPGIV is pretty good at string manipulation too but can never approach the flexibility of C# as the RPG designers would have to create a new keyword when it needs to perform a function on a string that it doesn't already have. In C# there are only a handful of keywords - most actions are accmplished by methods on the objects themselves. For instance in the above example you access the length of a string by examining its property. e.g. 'field.length' returns an integer value whereas in RPG I chose to use the built-in-function %len to do the same thing.
    To find the first non-blank in a string starting from the end you can use field.IndexofLast(' ') . RPGers note how the methods and properties are on the string 'field' which I defined. As soon as you define a variable it creates a copy of the string object so you have full access to a huge amount of manipulation techniques. Adding new methods and properties to strings and other types isn't a major change in the language.
RPG Output below





























C# Output:

Labels: , , , , ,

1/17/08

Datasets are what?

Datasets are a layer between the actual database and your application. When you need to connect to different tables and databases, datasets can help by separating all the connecting to your different data stores and working on the actual data. The analogy with RPG is that datasets are data structures. If you read a table in an RPG program and the put that data into a data structure, updated the fields in that data structure then moved the data structure back to your table then the dataset is the data structure and the bit that moves data between the table is the data adapter.
You don't need all this of course. It's part of .NET, specifically ADO.NET - that part of the framework that's supposed to make it easier to build complex data access application. The stuff that manages and brings it in and out of your application . Kind of like the way the RPG cycle (remember that?) reads in a table automatically. You can just read and write from any database without using datasets and adapters. It's just much easier and less error prone when you use data sets and adapters to manage your data. The IDE automatically creates these when you drop a table onto a form.

When you look at the code to fill a dataset from an adapter you can see there's not much too it. The key term here is Dataset. Datasets are completely separated from the database. Think of them as a data structure where you load data from your table to. The data structure knows nothing of the table where it got the data. It's just used to hold the data in memory. All queries, updates etc. are done to the Dataset not to the data store. We let the dataadapter take care of fetching data to and from the actual table.


// build a command object and prepare an SQL statement so that you can look at your table
SqlCommand buildData = conn.CreateCommand();

cmd.CommandText = "Select * from Orders where OrdQty >100";
// Build the Data Adapater - this fills a data set
SqlDataAdapter dataAdapter = new SqlDataAdapter(buildData);

// Now create the data set. The data structure which contains the data retrieved by the data adapter
DataSet orderDataSet = new DataSet();

// Populate the dataset with the Data Adapter
dataAdapter.Fill(dataSet);

Labels: , , , , ,

What are all those adapters and datasets when I create a form?

When you create a form in the Visual Studio IDE and drop a table on it, a bunch of components seem to have glued themselves to the bottom of the form.



Here's what they mean:






1/15/08

Where to get the iSeries ADO.NET data provider

The iSeries .NET data provider is the native data provider that allows you to access iSeries data and programs using .NET in a managed way.

This is a .dll (IBM.Data.DB2.iSeries.dll ) that you add in as a reference when creating .Net apps to connect to the iSeries

Once added in you have access to all the classes and methods that simplify writing applications in .Net to leverage iSeries data in the db2 database

The dll is part of iSerices Access for windows which you can download for free (when you select the technology preview). Make sure you check 'Selective Setup' and include the Data and Programmer's toolkit so you get all the data access drivers, help and tools.


  1. Download iSeries Access from http://www-03.ibm.com/systems/i/software/access/windows/downloads.html
    Select the technology preview version. You'll have do the register rigmarole.
    If the link doesn't work, google 'iSeries Access windows' to find the latest location.

  2. Install iSeries Access making sure that you select 'custom install' to include the programmers toolkit (it comes in handy as it has examples etc.) . Once you have installed iSeries Access you will find the dll in C:\Program Files\IBM\Client Access\IBM.Data.DB2.iSeries.dll

  3. In Visual Studio, open up your project. Click on the Solution Explorer, then references. Right click references and select 'Add Reference'. A dialog box appears. Click 'Browse'. Add in the dll from the location above.

  4. Add the namespace '
    using IBM.Data.DB2.iSeries;' to your code

  5. Start using the iSeries classes! The iDB2Command is what you use to run queries, IDB2Connection to create a connection string to your iSeries db, iDB2DataAdapter gives you a cache to both connect, retrieve and update a set of data.

With the native .NET provider you have support for:

  • SQL (INSERT, UPDATE, DELETE, SELECT)
  • Stored procedure support
  • Commitment control
  • Connection pooling
  • SQL naming,Unicode, Threads and multiple databases (IASPs)

To call iSeries programs use a stored procedure.

Labels: , , , , , ,

1/13/08

Different ways to access iSeries data

Remember, you have 4 main methods to access DB2 for iSeries from .NET programs:
  1. The ADO.NET managed provider for iSeries Access for Windows, IBM.Data.DB2.iSeries. This is probably your best bet for iSeries data connectivity. Get info on it here
    and....
  2. ODBC: The Microsoft-supplied ODBC bridge provider using the iSeries Access forWindows ODBC driver for underlying database connectivity. Microsoft.Data.Odbc
  3. OLE DB: The Microsoft-supplied OLEDB bridge provider using one of the iSeries Accessfor Windows OLE DB providers for underlying database connectivity. System.Data.OleDb This is an unmanaged method.
  4. The DB2 for Linux, UNIX, and Windows (LUW) managed provider implemented by IBM software group.
Managed vs. Unmanaged

The managed provider is superior in terms of controlling actions to the DB from within your application. Managed means managed by .net - the drivers to access the iSeries are compiled into a .Net assembly. Unmanaged means that it is outside the .Net assembly - an .exe for example.
When you use OLE DB you are using an unmanaged provider so there is an extra step that has to occur from .net to the iSeries such as a bridge between the two. You should experience better performance when using the .Net managed provider.

Here's an overview of the IBM .net managed provider (from IBM)

I highly recommend reading the IBM redbook ' Integrating DB2 Universal Database for iSeries with Microsoft ADO .NET' from which the above is summarized. 'You can download it at http://www.redbooks.ibm.com/abstracts/sg246440.html

Labels: , , , ,

1/11/08

C# for iSeries RPG programmers

There are many iSeries RPG programmers out there who are keen to get started on another programming language that matches the flexibility and scope of RPG with the added web, windows and forms simplicity available in modern IDE's.
Which language will you invest your valuable time in? Java, PHP, Visual Basic, Delphi, Ruby, C#?


Java is a good, mature candidate since it also runs on the iSeries. Ruby is open and emerging as easy to learn, productive and object oriented. Delphi (Object Pascal) has been around for donkey's. PHP is mainly used for scripting and web pages so only server partial needs. Visual Basic and C# are just variations of Microsoft's powerful .NET platform but C# programmers get paid more. For someone still on the iSeries you will want a language that has excellent connectivity to the black box. That leaves Java and C#. C# has Linq! and is far easier than Java at creating windows desktop applications but Java does run on the iSeries. So it's a toss up but my friends, Linq pushes the argument to C#.

Let's look at C#.
C# (like Java) can be hard to read, is full of abstruse concepts such as polymorphism, inheritance and encapsulation. Five lines of RPG could be one line in c# and one line in RPG could be five in c#.
It's Geeky. At first glance code will appear to operate your vacum cleaner but will just read a file and print its contents. It gives you lots of ways to accomplish the same thing. Lots.
It's not simple. It's not easy. It's a pain in the ass.
It's a great language.

I recommend that RPG developers dive in to c# despite the challenges. The best way to deal with challenges is, of course, to ignore them. Yes, run away. Start writing code c# just as you would in RPG. In other words I am advocating to begin your next language which is built specifically for object oriented (OO) development to start using it as a functional procedural language. Write short little programs to display iSeries data in grids for the web, for windows, for handhelds. Think of c# as RPG for the desktop.
You may well be persecuted by OO idealogues who are (bitterly) passionate about the 'right ' way to code. They like 'coding'. RPG programmers like 'going home at 5'. They really couldn't give a shite. RPG developers are for the most part business oriented types who create software to solve real life business situations.

As time passes you'll find that you'll write more complicated code and will need to start using object oriented principles.Keep your eyes on this blog for step by step instructions for writing c# programs for use against the iSeries data and legacy applications and together we will work up to object oriented development beginning with procedural C# - let's call it RPG#.

Labels: , , , ,

1/10/08

Using .NET Linq with the DB2 - release date?

Though IBM has pledged to provide Linq to access DB2 programmatically within C# - it doesn't exist yet. In fact, Linq to SQL only works for Microsft SQL. You can do a backdoor version by using an OLEDB linked server in SQL Server for example. IBM won't tell us when Linq can access DB2 so keep an eye out at their Developer Works site at http://www-128.ibm.com/developerworks/wikis/display/DB2/DB2+and+.NET+FAQ

Labels: , , , , , ,

1/6/08

Head First C# Book - First impressions


Having read through several C# books - O'Reilly Learning C#, C# for Dummies , Microsoft's cyptic MCTS book etc. I found this new book a refreshing read. C# is just not something you can read about and just do - it required a lot of practice. This book is geared to doing as you are reading so is much more of a workbook than a text book. So far so good. Any other readers comments?

Labels: , , , , ,