 | Level: Introductory Ray Else (raymonde@us.ibm.com), Support Engineer, IBM
23 Jun 2005 Learn to use ASP.NET with RedBack® objects to access your UniData® or UniVerse® database from the Web in a simple way, with examples in VB and C#.
Introduction
ASP.NET is Microsoft's powerful new Web middleware platform that supports both VB.NET and C#.NET languages. This article shows how you can use ASP.NET to access your UniData or UniVerse database in a simple, elegant way using IBM’s RedBack middleware.
Why use RedBack and RedBack objects with ASP.NET? Well, not only has RedBack been a solid performer now for over 6 years, with thousands of installations all over the world, it also allows you to access UniData or UniVerse without having to write in any other language except ASP.NET/VB or C# in the middle tier and Basic on the database side. And RedBack objects are virtual and reusable -- if tomorrow you decide to use PHP or JSP or XML/Soap instead of, or in addition to, ASP.NET, you won't have to change your RedBack objects at all.
RedBack objects
The RedBack Designer tool allows you to design RedBack objects with properties and methods. The properties are typically data place holders (like variables), whereas the methods are typically pointers to UniBasic subroutines. You can use some of the principal RedBack objects as templates for creating your own objects, including:
- SLRBO -- The fastest RedBack object, this very flexible, stateless object is good for reading single records (or multiple records delimited in some way), and for writing data to one or more files. It requires you to write the methods/subroutines that do the reading or writing. You should use this object whenever possible in your application, as it has the lightest load on a system.
- uQuery -- A stateful report object which, given a U2 (Pick flavor) select statement, returns a recordset. You don't typically write Basic code with this object. When you use uQuery in a stateful way, you can keep a handle to the object in the middleware, and use it to page through the data on multiple page hits without redoing the select.
RedBack setup
The RedBack documentation covers setup on the database server and on the Web server (see Resources). As part of that setup, a test database called rbexamples is installed, complete with data and RedBack objects for accessing that data. The sample code shown later in this article will use those objects to access rbexamples.
Because we are going to be making calls from ASP.NET to RedBack objects from Windows,
we will use the RedBack ADO/OLEDB component RedPages.dll on the Web server, along with
the rgw.ini file, to access the rbexamples database. Alternatively, you could use XML/Soap requests, but this article will not cover those.
- RedPages.dll -- This DLL contains the RedObject class that enables you to use RedBack objects. The example project includes a library reference to this in Visual Studio.
- rgw.ini -- This file specifies the database and server of the RedBack Responder. Place this file in the root document directory (wwwroot) or in the WINDOWS or WINNT directory. The file contains the database name, followed by a space, followed by the database server machine name or IP address, a colon, and the port number where the RedBack Responder is listening for requests to this database. For example:
rbexamples my2000:8444
Setting up the project in Visual Studio.Net
RedPages.dll is a COM object, and currently supports ADO/OLEDB (which you can call from ASP.NET). You need to set up Visual Studio.NET to use an ADO.NET wrapper in order to use RedObject or RedField, or to use an ADO Recordset (such as returned from a uQuery object).
To set up an ASP.NET project that uses RedBack:
- Open Visual Studio.NET and select New Project.
- Enter a Location and Name for your Visual Basic/ASP.NET Web Application,
and click OK. Visual Studio.NET creates a virtual directory for your pages in IIS.
Figure 1. New project
- Create a reference for RedPages.dll in your project. To do this:
- In the solution Explorer, right-click the References item under your project, and select Add Reference. This opens the Add Reference Window.
- Select the COM tab, and scroll down to RedPages 1.0 Type Library. Double-click this choice, then click OK. In the Solution Explorer, you will see REDPAGESlib added as a reference.
Figure 2. Add IBM U2 RedPages reference
- If you want to use Microsoft's Recordset, create a reference for it. (This is necessary because Recordset is also an ADO COM object.) To do this:
- In the Solution Explorer, right-click the References item under your project, and select Add Reference. This opens the Add Reference Window.
- Select the COM tab, and scroll down to Microsoft ActiveX Data Objects Recordset 2.7 Library. Double-click this choice, then click OK. In the Solution Explorer, you will see ADOR added as a reference.
Figure 3. Optionally add Microsoft Recordset reference
 |
