Building Web Services With C# and DB2
Building Web Services With C# and DB2
DB2
Presented by DB2 Developer Domain
http://www7b.software.ibm.com/dmdd/
Table of Contents
If you're viewing this document online, you can click any of the topics below to link directly to that section.
This sample application in this tutorial involves the JustPC.com Music Company, which
maintains a database with information about various CDs it has for sale. Through a
Web service it provides, users can search the database to retrieve various kinds of
information, including a list of artists, a list of CDs recorded by a specific artist and the
list of tracks on the CD.
All of the application code was created using Visual Studio .NET and the C#
programming language, while most of the database tasks were performed using the
DB2 Development Add-in to Visual Studio .NET.
• You are familiar with DB2 and wish to learn about how to create a C# Web service
using the new DB2 managed provider.
• You are familiar with C# and wish to see how to use the new IBM DB2 managed
provider to access a DB2 database.
• You wish to learn more about the capabilities of the new IBM DB2 Development
Add-in to Visual Studio .NET.
• You are curious to see how well a non-Microsoft database can be integrated into a
.NET application.
Tools
This tutorial relies on software from both IBM and Microsoft.
• IBM DB2, Version 8.1 provides the database facilities used by this tutorial. You can
download an evaluation copy of DB2 from:
http://www6.software.ibm.com/dl/db2udbdl/db2udbdl-p .
• You can download a beta copy of the IBM DB2 .NET Enablement package at:
http://www7b.software.ibm.com/dmdd/downloads/dotnetbeta/.
• Microsoft Visual Studio .NET (http://msdn.microsoft.com/vstudio) provides the
development environment used to build the web service and including the C#
compiler and the ASP.NET development libraries.
• Microsoft Windows 2000 Server (http://www.microsoft.com/windows2000/server/)
provides the operating system to host DB2, plus the tools to run the web service and
the C# ASP.NET application. Note that you can also use Windows 2000 Advanced
Server, Windows 2003 Server, or Windows 2003 Advanced Server.
• A separate C compiler to compile the stored procedures must also be available on
the same machine as the database server. You should refer to the DB2 installation
documentation for more details.
In order to follow along with this tutorial, you will need to create an empty database
called MUSIC using the DB2 Control Center. Simply use the Create Database Wizard
and specify MUSIC as the name of the database. No other information is required to
create the database.
Note: While this tutorial was created and tested on a single Windows 2000 Server
system, you may choose to run Visual Studio .NET on a Windows 2000 or XP
Professional system and copy the appropriate files to the Windows Server system for
execution.
You can also download all of the files in ZIP format (65 KB) for this example.
IBM, DB2, and DB2 Universal Database are trademarks or registered trademarks of
IBM Corporation in the United States, other countries, or both.
Other company, product, and service names may be trademarks or service marks of
others.
The JustPC.com Music Company maintains a database with information about various
CDs it has for sale. Through a Web service it provides, you can search the database to
retrieve various kinds of information, including a list of artists, a list of CDs recorded by
a specific artist and the list of tracks on the CD.
The customer's computer uses a Web browser to connect to a Web server which runs
the C# ASP.NET program. The C# program in turn communicates to a computer that
runs the Web service. Finally, the Web service executes stored procedures on the DB2
database server to retrieve the data returned to the client.
While the above diagram shows four independent computers, there is no reason why
the functions performed by each computer can't be combined. In fact this tutorial was
written on a single Windows 2000 Server computer running DB2 and Visual Studio
.NET. While this approach is a bit extreme, you may want to try this tutorial on a single
test computer before migrating it to use multiple computers in a more production-like
environment.
Database design
The database consists of two tables: one table containing a list of CDs, and a second
table containing a list of the tracks for each CD in the first table.
Stored procedures
The stored procedures access the database tables containing information about the
CDs in the music store.
The GetArtists stored procedure returns a list of artists available in the database.
There are no parameters in this stored procedure, although the stored procedure
needs to insure that each artist is unique.
The GetCDs stored procedure returns a list of CDs that were recorded by a particular
artist. The information returned includes CDId, Title, Artist, Type, Year and
Price. Note that you must pass a valid value for Artist to this stored procedure.
Ideally, this name should be derived from the list of artist names returned by the
GetArtists stored procedure.
Finally, the GetTracks stored procedure returns a list of tracks for a particular CD.
This stored procedure will return the TrackId and Title columns. The CDId value
must be passed to the stored procedure and the best place to get the CDId value is
from results returned by the GetCDs stored procedure.
Web service
The Web service uses the stored procedures to provide three methods to access the
data in the database.
• The GetArtists method returns the set of Artists found in the database. This
method has no parameters and returns a .NET DataSet object containing the list of
artists.
• The GetCDs method returns a collection of information about the CDs that are
recorded by a particular artist. The method has a single parameter -- a string
containing the name of the artist.
• The GetTracks method returns a list of tracks for a particular CD. You must supply
a valid integer containing the CDId to the web method in order to retrieve the
appropriate tracks.
C# ASP.NET program
In order to demonstrate the capabilities of the Web service, a simple ASP.NET
program was written in C#. This program calls all three of the Web service's methods
discussed in the previous panels and allows the visitor to the Web site to inquire about
any particular artist and CD available for sale.
Select IBM Projects as the Project Type and choose DB2 Database Project as the
template. Enter MusicStore as the name of the project and choose the appropriate
location on your computer to save the project. Press OK to begin creating the new DB2
Database Project.
Enter the name of the database in the Database Alias field, then enter a valid user
name and password in those fields. You can verify that this information is correct by
pressing the Test Connection button. Note that as you specify the Database Alias and
User Name fields, a value for Connection Name will automatically be constructed.
Once you create this connection, you will be returned to the DB2 Data Connection
dialog, where you can select the newly created connection.
The Procedures icon contains the collection of stored procedures associated with this
project, while all of the database functions are listed under the Functions icon. These
represent elements that can be called from an application program. The elements listed
under the Scripts icon, however, contain collections of SQL statements that can be
executed directly from the Visual Studio .NET IDE.
Choose the Create Table template and enter CreateCds as the name of the new
script. Then pressing Open will create a new script with a script that can be modified to
create a new table.
The script is grouped into four main sections. The first section drops the existing table,
while the other sections will recreate the table. However including a Delete Table
statement in the script is not a good idea, since any data that you may load into the
table would be lost each time you build your application.
The second section in the script creates the new table by executing an SQL Create
Table statement. You need to replace that statement with the one shown below:
The third section adds a unique index on the table. Replace the statement in the
template with the one listed below:
The last section contains a series of Insert statements which add some rows to the
sample table. Rather than code an Insert statement for each row in the sample data
(there are over 500 rows in the sample data file), you can simply use the DB2 Control
Center to import the sample data into the table after you create the table.
Normally the IBM Explorer is a floating window over the Visual Studio .NET IDE.
However, I like to add the IBM Explorer window as a new tabbed window in the same
area as the Solution Explorer windows as shown below.
To delete a table, simply right click on the table's name and choose Delete from the
popup menu. A message box will then be displayed verifying that you really want to
delete the table.
Once the table has been deleted, simply choose Build => Build Solution from the
main menu to create your table. You can also right click on the script in Solution
Explorer and choose Compile from the popup menu. Any error messages will be
displayed in the Output pane located at the bottom of the Visual Studio .NET IDE.
This Create Index statement is used to insure that only one unique combination of
CDId and TrackId exists in the table:
Finally, the Build => Build Solution command is used to create the second table.
Once this is done you can use the DB2 Control Center to populate the table from the
sample data.
Choose Procedures as the category and the DB2 Stored Procedure Wizard as the
template, then enter GetCDs.db2sp as name of the stored procedure as the name of
the stored procedure and click the Open button to create your new stored procedure.
In the first step of the wizard, you will choose a name for your stored procedure and
then provide comments that describe the stored procedure. Press Next to move to step
2. Note that the name you specify here is the actual name of the stored procedure,
while the name you specified when you added a new item to the project is merely the
name of the file that contains the stored procedure.
You can change the name of the statement in the Name file, and change the
statements location in the list of statements by changing the number in Order. You can
also use the up and down arrows next to the Statements box to do the same thing.
In the SQL statement box, enter the following SQL statement. You should always use a
unique name for a parameter and prefix the name with a colon. In this procedure,
:Artist is the only parameter.
Don't include a semicolon at the end of the statement, as the wizard will automatically
add one when it generates the script for the stored procedure. Also, if you want to use
multiple lines in your SQL statement, press Ctrl-Enter. When you have entered all of
the statements needed, press Next.
Defining parameters
Each parameter used in the stored procedure is listed in the Parameters box as shown
below. You can display detailed in formation about a parameter by selecting it in
Parameters box. Then you can modify the attributes about the parameter in the
Parameter detail section of the form.
In this case, the Artist parameter, is a Varchar(255) value, which you will have to
manually define. Depending on the type you choose, you may need to enter additional
information such as precision and scale for Decimal.
You can also arrange the order of the parameters in the Parameters box by pressing
the up and down arrows or changing the Order value after selecting a particular
parameter. You may also use the Add and Remove buttons to change the list of
parameters passed to this routine. If you remove a parameter that was automatically,
you may need to press the Back button and modify any statements that referenced the
parameter.
In the final step of the wizard, you'll see a short summary of the information that will be
used to create the stored procedure. You can also preview the script that will be used
to generate the stored procedure by pressing the Show generated code button. Once
you have verified everything, press Finish to create the stored procedure script.
The Output pane (bottom left pane) contains any errors that may have occurred during
compilation. If you encounter any errors, you should switch from the Build pane to the
IBM DB2 Output Message Pane. This pane will contain DB2 specific error messages.
Once you have successfully compiled the stored procedure, it is available for you to
use. If you can switch from the Solution Explorer to the IBM Explorer and refresh the
display (right click and choose Refresh from the popup menu), you will see the new
stored procedure.
To run the stored procedure, right click on its name and choose Run Stored
Procedure from the popup menu. If the stored procedure has parameters, you will be
prompted to enter their values using a dialog like the one shown below.
After entering a value and pressing OK, the results will be displayed the Visual Studio
.NET IDE. Since this stored procedure has an input set and a result set, you will see a
small plus sign, which expands to list these sets. Then clicking on the result set link will
display the results from the stored procedure as shown below.
The GetArtists stored procedure is illustrated below. It merely returns a unique list
of artists from the CDs table:
The GetTracks stored procedure takes a single parameter, :CDId, which identifies
the CD containing the tracks you want to retrieve:
In the next section, we'll build a C# program to access the DB2 database.
You can create the C# Web service by starting with the default C# Web Service
template, changing the names used with the newly created Web service to reflect this
particular application, and then adding Web methods that call the DB2 stored
procedures to access the database.
To create the new Web service, start Visual Studio .NET (start => Programs =>
Microsoft Visual Studio .NET => Microsoft Visual Studio .NET), and then click the
New Project button on the Start Page or choose File => New Project from the main
menu. You will see the New Project dialog box as shown below:
Select Visual C# Projects in the Project Types section of the dialog box and then select
ASP.NET Web Service in the templates section. Next choose the location for your Web
service. This example uses http://multivac/IBM/MusicStoreWebService.
Next you need to open the file to make rest of the changes. Right click over the new file
name and choose View Code from the popup menu. This will display the source code
for the prototype in the main pane of the Visual Studio .NET development window.
using IBM.Data.DB2;
Next you need to change the name of the service to complete the change from the
previous step. First you need to change every reference of Service1 to
MusicStoreInfo. You can either change it by using a search and replace (choose
Edit => Find and Replace => Replace from the main menu) or by changing the three
places Service1 appears in the code, one of which is a comment. The relevant code
fragment is shown below with the changes displayed in bold:
namespace MusicStoreWebService
{
/// <summary>
/// Summary description for MusicStoreInfo.
/// </summary>
public class MusicStoreInfo : System.Web.Services.WebService
{
public MusicStoreInfo ()
If you have never used C# in Visual Studio .NET, a word of caution is in order. Visual
Studio .NET has embedded some code of its own in the file you are editing. This
embedded code contains some methods that are used by the Visual Studio .NET
design tools, along with other references that insure that the service is properly
initialized and any resources it uses are disposed of properly. Do not remove this code
or your Web service may not work properly.
[WebMethod]
public DataSet GetArtists()
{
DataSet ds = new DataSet();
DB2Connection conn = new DB2Connection("database=Music");
DB2Command cmd = new DB2Command("Administrator.GetArtists", conn);
cmd.CommandType = CommandType.StoredProcedure;
DB2DataAdapter adpt = new DB2DataAdapter(cmd);
adpt.Fill(ds, "Artists");
return ds;
You can then define the function as you would normally define a function.
GetArtists is a public method that returns a DataTable object containing the
information extracted from the database.
The GetArtists method begins by declaring a new instance of the DataSet object
called ds. The DataSet object can hold a collection of DataTable objects. Then a
DB2Connection object is instantiated that contains a connection string pointing to the
particular instance of the database. Since the database runs on the same server, all
that you need to include in the connection is database=Music .
The DB2Command object combines the DB2Connection created in the previous line of
code with the fully qualified name of the stored procedure. Next, you should specify the
type of command contained in the DB2Command object using the CommentType
property. The last object to be created is a DB2DataAdapter, which includes a
reference to the DB2Command object that you just created.
After that the data adapter's Fill method is called to populate the DataSet object ds
with the results of the stored procedure. Then finally, the resulting DataSet object is
returned to the calling program.
Alternately, you can store configuration strings in the application's web.config file. To
modify the sample program, simply create a file called web.config in the same
directory as the Web page and insert the following XML elements. If you already have
a web.config file, just add the elements between the <appSettings> element
beneath the existing <configuration> element:
<configuration>
<appSettings>
</appSettings>
</configuration>
As you would expect, the code for this method is nearly identical to the GetArtists
method. However, following the line of code where you specify the type of command in
the DB2Command object, you should include the list of parameters for the stored
procedure.
[WebMethod]
public DataSet GetCDs(string Artist)
{
DataSet ds = new DataSet();
DB2Connection conn = new DB2Connection("database=Music");
DB2Command cmd = new DB2Command("Administrator.GetCDs", conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(":Artist", DB2Type.VarChar,64).Value = Artist;
DB2DataAdapter adpt = new DB2DataAdapter(cmd);
adpt.Fill(ds, "CDs");
return ds;
Because the Add method returns a DB2Parameter object, you can use the
DB2Parameter object's Value property to store the value you wish to use in the
newly created DB2Parameter object. While you could have explicitly created each
parameter object and then assigned it a value, this highly compact form is far more
readable if you have a stored procedure with more than a handful of parameters.
[WebMethod]
public DataSet GetTracks(int CDId)
{
DataSet ds = new DataSet();
DB2Connection conn = new DB2Connection("database=Music");
DB2Command cmd = new DB2Command("Adminitrator.GetTracks", conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(":CDId", DB2Type.Integer).Value = CDId;
DB2DataAdapter adpt = new DB2DataAdapter(cmd);
adpt.Fill(ds, "Tracks");
return ds;
After you enter all of the code for these Web methods, you are ready to compile your
Web service. Choose Build => Build Solution from the menu bar. Assuming that you
entered everything properly, you'll see a message in the Output pane (below the code
pane) that indicates that the build succeeded. Otherwise, you'll find a series of error
messages in the in the Output pane that will help you identify and correct the errors.
While you could easily add an ASP.NET Web page to your current project, it wouldn't
demonstrate the independence of the Web service from the ASP.NET application
program. So if you close your existing solution in Visual Studio .NET ( File => Close
Solution), you can open a new solution ( File => New Project) and start building the
ASP.NET application.
Next, enter the address the Web service you just created into the address field:
http://multivac/IBM/MusicStoreWebService/MusicStoreInfo.asmx
After you finish typing in the address, press the Enter key. You will then see the
information about the Web reference displayed in the dialog box as shown in the figure
below:
You may then browse the definitions and see the results though this dialog box. If you
click on an individual method, you will see more detailed information about the method.
You will also be given an opportunity to test the method and view the results. If
everything looks fine, press the Add Reference button at the bottom of the dialog box
to add the Web reference to your application.
Visual Studio .NET supports a drag and drop design tool that helps you lay out your
Web pages quickly. In this case, four elements were dragged from the Web Forms
toolbox on the left side of the screen onto the Web form. A Label control was dropped
and its Text property was set to The JustPC Music Store, and its Font
properties were modified to display the text in bold as well as make it larger.
Next a Button control was dropped on the form and its Text property was changed to
Show CDs for. Adjacent to the Button control, a DropDownList control was placed on
the Web form. Below the first Button and DropDownList, you should drag and drop a
second pair. This time you should change the Button's Text property to Show Tracks
for.
Finally a DataGrid control was added immediately below the pair of Button and the
DropDownList controls. The DataGrid will hold the final list of tracks for the selected CD
title.
If you wish, you can view the HTML associated with this Web page by switching from
the Design view to HTML view at the bottom of the editing surface. Any changes you
make in the HTML view will be reflected in the Design view when you switch back.
Once the Web form is laid out, double click on the form's background area. This will
open a new tab containing the code associated with the Web form and your cursor will
be positioned in the Page_Load event. The Page_Load event is fired each time the
Web page is generated, both when the page is originally requested and each time the
Web page posts information back to the server.
if (!IsPostBack)
{
multivac.MusicStoreInfo ws = new multivac.MusicStoreInfo();
DataSet ds = new DataSet();
ds = ws.GetArtists();
DropDownList1.DataSource = ds;
DropDownList1.DataTextField = "Artist";
DropDownList1.DataBind();
ds = ws.GetCDs(DropDownList1.SelectedItem.Value);
DropDownList2.DataSource = ds;
DropDownList2.DataTextField = "Title";
DropDownList2.DataValueField = "CDId";
DropDownList2.DataBind();
}
The best time to load the DropDownList is when the page is originally requested, and
this code ensures that the program isn't responding to a post back request. Then it
creates a new Web service using the variable ws from Web reference you added
earlier. The specific data type for this Web service is multivac.MusicStoreInfo. A
new DataSet object is also created at the start of the event. The Web service is then
used to retrieve the information about the artists in the database using the
GetArtists method.
An object reference to the data set is stored in the DataSource property of the
drop-down list. The column name containing the information to be displayed in the
drop-down list is assigned to the DataTextField property. Finally the drop-down list's
DataBind method is called to bind the data from the data set to the drop-down list
control.
This process is repeated for the second drop-down list, and is discussed in the next
panel.
The easiest way to define the Click event for the button is to switch back to the
Design view for the Web page and double click on the Show CDs for Button control.
Visual Studio .NET will automatically define the new event for you in the code section
of the Web page and place the cursor in the middle of the event.
The Web service and a data set object are defined as in the Page_Load event, but this
time the GetCDs method was used to extract information about the currently selected
artist in the drop down list. You can retrieve this value from DropDownList1 by using its
SelectedItem property to identify the currently selected item and then the item's
Text property to get the string value of the currently selected item:
ds = ws.GetCDs(DropDownList1.SelectedItem.Value);
DropDownList2.DataSource = ds;
DropDownList2.DataTextField = "Title";
DropDownList2.DataValueField = "CDId";
DropDownList2.DataBind();
Once you have the string value, it's merely a matter of passing that value to the
GetCDs method to retrieve a data set with all of the CDs for that particular artist. Once
the data set has been created, you save an object reference to it in the second
drop-down list's DataSource property.
DropDownLists have a useful feature that allows you to associate two values with each
item in the drop down list. The DataTextField represents the visible content in the list.
The DataValueField represents a "hidden" value that's distinct from the text value.
Thus you can display the title of the CD, while keeping track of the CD's unique
identifier.
ds = ws.GetTracks(Convert.ToInt32(DropDownList2.SelectedItem.Value,10));
DataGrid1.DataSource = ds;
DataGrid1.DataBind();
Next an object reference to the returned data set object is stored in the data grid's
DataSource property. Calling the DataBind method of the data grid will populate the
data grid using all of the rows and columns extracted from the Tracks table. The
DataGrid control will automatically create all of the necessary columns and rows based
on the information stored in the data set.
The work was about evenly split between the database activities (defining the tables,
loading the data and creating the stored procedures) and programming activities
(building the Web service and the application program). Visual Studio .NET coupled
with the DB2 Development Add-in makes short work of most tasks.
The DB2 Development Add-in was used to define the database tables and to create
and test the stored procedures that provide the data to the Web service. Visual Studio
.NET was used to create both the Web service and the sample application that used
the Web service to access the database. The DB2 managed data provider is well
integrated in Visual Studio .NET and makes it extremely easy to access a DB2
database.
Resources
• Download an evaluation copy of DB2 from:
http://www6.software.ibm.com/dl/db2udbdl/db2udbdl-p .
• Download a copy of the DB2 .NET Enablement beta, which includes the DB2
managed data provider, from:
http://www7b.software.ibm.com/dmdd/downloads/dotnetbeta/.
• Download a copy of the .NET Framework, including a command-line version of the
C# compiler from: http://www.asp.net/download.aspx?tabindex=0&tabid=1.
• Download a copy of ASP.NET Web Matrix, a free ASP.NET development tool, from:
http://www.asp.net/webmatrix/default.aspx?tabindex=4&tabid=46. This tool requires
the .NET Framework listed above.
• Learn how to create stored procedures using the DB2 development center in the IBM
developerWorks tutorial Creating stored procedures with DB2.
• Learn how to create SQL queries using the SQL Assist for DB2 tool in the article
Creating SQL queries the easy way with SQL Assist for DB2 UDB Version 8.1 from
IBM DB2 Developer Domain.
Section 8. Feedback
Your feedback
Colophon
This tutorial was written entirely in XML, using the developerWorks Toot-O-Matic tutorial
generator. The open source Toot-O-Matic tool is an XSLT style sheet and several XSLT
extension functions that convert an XML file into a number of HTML pages, a zip file, JPEG
heading graphics, and two PDF files. Our ability to generate multiple text and binary formats
from a single source file illustrates the power and flexibility of XML. (It also saves our
production team a great deal of time and effort.)