Sample form to display database data -- using VB.NET
The following ASP.NET/VB page, in conjunction with its code-behind page, makes a database connection, creates an object, sets a key property, calls the database read method of the RedBack object, then displays the returned properties' values.
Note: This stateless example will work with an SLRBO, an RBO, or a uObject, but not a uQuery (which returns a recordset). For more information on the differences between these objects, please refer to the RedBack documentation (see Resources).
Listing 1. Presentation page
<%@ Page Language="vb" AutoEventWireup="false" Codebehind="DisplayData1.aspx.vb"
Inherits="rb4nettrain.DisplayData1" ASPCompat="true"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
<title>DisplayData1</title>
<meta name="GENERATOR" content="Microsoft Visual Studio.NET 7.0">
<meta name="CODE_LANGUAGE" content="Visual Basic 7.0">
<meta name="vs_defaultClientScript" content="JavaScript">
<meta name="vs_targetSchema" content="http://schemas.microsoft.com/intellisense/ie5">
</HEAD>
<body>
<form id="Form1" method="post" runat="server">
<H3>DisplayData1.aspx - Sample Form to Display Database Data</H3>
<P>
<asp:Label id="Mess" runat="server"></asp:Label></P>
<P><STRONG><FONT face="Arial">Data Read with Key:
</FONT></STRONG>
<asp:Label id="Label1" runat="server"></asp:Label>
</P>
<P>
First Name:
<asp:Label id="FirstName" runat="server"></asp:Label><br>
Last Name:
<asp:Label id="LastName" runat="server"></asp:Label><br>
</P>
</form>
</body>
</HTML>
|
Listing 2. Code-behind page
Public Class DisplayData1
Inherits System.Web.UI.Page
Protected WithEvents Label1 As System.Web.UI.WebControls.Label
Protected WithEvents Label3 As System.Web.UI.WebControls.Label
Protected WithEvents Mess As System.Web.UI.WebControls.Label
Protected WithEvents FirstName As System.Web.UI.WebControls.Label
Protected WithEvents LastName As System.Web.UI.WebControls.Label
Protected WithEvents Label2 As System.Web.UI.WebControls.Label
#Region " Web Form Designer Generated Code "
'This call is required by the Web Form Designer.
<System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()
End Sub
Private Sub Page_Init(ByVal sender As System.Object, ByVal e As System.EventArgs)
Handles MyBase.Init
'CODEGEN: This method call is required by the Web Form Designer
'Do not modify it using the code editor.
InitializeComponent()
End Sub
#End Region
Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs)
Handles MyBase.Load
Dim Id As String
Dim ro As New REDPAGESLib.RedObject
Dim prop As New REDPAGESLib.RedProperty
' hardcode the Id for now
Id = "1016"
' do RedBack Database Access using pre-defined RedBack Object
Try
'Make Connection to rbexamples database
' using EmpReader object definition from Module EXMOD
' Note - Open3 in RB 4.2.6 is faster; here we use older Open2
ro.Open2("rbexamples", "EXMOD:EmpReader", "", "", "")
'Set Id into Object Property
prop = ro.Property("EmpId")
prop.Value = Id
'Call Method to Read
ro.CallMethod("DoRead")
'If RBO or SLRBO we would check some status property
' to see if Read Okay,
'if uObject we can check new_item = 1 to see if record did not exist
'Get Values from Properties and put in Text of Labels
prop = ro.Property("FirstName")
FirstName.Text = prop.Value
prop = ro.Property("LastName")
LastName.Text = prop.Value
Catch ex As Exception
'Set Message label with error message
Mess.Text = "Exception occurred: " & ex.Message
Finally
If IsReference(ro) Then
'Close Object
ro.Close()
End If
End Try
'Set Value of Id into Label Text
Label1.Text = Id
End Sub
End Class
|
Figure 4. Results in the browser
Sample form to display database data – using C#.NET
The following ASP.NET/C# page, in conjunction with its code-behind page, makes a database connection, creates an object, sets a key property, calls the database read method of the RedBack object, then displays the returned properties' values.
Note: This stateless example will work with an SLRBO, an RBO, or a uObject, but not a uQuery (which returns a recordset). For more information on the differences between these objects, please refer to the RedBack documentation (see Resources).
Listing 3. Presentation page
<%@ Page language="c#" Codebehind="CSharpData1.aspx.cs"
AutoEventWireup="false" Inherits="rb4CSharpnettrain.CSharpData1" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
<HTML>
<HEAD>
<title>CSharpData1</title>
<meta name="GENERATOR" Content="Microsoft Visual Studio 7.0">
<meta name="CODE_LANGUAGE" Content="C#">
<meta name="vs_defaultClientScript" content="JavaScript">
<meta name="vs_targetSchema"
content="http://schemas.microsoft.com/intellisense/ie5">
</HEAD>
<body>
<form id="Form1" method="post" runat="server">
<P>CSharpData1.aspx - Shows RedBack Database Access</P>
<P>Enter Employee Id (1001 - 1020):
<asp:TextBox id="EmpId" runat="server" Width="74px">
</asp:TextBox></P>
<P>
<asp:Button id="Button1" runat="server" Text="Read">
</asp:Button></P>
<P>
<asp:Label id="Label1" runat="server"></asp:Label></P>
</form>
</body>
</HTML>
|
Listing 4. Code-behind page
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
namespace rb4CSharpnettrain
{
/// <summary>
/// Summary description for CSharpData1.
/// </summary>
public class CSharpData1 : System.Web.UI.Page
{
protected System.Web.UI.WebControls.Button Button1;
protected System.Web.UI.WebControls.TextBox EmpId;
protected System.Web.UI.WebControls.Label Label1;
private void Page_Load(object sender, System.EventArgs e)
{
if (IsPostBack) {
// do same action as button click
Button1_Click(sender,e);
}
}
#region Web Form Designer generated code
override protected void OnInit(EventArgs e)
{
//
// CODEGEN: This call is required by the ASP.NET Web Form Designer.
//
InitializeComponent();
base.OnInit(e);
}
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.Button1.Click += new System.EventHandler(this.Button1_Click);
this.Load += new System.EventHandler(this.Page_Load);
}
#endregion
private void Button1_Click(object sender, System.EventArgs e)
{
//Simple example
string firstname;
string lastname;
REDPAGESLib.RedObject myrbo = new REDPAGESLib.RedObject ();
REDPAGESLib.RedProperty myprop;
// Note - Open3 in RB 4.2.6 is faster; here we use older Open2
myrbo.Open2 ("rbexamples", "EXMOD:EmpReader","","","");
myprop = (REDPAGESLib.RedProperty)myrbo.Property ("EmpId");
myprop.Value = EmpId.Text;
myrbo.CallMethod("DoRead");
myprop = (REDPAGESLib.RedProperty)myrbo.Property ("FirstName");
firstname = myprop.Value ;
myprop = (REDPAGESLib.RedProperty)myrbo.Property ("LastName");
lastname = myprop.Value ;
Label1.Text = firstname + " " + lastname;
}
}
}
|
Figure 5. Results in the browser
Sample report using uQuery with ADO recordset -- using VB.NET
If you can gather the records required for a report using a single select statement, then the uQuery object is an ideal RedBack object to use to bring the data from the database. This object returns an ADO Recordset, which you can loop through to display the fields in each record. You could also loop through the Recordset and populate a DataTable in a DataSet, to bind to a DataGrid.
Figure 6. The Input form, shown in Visual Studio.NET
Listing 5. Presentation page
<%@ Page Language="vb" AutoEventWireup="false" Codebehind="ReportData1.aspx.vb"
Inherits="testvb.ReportData1"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
<title>ReportData1</title>
<meta content="Microsoft Visual Studio.NET 7.0" name="GENERATOR">
<meta content="Visual Basic 7.0" name="CODE_LANGUAGE">
<meta content="JavaScript" name="vs_defaultClientScript">
<meta content="http://schemas.microsoft.com/intellisense/ie5" name="vs_targetSchema">
</HEAD>
<body>
<form id="Form1" method="post" runat="server">
<H3>ReportData1.aspx - Sample Report using uQuery with ADO Recordset</H3>
<P><asp:label id="Mess" runat="server"></asp:label></P>
<P><STRONG><FONT face="Arial">Please Input Department Code (1 to 5):
<asp:textbox id="DeptId" runat="server" Width="100px"></asp:textbox>
<INPUT type="submit" value="Submit">
</FONT></STRONG>
</P>
<center>
<asp:Panel id="Panel1" runat="server" Width="453px" Height="109px"
BorderStyle="Outset" HorizontalAlign="Center">
<P>
<%
If IsPostBack Then
Icnt = CInt(ro.Property("MaxRows").Value)
%>
<B>Records Found: <%= Icnt %></B>
<TABLE cellPadding="3">
<%
For i = 1 To Icnt %>
<TR>
<TD><%= rs.Fields("EMP.ID").Value %></TD>
<TD><%= rs.Fields("FIRST.NAME").Value %></TD>
<TD><%= rs.Fields("LAST.NAME").Value %></TD>
</TR>
<%rs.MoveNext()
Next i
ro.close()
rs.close()
End If %>
</TABLE>
<P></P>
</asp:Panel></center>
</form>
</body>
</HTML>
|
Listing 6. Code-behind page
Public Class ReportData1
Inherits System.Web.UI.Page
Public Icnt, i As Integer
Public ro As New REDPAGESLib.RedObject
Public prop As New REDPAGESLib.RedProperty
Public rs As ADOR.Recordset
Protected WithEvents Label1 As System.Web.UI.WebControls.Label
Protected WithEvents Mess As System.Web.UI.WebControls.Label
Protected WithEvents DeptId As System.Web.UI.WebControls.TextBox
Protected WithEvents Panel1 As System.Web.UI.WebControls.Panel
#Region " Web Form Designer Generated Code "
'This call is required by the Web Form Designer.
<System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()
Me.ID = "Form1"
End Sub
Private Sub Page_Init(ByVal sender As System.Object, ByVal e As System.EventArgs)
Handles MyBase.Init
'CODEGEN: This method call is required by the Web Form Designer
'Do not modify it using the code editor.
InitializeComponent()
End Sub
#End Region
Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs)
Handles MyBase.Load
'Hide results panel in case we don't need to show
Panel1.Visible = False
Mess.Text = ""
If Page.IsPostBack Then
Dim ErrMsg As String
Dim DatabaseName As String
Dim Id As String
Dim i As Integer
' get Id from Form field called DeptId
Id = Trim(DeptId.Text)
If Id = "" Then
'Set Message label with validation message
Mess.Text = "Validation failed: Please enter Id"
Else
' do RedBack Database Access using pre-defined RedBack Object
Try
'Make Connection to rbexamples database using object definition
' from Module EXMOD
DatabaseName = GetDatabaseName()
' note – use Open3 in RedBack 4.2.6 as it is faster;
' here we use the older Open2
ro.Open2(DatabaseName, "EXMOD:EmployeeList", "", "", "")
'Set Id into Object Property
prop = ro.Property("select_criteria")
prop.Value = "SELECT EMPLOYEES WITH DEPT = """ & Id &
""" BY LAST.NAME BY FIRST.NAME"
'Call Method to Read
rs = ro.CallMethod("Select")
Catch ex As Exception
'Set Message label with error message
Mess.Text = "Exception occurred: " & ex.Message
End Try
'Make Panel with results visible
Panel1.Visible = True
End If
End If
End Sub
Function GetDatabaseName()
Dim DatabaseName As String
DatabaseName = "rbexamples"
Return DatabaseName
End Function
End Class
|
Figure 7. Results in the browser
Sample report using uQuery with ADO recordset -- using C#.NET
This example is the same as the VB.NET example above. Note that neither report is paging the data; to do this you could save the handle to the object in the middleware, and refresh the object while requesting the next page of data. You can find an explanation of how to do this in the official RedBack documentation, and an ASP example in the rbexamples ASP pages supplied with RedBack.
Listing 7. Presentation page
<%@ Page language="c#" Codebehind="CSharpReport1.aspx.cs" AutoEventWireup="false"
Inherits="rb4CSharpnettrain.CSharpReport1" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
<HTML>
<HEAD>
<title>CSharpReport1</title>
<meta name="GENERATOR" Content="Microsoft Visual Studio .NET 7.1">
<meta name="CODE_LANGUAGE" Content="C#">
<meta name="vs_defaultClientScript" content="JavaScript">
<meta name="vs_targetSchema" content="http://schemas.microsoft.com/intellisense/ie5">
</HEAD>
<body>
<form id="Form1" method="post" runat="server">
<H3>CSharpReport1.aspx - Sample Report using uQuery with ADO Recordset</H3>
<P><asp:label id="Mess" runat="server"></asp:label></P>
<P><STRONG><FONT face="Arial">Please Input Department Code (1 to 5):
<asp:textbox id="DeptId" runat="server" Width="100px"></asp:textbox>
<INPUT type="submit" value="Submit">
</FONT></STRONG>
</P>
<center>
<asp:Panel id="Panel1" runat="server" Width="453px" Height="109px"
BorderStyle="Outset" HorizontalAlign="Center">
<P> </P>
<%
REDPAGESLib.RedProperty myprop;
if (IsPostBack) {
myprop = (REDPAGESLib.RedProperty)ro.Property ("MaxRows");
Icnt = Convert.ToInt16(myprop.Value);
%>
<B>Records Found: <%= Icnt %></B>
<TABLE cellPadding="3">
<%
string id = "";
string fldname = "";
string fname = "";
string lname = "";
string fval = "";
for (int i = 1; i <= Icnt;i++) {
id = rs.Fields["EMP.ID"].Value.ToString();
fname = rs.Fields["FIRST.NAME"].Value.ToString();
lname = rs.Fields["LAST.NAME"].Value.ToString();
%>
<TR>
<TD><%= id %></TD>
<TD><%= fname %></TD>
<TD><%= lname %></TD>
</TR>
<% rs.MoveNext();
}
if (ro != null) { ro.Close(); }
if (rs != null) { rs.Close(); }
} %>
</TABLE>
<P> </P>
</asp:Panel></center>
</form>
</body>
</HTML>
|
Listing 8. Code-behind page
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
namespace rb4CSharpnettrain
{
/// <summary>
/// Summary description for CSharpReport1.
/// </summary>
public class CSharpReport1 : System.Web.UI.Page
{
public REDPAGESLib.RedObject ro;
public ADOR.Recordset rs;
public REDPAGESLib.RedProperty myprop;
public int Icnt;
protected System.Web.UI.WebControls.Label Mess;
protected System.Web.UI.WebControls.TextBox DeptId;
protected System.Web.UI.WebControls.Panel Panel1;
private void Page_Load(object sender, System.EventArgs e)
{
//Hide results panel in case we don't need to show
Panel1.Visible = false;
Mess.Text = "";
if (Page.IsPostBack) {
string DatabaseName;
string Id;
// get Id from Form field called DeptId
Id = (DeptId.Text).Trim();
if (Id == "") {
//Set Message label with validation message
Mess.Text = "Validation failed: Please enter Id";
} else {
// do RedBack Database Access using pre-defined RedBack Object
try {
// Make Connection to rbexamples database
// using object definition from Module EXMOD
DatabaseName = GetDatabaseName();
ro = new REDPAGESLib.RedObject ();
// note – use Open3 in RedBack 4.2.6 as it is faster;
// here we use the older Open2
ro.Open2 (DatabaseName, "EXMOD:EmployeeList","","","");
//Set Department Id into Object Property as select statement
myprop = (REDPAGESLib.RedProperty)ro.Property ("select_criteria");
myprop.Value = "SELECT EMPLOYEES WITH DEPT = \"" + Id + "\" BY LAST.NAME BY FIRST.NAME";
//Call Method to Read
rs = (ADOR.Recordset)ro.CallMethod("Select");
} catch (Exception ex) {
//Set Message label with error message
Mess.Text = "Exception occurred: " + ex.Message;
}
//Make Panel with results visible
Panel1.Visible = true;
}
}
}
private string GetDatabaseName()
{
string DatabaseName;
DatabaseName = "rbexamples";
return DatabaseName;
}
#region Web Form Designer generated code
override protected void OnInit(EventArgs e)
{
//
// CODEGEN: This call is required by the ASP.NET Web Form Designer.
//
InitializeComponent();
base.OnInit(e);
}
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.Load += new System.EventHandler(this.Page_Load);
}
#endregion
}
}
|
Figure 8. Results in the browser
Summary
The examples in this article have illustrated how to write an ASP.NET Web Application using RedBack objects to access a UniVerse or UniData database.
Resources - Getting Started with RedBack describes how to set up a RedBack server.
- The RedPages manual provides more detail about the objects used in the examples above, and about accessing RedBack from ASP.NET in general.
- To learn more about U2 and RedBack, visit the IBM U2 Web site.
About the author  | 
|  | Ray Else works for IBM U2, with seven years experience helping clients develop Web/U2 Applications using RedBack Objects. He has an M.S. in technical instruction/technical writing/film history from the University of North Texas. His undergraduate degree is in computer science from Texas A&M - Commerce. |
Rate this page
|  |