SlideShare a Scribd company logo
Odpnet Developers Guide Oracle Database 10g
Development With Visual Studio 2005 And The
Oracle Data Provider For Net Jagadish
Pulakhandam Sunitha Paruchuri download
https://ebookbell.com/product/odpnet-developers-guide-oracle-
database-10g-development-with-visual-studio-2005-and-the-oracle-
data-provider-for-net-jagadish-pulakhandam-sunitha-
paruchuri-4104880
Explore and download more ebooks at ebookbell.com
Here are some recommended products that we believe you will be
interested in. You can click the link to download.
Odpnet Developers Guide Oracle Database 10g Development With Visual
Studio 2005 And The Oracle Data Provider For Net A Practical Guide For
Developers Developer Tools For Visual Studio 2005 1st Ed Jagadish
Chatarji Pulakhandam
https://ebookbell.com/product/odpnet-developers-guide-oracle-
database-10g-development-with-visual-studio-2005-and-the-oracle-data-
provider-for-net-a-practical-guide-for-developers-developer-tools-for-
visual-studio-2005-1st-ed-jagadish-chatarji-pulakhandam-1213244
Pro Odpnet For Oracle Database 11g 2nd Edition Edmund Zehoo Yap Wai
Hong
https://ebookbell.com/product/pro-odpnet-for-oracle-database-11g-2nd-
edition-edmund-zehoo-yap-wai-hong-33448242
Pro Odpnet For Oracle Database 11g 1st Edition Edmund Zehoo Yap Wai
Hong
https://ebookbell.com/product/pro-odpnet-for-oracle-database-11g-1st-
edition-edmund-zehoo-yap-wai-hong-34783930
Building Enterprise Systems With Odp An Introduction To Open
Distributed Processing Linington
https://ebookbell.com/product/building-enterprise-systems-with-odp-an-
introduction-to-open-distributed-processing-linington-4393208
Building Enterprise Systems With Odp An Introduction To Open
Distributed Processing 1st Edition Peter F Linington
https://ebookbell.com/product/building-enterprise-systems-with-odp-an-
introduction-to-open-distributed-processing-1st-edition-peter-f-
linington-4440298
ODP.NET Developer's Guide
Oracle Database 10g Development with Visual
Studio 2005 and the Oracle Data Provider for .NET
A practical guide for developers working with the Oracle
Data Provider for .NET and the Oracle Developer Tools
for Visual Studio 2005
Jagadish Chatarji Pulakhandam
Sunitha Paruchuri
BIRMINGHAM - MUMBAI
ODP.NET Developer's Guide
Oracle Database 10g Development with Visual Studio 2005 and the
Oracle Data Provider for .NET
Copyright © 2007 Packt Publishing
All rights reserved. No part of this book may be reproduced, stored in a retrieval
system, or transmitted in any form or by any means, without the prior written
permission of the publisher, except in the case of brief quotations embedded in
critical articles or reviews.
Every effort has been made in the preparation of this book to ensure the accuracy of
the information presented. However, the information contained in this book is sold
without warranty, either express or implied. Neither the authors, Packt Publishing,
nor its dealers or distributors will be held liable for any damages caused or alleged to
be caused directly or indirectly by this book.
Packt Publishing has endeavored to provide trademark information about all the
companies and products mentioned in this book by the appropriate use of capitals.
However, Packt Publishing cannot guarantee the accuracy of this information.
First published: June 2007
Production Reference: 1150607
Published by Packt Publishing Ltd.
32 Lincoln Road
Olton
Birmingham, B27 6PA, UK.
ISBN 978-1-847191-96-0
www.packtpub.com
Cover Image by www.visionwt.com
Table of Contents
Preface 1
Chapter 1: Introduction to ODP.NET 5
Introduction to ODP.NET 5
Why Use ODP.NET? 7
Oracle Database Access from .NET Applications 7
What Do We Require to Work with ODP.NET? 9
Introduction to Oracle Database Extensions for .NET 10
Oracle Database Extensions for .NET  10
How does .NET Work within Oracle Database? 10
Processing of .NET Stored Procedure with Oracle 11
Introduction to Oracle Developer Tools for Visual Studio 11
Summary 13
Chapter 2: Connecting to Oracle 15
Provider-Independent Model in ADO.NET 2.0 15
Listing All Installed .NET Data Providers 16
Enumerating all Oracle Data Sources Available 17
Connecting to Oracle Databases from .NET 19
Connecting Using .NET Data Provider Factory Classes 20
Connecting Using .NET Data Provider for OLEDB 22
Connecting Using .NET Data Provider for ODBC 23
Connecting using Microsoft's .NET Data Provider for Oracle  24
Connecting Using Oracle Data Provider for .NET (ODP.NET)  25
Connecting with Connection Pooling 27
Connecting with System-Level Privileges or DBA Privileges 28
Dynamic Connecting String Using OracleConnectionStringBuilder and app.config29
Embedding a tnsnames.ora Entry-like Connection String 31
Connecting to a Default Oracle Database 32
Connecting Using Windows Authentication (Single Sign‑On) 33
Summary 35
Table of Contents
[ ii ]
Chapter 3: Retrieving Data from Oracle Using ODP.NET 37
Fundamental ODP.NET Classes to Retrieve Data  37
Retrieving Data Using OracleDataReader  39
Retrieving a Single Row of Information 39
Using Using for Simplicity 42
Retrieving Multiple Rows on to the Grid  43
Pulling Information Using Table Name 46
Retrieving Typed Data  47
Working with Data Tables and Data Sets 48
Retrieving Multiple Rows into a DataTable Using OracleDataAdapter 48
Filling a DataTable Using OracleDataReader 51
Retrieving a Single Row of Information Using OracleDataAdapter 52
Working with DataTableReader 54
Populating a Dataset with a Single Data Table 55
Populating a Dataset with Multiple Data Tables 56
Presenting Master-Detail Information Using a Dataset 58
More About the OracleCommand Object 61
Retrieving a Single Value from the Database 61
Handling Nulls when Executing with ExecuteScalar 62
Handling Nulls when Working with OracleDataReader 63
Working with Bind Variables together with OracleParameter 64
Working with OracleDataAdapter together with OracleCommand 66
Techniques to Improve Performance while Retrieving Data 67
Summary 69
Chapter 4: Manipulating Data in Oracle Using ODP.NET 71
Executing DML or DDL Statements Using OracleCommand  71
Using INSERT with OracleCommand 72
Using UPDATE with OracleCommand 73
Using DELETE with OracleCommand 75
Multiple Inserts Using Statement Caching 76
Multiple Inserts Using Array Binding 78
Creating an Oracle Table Dynamically Using ODP.NET 81
Updating Offline Data to the Database Using OracleDataAdapter  82
Working with OracleCommandBuilder and OracleDataAdapter  84
Working with Transactions Using ODP.NET  86
Handling Oracle Errors and Exceptions  88
Displaying a Single or First Error 88
Displaying Multiple Errors 89
Summary 92
Table of Contents
[ iii ]
Chapter 5: Programming ODP.NET with PL/SQL 93
Working with Anonymous PL/SQL Blocks 93
Executing Anonymous PL/SQL Blocks 94
Passing Information to Anonymous PL/SQL Blocks 95
Retrieving Information from Anonymous Blocks 96
Working with PL/SQL Stored Procedures and Functions 98
Executing a PL/SQL Stored Procedure  98
Passing Parameter Values to a PL/SQL Stored Procedure  100
Using an Anonymous PL/SQL Block to Execute a PL/SQL Stored Procedure102
Retrieving Output Parameters from a PL/SQL Stored Procedure  103
Passing IN and Getting OUT Simultaneously  105
Handling User-Defined Application Errors 107
Executing a PL/SQL User-Defined Function  109
PL/SQL Packages, Tables, and REF CURSOR  111
Executing Routines in a PL/SQL Package 111
Executing a Procedure in a PL/SQL Package 112
Executing a User-Defined Function in a PL/SQL Package 114
Passing Arrays to and Receiving Arrays from Oracle Database 116
Sending an Array to Oracle Database 116
Receiving an Array from Oracle Database 119
Working with REF CURSOR Using ODP.NET 122
Pulling from REF CURSOR Using OracleDataReader 122
Filling a Dataset from REF CURSOR 125
Working with Multiple Active Result Sets (MARS) 126
Summary 130
Chapter 6: Dealing with Large Objects (LOBs) 131
Working with BFILEs 131
Setting Up the Environment to Work with BFILEs 132
Adding a New Row Containing BFILE 133
Updating an Existing BFILE Row 135
Retrieving BFILE Information from a Database 136
Retrieving Properties of a BFILE  138
Working with CLOBs 140
Inserting Huge Text Information into Oracle Database 140
Updating CLOB Information Using OracleClob 142
Retrieving CLOB Information from Oracle Database  143
Reading a Text File and Uploading as CLOB 144
Working with BLOBs 147
Setting Up the Environment to Work with BLOBs 148
Uploading Images to Oracle Database Using BLOB 150
Table of Contents
[ iv ]
Retrieving Images from Oracle Database Using BLOB 153
Uploading Documents to and Retrieving Documents from Oracle Database  154
Summary 158
Chapter 7: XML and XML DB Development with ODP.NET  159
A Fast Track on XML with Oracle 160
Generating XML from Existing Rows in Tables 163
Generate XML Using ADO.NET DataSet 163
Generate XML Using ExecuteXMLReader 164
Generate XML Using DBMS_XMLGEN 166
Converting Rows to HTML Using XML and XSLT 167
Manipulating Rows in a Table Using XML  171
Inserting Rows into Oracle Using XML 171
Updating Rows into Oracle Using XML 174
Working with Native XML in Oracle Database 175
Inserting XML Data into XMLType Using Traditional INSERT 175
Updating XML Data in XMLType Using Traditional UPDATE 177
Inserting XML Data Using OracleXmlType 178
Retrieving and Updating XML Data Using OracleXmlType 179
Extracting Individual Node Information of an XMLType Value 181
Summary 183
Chapter 8: Application Development Using ODP.NET 185
Notifying Applications of Database Changes 185
Catching Notifications 186
Catching Multiple Notifications 189
Identifying Rows Modified During Notifications 190
Developing Long-Running Applications  193
The Devil of Applications: Not Responding  194
Asynchronous Task with Multi-Threading 195
Developing Web Applications Using ASP.NET and ODP.NET 199
Web Development Using Smart Data Binding 199
Populating an ASP.NET DropDownList Control 199
Linking an ASP.NET GridView Control with a DropDownList Control 207
Add, Update, or Delete a Row Using GridView and FormView 212
Working with Web Controls Manually 218
Developing Web Reports Using ASP.NET 221
Creating a Strongly-Typed Dataset Using Designer 221
Designing and Binding a Report to the Dataset  224
Grouping and Displaying Sub-Totals 228
Embedding Charts (Graphs) in Reports 232
Table of Contents
[  ]
Object-Oriented Development Using ASP.NET and ODP.NET 235
Developing a Simple Oracle Database Helper Class 236
Developing a Simple Business Logic Class 238
Working with ObjectDataSource in an ASP.NET 2.0 Web Form 241
Developing Web Services Using ODP.NET 247
Creating the .NET XML Web Service 247
Consuming the Web Service from ASP.NET 255
Developing Smart Device Applications 259
Introducing Microsoft Windows Mobile 259
Consuming a Web Service from Pocket PC 260
Summary 263
Chapter 9: Introduction to Oracle Developer Tools for Visual Studio 2005265
Features of Oracle Developer Tools 265
Connecting to Oracle from Visual Studio Using Oracle Explorer 266
Retrieving Oracle Information from Visual Studio Using ODT 270
Working with Oracle Database Objects from Visual Studio Using ODT 274
Dealing with Tables, Views, and Sequences Using ODT 274
Creating Stored Procedures Using ODT 277
Debugging PL/SQL Stored Procedures from Visual Studio 279
.NET CLR Stored Procedures in Oracle 289
Taking Advantage of Automatic .NET Code Generation 296
Summary 307
Index 309
Preface
Oracle's ODP.NET is a .NET data provider that can connect to and access Oracle
databases with tight integrity. It can be used from any .NET language, including
C# and VB.NET. This book will show you how ODP.NET is the best choice for
connecting .NET applications with Oracle database. We will be dealing with the
concepts of ODP.NET and its requirements, working with SQL, PL/SQL, and
XML DB using ODP.NET, looking at application development with ODP.NET:
Web Applications, Web Services, and Mobile Applications. We will also learn to
manipulate Oracle databases from within Visual Studio using Oracle Developer
Tools for Visual Studio.
What This Book Covers
Chapter 1 introduces the concept of Oracle Database Extensions for .NET and
provides information about Oracle Developer Tools for Visual Studio.
Chapter 2 introduces the Provider-Independent Model in ADO.NET 2.0, and shows
how to connect to Oracle databases from .NET, working with .NET data providers,
connection pooling, system privileged connection, and single sign-on etc.
Chapter 3 shows you several methods to retrieve data from an Oracle database. You
will work with the core ODP.NET classes like OracleCommand, OracleDataReader,
OracleDataAdapter, OracleParameter, and ADO.NET classes like DataSet,
DataTable, and DataRow etc.
Chapter 4 is about inserting, updating, and deleting data in the database. You
will also learn about statement caching, array binding, working with offline data,
implementing transactions, and handling errors and exceptions encountered during
database work.
Preface
[  ]
Chapter 5 deals with working with PL/SQL blocks, PL/SQL stored procedures, and
functions. It also teaches you how to execute routines in PL/SQL packages, how to
pass arrays to and receive arrays from the Oracle database, and working with REF
CURSOR using ODP.NET.
Chapter 6 is completely dedicated to dealing with large objects in Oracle. This chapter
illustrates concepts, configurations, and programming for BFILE, BLOB, and CLOB
(or NCLOB) in conjunction with ODP.NET.
Chapter 7 gives details about Oracle XML DB, an add-on feature of Oracle database.
It provides information about generating XML from existing rows in tables,
manipulating rows in a table using XML, and working with native XML in the
Oracle database.
Chapter 8 deals with real-time application development scenarios like Oracle
database change notifications, asynchronous application development, web
application development using ASP.NET 2.0, web reporting (including grouping,
sub-totals, charts, etc.), Object-Oriented development with ODP.NET and ASP.NET,
XML web-services development using ODP.NET, and Smart Device Application
development (for clients like the Pocket PC).
Chapter 9 introduces you to Oracle Developer Tools for Visual Studio 2005. It
teaches you to connect to Oracle from the Visual Studio 2005 environment, retrieve
Oracle information from Visual Studio, and work with database objects from Visual
Studio. It also provides information about how to create and debug PL/SQL stored
procedures and .NET CLR stored procedures in Oracle.
Conventions
In this book, you will find a number of styles of text that distinguish between
different kinds of information. Here are some examples of these styles, and an
explanation of their meaning.
There are three styles for code. Code words in text are shown as follows: �����������
Connecting
to a default Oracle database is purely dependent on the ORACLE_SID key available in
your registry.�

A block of code will be set as follows:
Dim ProviderName As String = _
Oracle.DataAccess.Client
Dim fctry As DbProviderFactory = -
DbProviderFactories.GetFactory(ProviderName)
Preface
[  ]
When we wish to draw your attention to a particular part of a code block, the
relevant lines or items will be made bold:
Dim dt As DataTable = _
DbProviderFactories.GetFactoryClasses()
Me.DataGridView1.DataSource = dt
New terms and important words are introduced in a bold-type font. Words that you
see on the screen, in menus or dialog boxes for example, appear in our text like this:
clicking the Next button moves you to the next screen.
Warnings or important notes appear in a box like this.
Tips and tricks appear like this.
Reader Feedback
Feedback from our readers is always welcome. Let us know what you think about
this book, what you liked or may have disliked. Reader feedback is important for us
to develop titles that you really get the most out of.
To send us general feedback, simply drop an email to feedback@packtpub.com,
making sure to mention the book title in the subject of your message.
If there is a book that you need and would like to see us publish, please send
us a note in the SUGGEST A TITLE form on www.packtpub.com or email
suggest@packtpub.com.
If there is a topic that you have expertise in and you are interested in either writing
or contributing to a book, see our author guide on www.packtpub.com/authors.
Preface
[  ]
Customer Support
Now that you are the proud owner of a Packt book, we have a number of things to
help you to get the most from your purchase.
Downloading the Example Code for the Book
Visit http://www.packtpub.com/support, and select this book from the list of titles
to download any example code or extra resources for this book. The files available
for download will then be displayed.
The downloadable files contain instructions on how to
use them.
Errata
Although we have taken every care to ensure the accuracy of our contents, mistakes
do happen. If you find a mistake in one of our books—maybe a mistake in text or
code—we would be grateful if you would report this to us. By doing this you can
save other readers from frustration, and help to improve subsequent versions of
this book. If you find any errata, report them by visiting http://www.packtpub.
com/support, selecting your book, clicking on the Submit Errata link, and entering
the details of your errata. Once your errata are verified, your submission will be
accepted and the errata added to the list of existing errata. The existing errata can be
viewed by selecting your title from http://www.packtpub.com/support.
Questions
You can contact us at questions@packtpub.com if you are having a problem with
some aspect of the book, and we will do our best to address it.
Introduction to ODP.NET
In the early days of databases, developers used to have knowledge on only one data
access technology as they would usually concentrate on a single database. Later,
numerous database products advanced quickly, leaving programmers in a confused
state when selecting a particular data access methodology. The era of evolving
architectures like client/server (two tier), three tier, and multi-tier (which includes
web-enabled) has dramatically changed the way of accessing databases.
The paradigm got shifted from simple connection-oriented applications to
connection-less or disconnected (or offline) applications to meet the demands of
devices like PDAs/Handhelds, Smart Phones, Pocket PCs etc.
Introduction to ODP.NET
We now have several types of data access methodologies to develop applications.
Choosing the best data access methodology is totally dependent on the type of
application you are working on.
ADO.NET is a rock-solid technology and a proof of Microsoft's commitment to the
UDA (Universal Data Access) strategy. The ADO.NET layer in the .NET architecture
internally contains a few .NET data components (or .NET data providers), which can
be used to connect to and access any database.
Introduction to ODP.NET
[  ]
The data access through ADO.NET is shown in the following figure (along with
other data access methodologies available prior to .NET):
Traditional
VB/ASP
application
.NET Applications
ADO.NET
C/C++
Applications
Microsoft
SQL Server
.NET Data
Provider
Microsoft
Oracle
.NET Data
Microsoft
ODBC
.NET Data
Microsoft
OLEDB .NET
Data Provider
Oracle Data
Provider
(ODP
.NET)
Other / 3rd
party .NET
Data Provider
DAO
ADO
RDO
OLEDB (with OLEDB Providers)
ODBC (with ODBC Mgr. and ODBC Drivers) Respective
libraries
Access MS SQL Server Oracle
Other
RDBMS
Flat files,
XML, Mail
Servers
Other
Legacy
Systems
Even though Microsoft designed its own .NET data providers, it has also opened
its doors (specification) to the public and is encouraging other database companies
to develop their own .NET data providers. Microsoft made the data access model
consistent among all of the .NET data providers and thus any .NET data provider
should definitely conform to the standards and architecture of ADO.NET. One of
those is Oracle's ODP.NET, a .NET data provider that can connect to and access
Oracle databases with tight integrity.
Chapter 1
[  ]
The ODP.NET features optimized data access to the Oracle database from a .NET
environment. It is one of the several data access methods to connect to and access
Oracle databases. Oracle didn't simply stop giving support to Microsoft platform
with only ODP.NET. Instead, it has extended its commitment for Microsoft .NET
by adding� Oracle database extensions for .NET and Oracle Developer Tools for
Visual Studio.
The upcoming sections will give you a solid understanding of ODP.NET along with
its features.
Why Use ODP.NET?
Can't we access Oracle without ODP.NET? Yes, we can. It is not compulsory for you
to work with ODP.NET. As mentioned in the following section, we can still connect
to and access Oracle using other alternative methods. But, in terms of features and
performance, ODP .NET is your best choice for connecting .NET applications with
Oracle database. Let us see how!
I am limiting the discussion to only .NET applications or clients
that are trying to access Oracle databases. I will not be discussing
application development prior to .NET.
Oracle Database Access from .NET
Applications
There exist four main methodologies to access Oracle database from a
.NET application:
Microsoft's .NET data provider for ODBC (or ODBC.NET)
Microsoft's .NET data provider for OLEDB (or OLEDB.NET)
Microsoft's .NET data provider for Oracle
Oracle's data provider for .NET (or ODP.NET)
•
•
•
•
Introduction to ODP.NET
[  ]
Before discussing each of the above methodologies, let us understand their nature
from the following figure:
Any .NET Client
VB.NET C# C++.NET ASP
.NET …
ODBC.NET OLEDB.NET
Oracle ODBC Oracle OLEDB
Microsoft's
.NET data
provider
for Oracle
Oracle database
Oracle's Data
Provider
(ODP
.NET)
Oracle Client
ADO.NET
Microsoft's .NET data providers for ODBC and OLEDB are not intentionally
developed exclusively for Oracle database. Those are generic .NET data providers
mainly targeted for most of the common data sources. If you plan to use either of
those two .NET data providers, you are likely to face performance problems.
From the above figure, you can observe that there exists a separate layer for each of
those .NET data providers. In other words, ODBC.NET or OLEDB.NET would not
directly execute the queries or commands. Those operations would be carried to
another intermediate layer (or data access bridge) and further get executed at Oracle
database. The existence of this intermediate layer really kills the performance (or
response time) of execution. So, if you are trying to access Oracle database from a
.NET application, neither of those would be a good choice.
Coming to the next choice, it is somewhat promising. Microsoft contributed a
separate .NET Framework data provider (or Microsoft's Data Provider for Oracle) to
connect to and access Oracle. It enables data access to Oracle data sources through
Oracle client connectivity software without having any intermediate layers. This
really improves performance over the previous two choices. Before using this
provider in your .NET applications, you should install and configure Oracle client
software (version 8.1.7 or later) on the development machine and test it.
Chapter 1
[  ]
The Oracle Data Provider for .NET (ODP.NET) features optimized data access to
the Oracle database from any .NET client. It is the best in performance together with
great flexibility. It allows developers to take advantage of native Oracle data types
(including XML data type), XML DB, binding array parameters, Multiple Active
Result Sets (MARS), Real Application Clusters (RAC), advanced security, etc.
What Do We Require to Work with ODP.NET?
As we are trying to develop .NET applications with access to Oracle database, we
must have .NET Framework installed on our machine. Any Windows Operating
System (preferably Windows Server 2003 or Windows XP Professional) supporting
.NET can be used to work with ODP.NET.
At the time of this writing, .NET Framework 3.0 is the latest in market; but Oracle
hasn't released ODP.NET compatible with that version yet. Not only that, Visual
Studio 2008 (or Orcas) supporting .NET Framework 3.0/3.5 is still in its beta
version. For our purpose .NET Framework 2.0 is the latest in market, and you can
download it free from Microsoft's website.
Even though .NET Framework (including SDK and .NET runtime) alone is enough
to develop .NET-based applications, it is better to have some GUI-based RAD
environment (or IDE) installed, so that we can develop .NET applications in no time.
Microsoft Visual Studio 2005 Professional Edition is the preferred GUI to develop
.NET 2.0-based applications. If you install Microsoft Visual Studio 2005 Professional
Edition, all the necessary components (including .NET Framework SDK and
runtime) get automatically installed.
The next is Oracle database. It is preferred to have at least Oracle 8.1 on your machine
(or on a separate server). If you want to test with the latest version of Oracle on your
own machine, you can download it free from Oracle's website for your development
purposes. The lightest Oracle database version available (free) at the time of this
writing is Oracle Database 10g Express Edition (or XE). Certain of the features like
.NET CLR extensions (for .NET CLR-based stored procedure development) for Oracle
are available only from Oracle 10g version 2.0 (Oracle 10.2) onwards. If you want to
have distributed transaction support (like COM+ or Enterprise Services, etc.), then
you may have install and configure Oracle Services for MTS.
If you install Oracle database version 9i release 2 or later on your own system, no
special Oracle client is necessary to work with ODP.NET. If your database is at some
other location, then you may have to install and configure Oracle 9i Release 2 or higher
client on your machine to work with ODP.NET. Oracle Net Services get automatically
installed when Oracle 9i Release 2 or higher client is installed on your machine. This
may be required when you try to access an Oracle database on a network.
Introduction to ODP.NET
[ 10 ]
Another important optional component is Oracle Developer Tools for Visual Studio
2005. This is a wonderful add-in, which gets injected right into Visual Studio 2005.
Using this add-in (called Oracle Explorer), you can connect to any Oracle database
and work with schema or data without leaving the Visual Studio 2005 environment.
It is particularly useful if you are likely to deal with .NET CLR extensions for Oracle.
I strongly recommend having it installed on your machine, if you are working with
Visual Studio Environment.
If you are developing ASP.NET applications, it is better to have IIS configured on
your machine, to test web applications over the network. If you are developing
Smart Phone or Pocket PC applications, you may need to install Smart Device
Extensions for Visual Studio (which automatically installs .NET Compact Framework
for Smart Devices).
Introduction to Oracle Database
Extensions for .NET
The Oracle Database Extensions for .NET is a new feature of Oracle Database
10g Release 2 on Windows that makes it easy to develop, deploy, and run stored
procedures and functions written in any .NET-compliant language.
Oracle Database Extensions for .NET
Oracle Database Extensions for .NET makes it possible to build and run any .NET-
based stored procedures or functions with Oracle Database for Microsoft Windows.
This feature is supported only from Oracle 10g version 2 (on Windows) onwards or
Oracle 10g Express Edition (or Oracle 10g XE).
How does .NET Work within Oracle Database?
How come Oracle understands .NET? Oracle database doesn't need to understand
.NET at all. It simply hosts the Microsoft .NET Common Language Runtime (CLR)
in an external process, outside of the Oracle database process, but on the same
computer. The integration of Oracle database with the Microsoft Common Language
Runtime (CLR) enables applications to run .NET stored procedures or functions on
Oracle database without any hurdles.
Application developers can write stored procedures and functions using any
.NET-compliant language, such as C# and VB.NET, and use these .NET stored
procedures in the database, in the same manner as other PL/SQL or Java stored
procedures. .NET stored procedures can be used from PL/SQL packages,
procedures, functions, and triggers.
Chapter 1
[ 11 ]
Once the caller (or other PL/SQL stored procedures, packages, etc.) calls any of these
.NET routines (stored procedures or functions), they get executed by the Oracle
hosted Microsoft CLR and the results are automatically picked up by the Oracle
PL/SQL engine. Once the control comes back to PL/SQL engine, it proceeds with the
normal and traditional the PL/SQL process flow of execution.
Processing of .NET Stored Procedure with Oracle
To develop .NET CLR-based stored procedures or functions, you may need to have
Oracle 10g version 2 or higher (for Windows) or at least Oracle 10g Express Edition
together with Oracle Database Extensions for .NET installed. If you use Oracle 10g
Express Edition, the extensions get automatically installed. But, if you install Oracle
10g version 2 (for Windows), you may have to go to custom install and select the
extensions. Apart from the extensions, you also need to download Oracle Developer
Tools for Visual Studio (with appropriate version) to develop and deploy .NET CLR-
based routines in Oracle database.
Application developers build .NET stored procedures or functions using any .NET
compliant language, such as C# and VB.NET, into a .NET assembly (generally a
DLL), typically using Microsoft Visual Studio .NET 2003/2005. Obviously, we use
Oracle Data Provider for .NET (ODP.NET) in .NET stored procedures and functions
for Oracle data access. After building .NET procedures and functions into a .NET
assembly, developers deploy them in Oracle database, using the Oracle Deployment
Wizard for .NET, a component of the Oracle Developer Tools for Visual Studio .NET.
Once the .NET stored procedure gets deployed, the PL/SQL wrappers for all of
those routines get automatically created within the schema. The user invokes a .NET
stored procedure or function through this PL/SQL wrapper (which would be the
same as for normal PL/SQL stored procedures or functions). Oracle Deployment
Wizard for .NET determines the probable mappings between Oracle data types and
.NET data types, which the user can override. The mappings are handled seamlessly
by the PL/SQL wrapper.
Introduction to Oracle Developer Tools
for Visual Studio
Oracle Developer Tools for Visual Studio is an add-in for Microsoft Visual Studio
that tightly integrates the Visual Studio environment with Oracle database. You
will be able to manipulate Oracle databases from within Visual Studio and without
leaving Visual Studio.
Introduction to ODP.NET
[ 12 ]
At the time of this writing, Oracle Developer Tools for Visual Studio is available
for both Microsoft Visual Studio.NET 2003 and Microsoft Visual Studio.NET 2005
versions. If you have both versions on your computer, you can install for both of
those IDEs by installing Oracle Developer Tools for Visual Studio 2005.
Once you install Oracle Developer Tools for Visual Studio, Oracle Explorer
automatically shows up in the View menu of Visual Studio as shown in the
following figure:
Using Oracle Explorer in the Visual Studio environment, you can browse through
your entire Oracle schema, launch several designers and wizards to work with
different schema objects (like tables, views, etc.), execute queries directly against
your schema (using SQL Query Window), automatically generate .NET code, and
several more. The following is a small glimpse of Oracle Explorer:
Chapter 1
[ 13 ]
To work with database tables (for example inserting, updating, etc.) you can keep
yourself tied with Oracle Data Window. It also gives you the flexibility to run and
test your PL/SQL stored procedures. Oracle Explorer also includes a fully integrated
PL/SQL debugger (for Visual Studio 2005).
Apart from all of the above, you can easily develop and deploy .NET stored
procedures and functions using .NET Deployment Wizard.
Summary
In this chapter, we have covered the concepts of ODP.NET, requirements to work
with ODP.NET, Oracle Database Extensions for .NET, and finally concluded with an
introduction to Oracle Developer Tools for Visual Studio.NET
Connecting to Oracle
From this chapter on, we will start programming with ODP.NET. This chapter
mainly concentrates on the following:
Introducing the Provider-Independent Model in ADO.NET 2.0
Working with .NET data providers
Different ways to connect to Oracle database from ADO.NET 2.0
Connection pooling, system privileged connection, Windows authentication
Provider-Independent Model in ADO.NET 2.0
ADO.NET internally works with .NET data providers (or .NET data bridge provider)
to connect to and access data from different kinds of data sources (including
databases). The same data provider model existing in ADO.NET 1.1 is further
enhanced in ADO.NET 2.0 (with new factory classes) to leverage the flexibility of
developing database-independent applications.
What exactly is a ���������������������������������������������������������������
factory class?�������������������������������������������������
������������������������������������������������
The purpose of a factory class is to provide an
interface for creating families of related objects, with or without specifying their
concrete (method implementation) classes. If the factory class is created without one
or more implementations of methods, we call it as an abstract factory class.
The provider-independent programming model in ADO.NET 2.0 revolves around
the classes in the System.Data.Common namespace. There are mainly two new
factory classes that implement the provider-independent model (within the
same namespace):
DbProviderFactories
DbProviderFactory
•
•
•
•
•
•
Connecting to Oracle
[ 16 ]
Listing All Installed .NET Data Providers
Now, let us start our programming with listing all .NET data providers installed on
your machine. All .NET data provider-related information gets listed in the machine.
config file on your machine�������������������������������������������������
. Each provider is generally identified with its invariant
name. The invariant name (in most cases) is the same as its namespace.
The following code gives out the list of all .NET data providers installed on
your machine:
Imports System.Data.Common
Public Class Form1
Private Sub btnProviders_Click(ByVal sender As
System.Object, ByVal e As System.EventArgs) Handles
btnProviders.Click
Dim dt As DataTable = _
DbProviderFactories.GetFactoryClasses()
Me.DataGridView1.DataSource = dt
End Sub
End Class
Within the above code, the DbProviderFactories class is mainly used to enumerate
all .NET data providers installed on your machine. Using the same class, we can also
create instances related to a specific provider (to access databases specific to that
provider). To list all the .NET data providers installed on your machine, we can use a
GetFactoryClasses() ������������������������
method available in the DbProviderFactories class.
The highlighted line of code finds and lists all the .NET data providers installed on
your machine (and populates them into a data table). When that code gets executed,
the output should look similar to the following:
Chapter 2
[ 17 ]
According to the preceding figure, you can see that the machine has six .NET data
providers installed. The third column represents the invariant names to identify each
of those providers.
Enumerating all Oracle Data Sources Available
In the previous section, we enumerated the list of all .NET data providers installed
on the machine. In the previous screenshot, you should observe that the machine in
this example has the Oracle Data Provider for .NET installed, ��������������������
which is identified
with invariant name Oracle.DataAccess.Client.
In this section, we shall enumerate the list of all Oracle data sources available. Let us
go through the following code first:
Imports System.Data.Common
Public Class Form2
Private Sub btnDataSources_Click(ByVal sender As
System.Object, ByVal e As System.EventArgs) Handles
btnDataSources.Click
Dim ProviderName As String = _
Oracle.DataAccess.Client
Dim fctry As DbProviderFactory = _
DbProviderFactories.GetFactory(ProviderName)
If (fctry.CanCreateDataSourceEnumerator) Then
Dim dsenum As DbDataSourceEnumerator = _
fctry.CreateDataSourceEnumerator()
Dim dt As DataTable = dsenum.GetDataSources()
Me.DataGridView1.DataSource = dt
Else
MessageBox.Show(No datasources found)
End If
End Sub
End Class
Let us go through the above code step by step.
The following is the statement that selects the ODP.NET data provider:
Dim ProviderName As String = Oracle.DataAccess.Client
Connecting to Oracle
[ 18 ]
The .NET data provider name is nothing but the invariant name available for the
respective .NET data provider. In the previous screenshot, you can observe that
there is a special column named InvariantName to identify the respective .NET
data provider.
The following statement creates a factory instance of the data provider selected:
Dim fctry As DbProviderFactory = _
DbProviderFactories.GetFactory(ProviderName)
Once the factory instance is created, we need to determine whether the provider (or
instance) supports enumerating of data sources or not. This is easily accomplished
with the CanCreateDataSourceEnumerator() ����������������������������������
method����������������������������
(which returns a Boolean).
If the underlying .NET data provider supports enumerating the data sources, we
can find and retrieve all the data sources for respective .NET data provider using the
following code:
If (fctry.CanCreateDataSourceEnumerator) Then
Dim dsenum As DbDataSourceEnumerator = _
fctry.CreateDataSourceEnumerator()
Dim dt As DataTable = dsenum.GetDataSources()
Me.DataGridView1.DataSource = dt
Else
MessageBox.Show(No datasources found)
End If
The CreateDataSourceEnumerator() method simply creates an enumerator. The
method GetDataSources() enumerates through all existing Oracle data sources.
When the above code gets executed, the output should look similar to the following:
Chapter 2
[ 19 ]
Here, the XE is nothing but the name of the Oracle instance (SID) running on the
system, which has Oracle 10g Express Edition installed.
So far we have just enumerated all the .NET data providers installed on our machine
and the list of Oracle data sources. We haven't connected to an Oracle database yet in
the preceding code.
Connecting to Oracle Databases from .NET
There are several ways to connect to Oracle database from within .NET. Each of those
methods has its own pros and cons as described in Chapter 1. Now, we will explore
the most popular methodologies to connect to Oracle database through .NET.
To connect to Oracle, we need to have proper connection descriptors configured
on the system. This is usually taken care by the� tnsnames.ora file. TNS stands
for Transparent Network Substrate. It provides a uniform application interface to
enable network applications to access the underlying network protocols. tnsnames.
ora ��������������������������������������������������������������������������������
is simply a text file that provides SQL*Net with the Oracle server location and
the necessary connection strings to connect to Oracle databases. This file always
resides in the ��������������
Oracle home's NetworkAdmin folder.
If the Oracle client (or SQL*Plus) is already able to connect to the Oracle database
server, the tnsnames.ora file is already correctly configured and you need not
disturb it. But, it is beneficial for you to look at the content of tnsnames.ora to have
a better understanding of the connection descriptors. The following is an example
entry available in the tnsname.ora file on a machine to get connected to Oracle
(yours could be different):
XE =
(DESCRIPTION =
(ADDRESS_LIST =
(ADDRESS = (PROTOCOL = TCP)(HOST = 127.0.0.1)
(PORT = 1521))
)
(CONNECT_DATA =
(SERVICE_NAME = xe)
)
)
The above configuration script shows that the Oracle database server is available at
127.0.0.1 (local machine) and listening at port 1521. The service name (or SID) to
connect to the server is xe. The whole description is assigned to a name XE.
We will make use of the above specification in most of the connection strings
available in the examples.
Connecting to Oracle
[ 20 ]
Before building the connection strings, make sure that you configured
and tested tnsnames.ora properly and can connect to the Oracle
database. If you can already connect to the Oracle database server,
you need not modify further. But you should know to which host
you are going to connect. This is essential, as an Oracle client could
be configured to connect to more than one Oracle database server
simultaneously. You can also configure and test these connections
using a graphical wizard, Net Configuration Assistant.
Connecting Using .NET Data Provider Factory
Classes
The previous topic introduced .NET data provider factory classes and this section
will use those classes to connect to an Oracle database.
The following code demonstrates how to connect to an Oracle database using the
.NET data provider factory classes:
Imports System.Data.Common
Public Class Form3
Private Sub btnConnect_Click(ByVal sender As
System.Object, ByVal e As System.EventArgs) Handles
btnConnect.Click
'specify provider's invariant name
Dim ProviderName As String = _
Oracle.DataAccess.Client
'create factory instance for the provider
Dim fctry As DbProviderFactory = _
DbProviderFactories.GetFactory(ProviderName)
'create connection based on the factory
Dim Connection As Data.Common.DbConnection
Connection = fctry.CreateConnection
'specify connection string
Connection.ConnectionString = _
Data Source=xe;user id=scott;password=tiger
Try
'try connecting to oracle
Connection.Open()
'close the connection before exiting
Connection.Close()
MessageBox.Show(Succesfully connected)
Chapter 2
[ 21 ]
Catch ex As Exception
'display error message if not connected
MessageBox.Show(Unable to connect.   ex.Message)
End Try
End Sub
End Class
From the preceding code we have the following statements that are used to create
a factory instance for the .NET data provider selected (in this case it is Oracle.
DataAccess.Client).
Dim ProviderName As String = _
Oracle.DataAccess.Client
Dim fctry As DbProviderFactory = _
DbProviderFactories.GetFactory(ProviderName)
Further moving down, we have the following:
Dim Connection As Data.Common.DbConnection
Connection = fctry.CreateConnection
Data.Common.DbConnection can simply hold any type of database connection
irrespective of the data source or data provider. To create a database connection
object from the factory instance, we can make use of the CreateConnection()
method, which in turn returns an object of the type Data.Common.DbConnection.
Once the DbConnection object is created (for the respective .NET data provider
through the factory instance), it needs to be provided with database connection
string information as follows:
Connection.ConnectionString = _
Data Source=xe;user id=scott;password=tiger
Once the DbConnection object is ready, we can open the connection to connect and
work with the database. It is always suggested to open a database connection as late
as possible and close it as early as possible. The following code fragment tries to
open the connection using the Open() method and closes using the Close() method:
Try
'try connecting to oracle
Connection.Open()
'close the connection before exiting
Connection.Close()
MessageBox.Show(Succesfully connected)
Catch ex As Exception
'display error message if not connected
MessageBox.Show(Unable to connect.   ex.Message)
End Try
Connecting to Oracle
[ 22 ]
This model (and method) of connectivity is mostly preferred when you are trying to
develop database-independent applications.
Connecting Using .NET Data Provider for
OLEDB
This method is mostly preferred when you are trying to develop database-
independent applications based on ADO.NET 1.1. If you are trying to develop a
database-independent application based on ADO.NET 2.0, the method provided in
the previous section is preferred.
The following is the code to connect to Oracle database using .NET data provider
for OLEDB:
Imports System.Data.OleDb
Public Class Form4
Private Sub btnConnect_Click(ByVal sender As
System.Object, ByVal e As System.EventArgs) Handles
btnConnect.Click
Dim cn As New OleDbConnection
cn.ConnectionString = Provider=msdaora;
Data Source=xe;User Id=scott;Password=tiger;
Try
'try connecting to oracle
cn.Open()
'close the connection before exiting
cn.Close()
MessageBox.Show(Succesfully connected)
Catch ex As Exception
'display error message if not connected
MessageBox.Show(Unable to connect.   ex.Message)
End Try
End Sub
End Class
In the above code, the System.Data.oleDb namespace is used to deal with .NET
Data Provider for OLEDB. When we are working with OLEDB data sources, we need
to connect through the OleDbConnection class. The connection string information
would also be different when we deal with .NET Data Provider for OLEDB to
connect to Oracle.
Chapter 2
[ 23 ]
The following is the new connection string used to get connected to Oracle database
using .NET Data Provider for OLEDB:
cn.ConnectionString = Provider=msdaora;
Data Source=xe;User Id=scott;Password=tiger;
Connecting Using .NET Data Provider for
ODBC
This method is used when you are trying to develop multi-platform
database‑independent applications using ADO.NET. This method is preferable, if you
want to connect to legacy systems or database systems existing on other platforms.
The following is the code to connect to Oracle database using .NET data provider
for ODBC:
Imports System.Data.odbc
Public Class Form5
Private Sub btnConnect_Click(ByVal sender As
System.Object, ByVal e As System.EventArgs) Handles
btnConnect.Click
Dim cn As New OdbcConnection
cn.ConnectionString =
Driver={Microsoft ODBC for Oracle};
Server=xe;Uid=scott;Pwd=tiger;
Try
'try connecting to oracle
cn.Open()
'close the connection before exiting
cn.Close()
MessageBox.Show(Succesfully connected)
Catch ex As Exception
'display error message if not connected
MessageBox.Show(Unable to connect.   ex.Message)
End Try
End Sub
End Class
Connecting to Oracle
[ 24 ]
In the preceding code, the System.Data.odbc namespace is used to deal with .NET
Data Provider for ODBC. When we are working with ODBC data sources, we need
to connect through the OdbcConnection class. The connection string information
would also be different when we deal with .NET Data Provider for ODBC to connect
to Oracle. The following is the new connection string used to get connected to Oracle
database using .NET Data Provider for ODBC:
cn.ConnectionString = Driver={Microsoft ODBC for Oracle};
Server=xe;Uid=scott;Pwd=tiger;
Connecting using Microsoft's .NET Data
Provider for Oracle
This provider is added by Microsoft to facilitate developers connecting and
accessing Oracle databases. This method is mostly preferred when you are trying
to access only Oracle databases and when you don't have ODP.NET installed on
your machine.
Before you start working with this provider, you need to add a reference to the
assembly System.Data.OracleClient as shown in following figure:
Chapter 2
[ 25 ]
Once you add a reference as shown in the preceding figure, you can proceed with the
following code to connect to Oracle database using Microsoft's .NET data provider
for Oracle:
Imports System.Data.OracleClient
Public Class Form6
Private Sub btnConnect_Click(ByVal sender As
System.Object, ByVal e As System.EventArgs) Handles
btnConnect.Click
Dim cn As New OracleConnection
cn.ConnectionString = _
Data Source=xe; User Id=scott;Password=tiger;
Try
'try connecting to oracle
cn.Open()
'close the connection before exiting
cn.Close()
MessageBox.Show(Succesfully connected)
Catch ex As Exception
'display error message if not connected
MessageBox.Show(Unable to connect.   ex.Message)
End Try
End Sub
End Class
In the above code, we are making use of the System.Data.OracleClient namespace
to deal with ������������
Microsoft's� .NET Data Provider for Oracle. The OracleConnection class
used in the above code is available as part of the same namespace (and not to be
confused with the same class available in Oracle.DataAccess.Client).
Connecting Using Oracle Data Provider for
.NET (ODP.NET)
This provider is contributed by Oracle to facilitate developers connecting and
accessing Oracle databases with tight integration (along with best performance) and
advanced features. This method is the best even when you are trying to access Oracle,
as ODP.NET has tight integration with Oracle database. To use this method, you must
have ODP.NET downloaded (available free) and installed on your machine.
Connecting to Oracle
[ 26 ]
Once you have ODP.NET installed on your machine, you need to add a reference to
the assembly Oracle.DataAccess. If you have more than one version installed, you
may have to choose the right one. If you are using Visual Studio 2005 and ODP.NET
10.2.0.2.20 (with support for ADO.NET 2.0) choose as shown in following figure:
Once you add a reference as shown in the above figure, you can proceed with the
following code to connect to Oracle database using ODP.NET:
Imports oracle.DataAccess.Client
Public Class Form7
Private Sub btnConnect_Click(ByVal sender As
System.Object, ByVal e As System.EventArgs) Handles
btnConnect.Click
Dim cn As New OracleConnection
cn.ConnectionString = _
Data Source=xe;User Id=scott;Password=tiger;
Try
'try connecting to oracle
cn.Open()
'close the connection before exiting
cn.Close()
MessageBox.Show(Succesfully connected)
Catch ex As Exception
Chapter 2
[ 27 ]
'display error message if not connected
MessageBox.Show(Unable to connect.   ex.Message)
End Try
End Sub
End Class
In the above code, the namespace Oracle.DataAccess.Client is used to deal with
Oracle Data Provider for .NET (ODP.NET). The OracleConnection class used in the
above code is available as part of the same namespace (and not to be confused with
the same class available in System.data.OracleClient). The connection string
information for this data provider and .NET data provider factory classes could be
the same (as both of them deal with the namespace internally).
Connecting with Connection Pooling
Opening and maintaining a database connection for each client (or application/
user) is expensive and wastes lots of resources. This is true especially during web
application development. To overcome such scenarios, Connection Pooling can
be implemented.
A Connection Pool is simply a cache of database connections. These connections can
be reused when the database receives future requests from clients (or applications)
for data. The clients (or applications) will feel as if each of them has a separate
connection to the database.
Connection Pooling is enabled by default and it is not only limited to ODP.NET but
also available with other .NET data providers. You can simply add pooling=false
to your connection string to disable Connection Pooling. You can customize pooling
with your own specification within the connection string.
The following is a simple demonstration of customizing the Connection Pooling as
part of the connection string:
Imports oracle.DataAccess.Client
Public Class Form7
Private Sub btnConnect_Click(ByVal sender As
System.Object, ByVal e As System.EventArgs) Handles
btnConnect.Click
Dim cn As New OracleConnection
cn.ConnectionString = Data Source=xe;
User id=scott;Password=tiger;
Min Pool Size= 5;
Connection Lifetime=120;
Connecting to Oracle
[ 28 ]
Connection Timeout=60;
Incr Pool size=2;
Decr Pool size=1
Try
'try connecting to oracle
cn.Open()
'close the connection before exiting
cn.Close()
MessageBox.Show(Succesfully connected)
Catch ex As Exception
'display error message if not connected
MessageBox.Show(Unable to connect.   ex.Message)
End Try
End Sub
End Class
The connection string in the code above is defined with several parameters.
Connection Lifetime sets the maximum duration in seconds of the connection
object in the pool. Connection Timeout is the maximum number of seconds to
wait for the connection to the server (before raising an error). Min Pool Size is the
number of connection objects it needs to hold at any time (similarly Max Pool Size
is also available). Based on the demands of requests and activity, the number of
connections in the pool gets decreased or increased based on the specification of
Incr Pool size and Decr Pool size.
Connecting with System-Level Privileges or
DBA Privileges
DBA-level privileges are primarily focussed on database object-level access of
a particular user. System-level privileges are more special when compared with
ordinary database-level (or even object-level) privileges. When connecting with
system-level�����������������������������������������������������������������������
privileges, you have the opportunity to administer the database, even
before it starts up.
The two main system-level privileges are SYSDBA and SYSOPER. When you log in
as SYSDBA, the default schema is SYS, whereas with SYSOPER the default schema is
PUBLIC. SYSDBA is a superset of SYSOPER.
While connecting with system-level privileges, it is obvious to work with DBA
privileges as well. If you don't need to work at system level, and simply want
to access few of the DBA objects, it is not really necessary to connect using
system-level privileges.
Chapter 2
[ 29 ]
If you need .NET applications to connect to Oracle with system-level privileges, you
just need to add connection parameters to the existing connection string as follows:
Imports oracle.DataAccess.Client
Public Class Form7
Private Sub btnConnect_Click(ByVal sender As
System.Object, ByVal e As System.EventArgs) Handles
btnConnect.Click
Dim cn As New OracleConnection
cn.ConnectionString = Data Source=xe;
User id=system;Password=manager;
DBA Privilege=SYSOPER
Try
'try connecting to oracle
cn.Open()
'close the connection before exiting
cn.Close()
MessageBox.Show(Succesfully connected)
Catch ex As Exception
'display error message if not connected
MessageBox.Show(Unable to connect.   ex.Message)
End Try
End Sub
End Class
In the above statement, you can observe that the user name is system (which is a
DBA user) and privilege is SYSDBA.
Dynamic Connecting String Using
OracleConnectionStringBuilder and app.config
You can dynamically build a connection string using the
OracleConnectionStringBuilder class available in ODP.NET 10.2.0.2. This is very
helpful if you have any Oracle connectivity parameters in the .NET configuration
files like app.config or web.config.
Connecting to Oracle
[ 30 ]
Now, let us add few of the Oracle connectivity parameters to the app.config file by
using solution properties as follows:
Once you add the parameters as shown in the above figure, you can
develop the code as follows to dynamically create a connection string using
OracleConnectionStringBuilder (explained later)�
:
Imports Oracle.DataAccess.Client
Public Class Form9
Private Function getConnectionString() As String
Dim cnBuilder As New OracleConnectionStringBuilder
With cnBuilder
.DataSource = My.Settings.DataSource
.UserID = My.Settings.UserID
.Password = My.Settings.Password
End With
Return cnBuilder.ConnectionString
End Function
Chapter 2
[ 31 ]
Private Sub btnConnect_Click(ByVal sender As
System.Object, ByVal e As System.EventArgs) Handles
btnConnect.Click
Dim cn As New OracleConnection
cn.ConnectionString = getConnectionString()
Try
'try connecting to oracle
cn.Open()
'close the connection before exiting
cn.Close()
MessageBox.Show(Succesfully connected)
Catch ex As Exception
'display error message if not connected
MessageBox.Show(Unable to connect.   ex.Message)
End Try
End Sub
End Class
From the above code, you can observe that we are trying to retrieve all the
connection parameters from the app.config file using the My object introduced in
.NET Framework 2.0. The OracleConnectionStringBuilder object simply needs
to have a few properties (like DataSource, UserID, Password etc.) set. Once the
properties are set, it automatically frames a connection string internally and returns
this when used with the ConnectionString property.
Embedding a tnsnames.ora Entry-like
Connection String
In all of the above examples, we directly used the specification available in the
tnsnames.ora file. You can even define your own entry in the style of tnsnames.
ora,������������������������������������������������������������������������
directly within the connection string. The following is the code for a tnsnames.
ora-less connection:
Imports oracle.DataAccess.Client
Public Class Form7
Private Sub btnConnect_Click(ByVal sender As
System.Object, ByVal e As System.EventArgs) Handles
btnConnect.Click
Dim cn As New OracleConnection
Dim ConnStr As String
Connecting to Oracle
[ 32 ]
ConnStr = Data Source = 
ConnStr = (DESCRIPTION = 
ConnStr =  (ADDRESS_LIST =
ConnStr =  (ADDRESS = (PROTOCOL = TCP)
(HOST = 127.0.0.1)(PORT = 1521))
ConnStr =  )
ConnStr =  (CONNECT_DATA =
ConnStr =  (SERVICE_NAME = xe)
ConnStr =  )
ConnStr = );
ConnStr = User Id=scott;
ConnStr = password=tiger;
cn.ConnectionString = ConnStr
Try
'try connecting to oracle
cn.Open()
'close the connection before exiting
cn.Close()
MessageBox.Show(Succesfully connected)
Catch ex As Exception
'display error message if not connected
MessageBox.Show(Unable to connect.   ex.Message)
End Try
End Sub
End Class
In the above code, we simply copied and pasted the entry available in tnsnames.ora
and it worked like a charm. You can also make the above connection string dynamic
(say, if you want to connect to different data sources at different times), by adding text
boxes to your form and concatenating those values with the above connection string.
Connecting to a Default Oracle Database
In all of the previous methods, within the connection string, we specified the data
source or server values to connect to an Oracle instance (using SID). Sometimes, it
may be necessary for us to get connected to the default Oracle database existing on
the same machine as of the .NET application (but not on any other network server).
Connecting to a default Oracle database is purely dependent on the ORACLE_SID key
available in your registry (as shown in the following). You can even add it manually
if it is not available in your Oracle home. Once that is added, you can define
connection strings without the specification of data source or server.
Chapter 2
[ 33 ]
Even though you can add this ORACLE_SID using the Environment
Variables dialog box, this method is not suggested if you have
multiple versions of Oracle installed on the same machine.
Once you set up the default Oracle database using the ORACLE_SID registry key in
your registry, the connection string could be modified and made simple (without
specifying any data source or server specification) as follows:
cn.ConnectionString = User Id=scott;Password=tiger;
Connecting Using Windows Authentication
(Single Sign‑On)
This is totally a different scenario from any of the previous types of connectivity to
Oracle databases. A Windows Authentication is simply a process of authenticating
against Oracle database using the Windows-user credentials. A Single Sign-on is
the process of authenticating against Oracle database even without providing any
credentials (by taking into the account of existing Windows-user credentials).
There exists no direct solution to achieve 100% �������������������������������
single sign-on�����������������
to authenticate
against Oracle database. However, we need to provide the user ID as /, which
automatically carries our current Windows-user credentials to authenticate
against Oracle database. By using this facility, we can develop .NET applications
implementing 100% ����������������������������������������
single sign-on against Oracle databases.
Connecting to Oracle
[ 34 ]
Primarily, a Windows Authentication to an Oracle database is not a straight process.
Even though, it is not very complicated process, we do have some configuration,
which needs to be set up using database administrator privileges. To get a Windows
user for a successful Windows authentication (or single sign-on) against Oracle
database, we must start by finding two important values as follows:
Operating System Authentication Prefix (os_authent_prefix parameter in
the init.ora file)
Windows user name (along with either host name or domain name)
The ���������������������������������������������������������������������
Operating System Authentication Prefix�������������������������������
gets configured during Oracle
installation and is available as an os_authent_prefix �����������������
parameter in the
init.ora file. We need to use this value as a prefix to the Windows-user credentials.
To retrieve the value of that parameter, you need to use the following statement:
SQL show parameter os_authent_prefix
You may need to have DBA privileges (or log in as system/sysdba/sysoper user) to
carry out these tasks.
You can easily get your complete user name (along with your host name or domain
name) from your login dialog box. You can even get it dynamically using the
following VB.NET code:
Private Sub btnWindowsUser_Click(ByVal sender As
System.Object, ByVal e As System.EventArgs) Handles
btnWindowsUser.Click
Dim WindowsUser As String = My.User.Name
MessageBox.Show(WindowsUser)
End Sub
Once you find out those two values, you need to create a user in Oracle with the
same Windows user name (along with host/domain name) preceded with the value
of os_authent_prefix and grant enough privileges to get the user connected.
Sometimes, the value of os_authent_prefix could be
empty (or no value). In such scenarios, you need not prefix the
Windows user with any value.
•
•
Chapter 2
[ 35 ]
You can issue the following statements to create and grant privileges to the Windows
user in Oracle:
SQL CREATE USER PS$LAPTOP2K3ADMINISTRATOR
IDENTIFIED EXTERNALLY;
SQL GRANT connect, resource TO
PS$LAPTOP2K3ADMINISTRATOR
In the above commands, PS$ is the parameter value of os_authent_prefix on my
machine and LAPTOP2K3ADMINISTRATOR is the Windows user. If there is no value
(or empty) for os_authent_prefix, you need not prefix the Windows user with any
value. Once the above setup is perfectly configured, you must be able to connect to
that user using the following command at the SQL prompt:
SQL connect /
You can observe that it is quite simple to connect to Oracle database using /, which
informs it to use a Windows authentication. In the same manner, you can modify
your connection string in .NET as follows to achieve a single sign-on authentication
(with Windows authentication) to Oracle database:
Dim cn As New OracleConnection
cn.ConnectionString = Data Source=xe;User Id=/;
Summary
In this chapter, we have reviewed the strategy of the Provider-Independent Model in
ADO.NET 2.0, used this model to list installed .NET data providers and data sources,
and finally developed code to connect to Oracle database from .NET using all the
available methods.
Retrieving Data from Oracle
Using ODP.NET
We have several methodologies to retrieve information from Oracle using ODP.NET.
Sometimes, we may have to use few of the ODP.NET classes together with few of the
ADO.NET classes to develop .NET applications efficiently.
In this chapter, we will concentrate on the following:
Executing queries with OracleCommand
Retrieving data using OracleDataReader
Retrieving data using OracleDataAdapter
Working with DataTable and Dataset when offline (disconnected mode)
Using DataTableReader with DataTable
Bind variables using OracleParameter
Performance techniques
If you would like to work with stored procedures to retrieve data, you should skip to
Chapter 5 (provided you are familiar with all the concepts discussed here).
Fundamental ODP.NET Classes to
Retrieve Data
To retrieve data from an Oracle database using ODP.NET, we need to work with a
few of the ODP.NET classes. At this point, we will discuss the most fundamental
classes available in ODP.NET for retrieving data.
•
•
•
•
•
•
•
Retrieving Data from Oracle Using ODP.NET
[ 38 ]
The following is the list of fundamental ODP.NET classes:
OracleConnection
OracleCommand
OracleParameter
OracleDataReader
OracleDataAdapter
The OracleConnection class provides the means to connect to the Oracle database.
We have already used this class several number of times in the previous chapter. It
connects to Oracle database and performs all the operations we need to carry out.
Without this class, we would never be able to perform any database operation. It also
manages transactions and connection pooling.
The OracleCommand class is mainly used to execute commands against Oracle
database. It supports the execution of SQL commands (like SELECT, INSERT, and
CREATE), stored procedures, etc. We can even specify table or view names (without
even providing a SELECT statement) to retrieve the rows available through them. It
works in conjunction with OracleConnection to connect to Oracle database.
The OracleParameter class is complementary to the OracleCommand class to
provide run‑time parameters along with their values to SQL queries or stored
procedures. You can even work with different types of stored-procedure parameters
like IN, OUT, or IN OUT. It is also mostly used whenever you want to execute the
same SQL command frequently or continuously.
The OracleDataReader class is simply a read-only and forward-only result set. As
the data retrieved using this class is non-updatable and only forward-navigable, this
is the fastest retrieval mechanism available. The most important point to remember
while using OracleDataReader is that it needs a dedicated connection to Oracle
database while it retrieves information. It is best used to fill in drop-down lists, data
grids, etc. It works in conjunction with OracleCommand to connect to and retrieve
information from Oracle database.
The� OracleDataAdapter class is mainly used to populate datasets or data tables
for offline use (disconnected use). The OracleDataAdapter simply connects to
the database, retrieves the information (or data), populates that information into
datasets or data tables, and finally disconnects the connection to the database. It
works with OracleConnection to connect to Oracle database. It can also work with
OracleCommand if necessary.
A data table is very similar to a disconnected result set (or record set). A dataset is
simply a set of data tables along with their relations (if available). A dataset is a kind
of small scale in-memory RDBMS, which gets created on demand.
•
•
•
•
•
Chapter 3
[ 39 ]
DataTable and DataSet are the two classes for these in ADO.NET that are used
in combination with OracleDataAdapter. The data in a dataset (or data table) can
be modified offline (in disconnected mode) and later can be updated back to the
database using the same OracleDataAdapter. In simple words, OracleDataAdapter
works as a bridge between offline data (or a dataset) and Oracle database.
Retrieving Data Using OracleDataReader
OracleDataReader is simply a read-only and forward-only result set. It works only
if the database connection is open and it makes sure that the connection is open
while you are retrieving data. As the data that it retrieves is read-only, it is a bit
faster than any other method to retrieve data from Oracle.
You need to work with OracleCommand together with OracleConnection to
get access to OracleDataReader. ������������
There is an ExecuteReader method in the
OracleCommand class����������������������
, which gives you the OracleDataReader.
Retrieving a Single Row of Information
Let us start by retrieving a single row from Oracle database using ODP.NET and
populate the data into few textboxes on a WinForm.
To connect to and work with Oracle database, we need to start with
OracleConnection. Once a connection to the database is established, we need to
issue a SELECT statement to retrieve some information from the database. A query
(or any SQL command) can be executed with the help of an OracleCommand object.
Once the SELECT statement gets executed, we can use OracleDataReader to retrieve
the information.
The following code accepts an employee number from the user and gives you the
details of that employee:
Imports Oracle.DataAccess.Client
Public Class Form1
Private Sub btnGetEmployee_Click(ByVal sender As
System.Object, ByVal e As System.EventArgs) Handles
btnGetEmployee.Click
'create connection to db
Dim cn As New OracleConnection(Data Source=xe; _
User Id=scott;Password=tiger)
Try
Dim SQL As String
'build the SELECT statement
Retrieving Data from Oracle Using ODP.NET
[ 40 ]
SQL = String.Format(SELECT ename, sal, job FROM
emp WHERE empno={0}, Me.txtEmpno.Text)
'create command object to work with SELECT
Dim cmd As New OracleCommand(SQL, cn)
'open the connection
cmd.Connection.Open()
'get the DataReader object from command object
Dim rdr As OracleDataReader = _
cmd.ExecuteReader(CommandBehavior.CloseConnection)
'check if it has any rows
If rdr.HasRows Then
'read the first row
rdr.Read()
'extract the details
Me.txtEname.Text = rdr(ename)
Me.txtSal.Text = rdr(sal)
Me.txtJob.Text = rdr(job)
Else
'display message if no rows found
MessageBox.Show(Not found)
End If
'clear up the resources
rdr.Close()
Catch ex As Exception
'display if any error occurs
MessageBox.Show(Error:   ex.Message)
'close the connection if it is still open
If cn.State = ConnectionState.Open Then
cn.Close()
End If
End Try
End Sub
End Class
As explained earlier, the above program creates an OracleConnection object
as follows:
Dim cn As New OracleConnection(Data Source=xe; _
User Id=scott;Password=tiger)
Chapter 3
[ 41 ]
Next, we need to create an OracleCommand object by providing a SELECT query and
the connection object (through which it can connect to the database):
Dim SQL As String
SQL = String.Format(SELECT ename, sal, job FROM
emp WHERE empno={0}, Me.txtEmpno.Text)
Dim cmd As New OracleCommand(SQL, cn)
Once the OracleCommand object is created, it is time to open the connection and
execute the SELECT query. The following does this:
cmd.Connection.Open()
Dim rdr As OracleDataReader = _
cmd.ExecuteReader(CommandBehavior.CloseConnection)
You must observe that the query gets executed using the ExecuteReader method of
OracleCommand object, which in turn returns an OracleDataReader object. In the
above statement, the ExecuteReader method is specified with CommandBehavior.
CloseConnection, which simply closes the database connection once the
OracleDataReader and OracleCommand are disposed.
We can use the HasRows property of OracleDataReader to test whether the reader
retrieved any rows or not. If any rows are retrieved, we can read each successive row
using the Read method of OracleDataReader. The Read method returns a Boolean
value to indicate whether it has successfully read a row or not. Once the Read
succeeds, we can retrieve each value in the row with the column name as follows:
If rdr.HasRows Then
'read the first row
rdr.Read()
'extract the details
Me.txtEname.Text = rdr(ename)
Me.txtSal.Text = rdr(sal)
Me.txtJob.Text = rdr(job)
Else
'display message if no rows found
MessageBox.Show(Not found)
End If
Finally, we close the OracleDataReader object using the Close method as follows:
rdr.Close()
Retrieving Data from Oracle Using ODP.NET
[ 42 ]
If it could read successfully, the output for this code would look similar to the
following figure:
Using Using for Simplicity
The above program can be made simple by using the Using statement together with
ODP.NET classes as follows:
Using cn As New OracleConnection(Data Source=xe;
User Id=scott;Password=tiger)
Try
cn.Open()
Dim SQL As String
SQL = String.Format(SELECT ename, sal,
job FROM emp WHERE empno={0}, Me.txtEmpno.Text)
Using cmd As New OracleCommand(SQL, cn)
Using rdr As OracleDataReader = cmd.ExecuteReader
If rdr.HasRows Then
'read the first row
rdr.Read()
'extract the details
Me.txtEname.Text = rdr(ename)
Me.txtSal.Text = rdr(sal)
Me.txtJob.Text = rdr(job)
Else
'display message if no rows found
MessageBox.Show(Not found)
End If
End Using
End Using
Catch ex As Exception
MessageBox.Show(Error:   ex.Message)
If cn.State = ConnectionState.Open Then
Chapter 3
[ 43 ]
cn.Close()
End If
End Try
End Using
The Using keyword is new in Visual Basic 2005, which internally generates try and
finally blocks around the object being allocated and calls Dispose() for you saving
you the hassle of manually creating it.
The objects created using the Using keyword are automatically erased (and
respective resources would be automatically cleared) from the memory once it is out
of using scope. Even though it is very flexible to use the Using statement, for the
sake of clarity, we will go without using it in the examples of this book.
Retrieving Multiple Rows on to the Grid
In the previous section, we tried to retrieve only one row using OracleDataReader.
In this section, we will try to retrieve more than one row (or a result set) and
populate a DataGridView on a WinForm.
The following code lists out the details of all employees available in the emp table:
Imports Oracle.DataAccess.Client
Public Class Form2
Private Sub btnGetEmployees_Click(ByVal sender As
System.Object, ByVal e As System.EventArgs) Handles
btnGetEmployees.Click
'create connection to db
Dim cn As New OracleConnection(Data Source=xe;
User Id=scott;Password=tiger)
Try
Dim SQL As String
'build the SELECT statement
SQL = String.Format(SELECT empno, ename, job,
mgr, hiredate, sal, comm, deptno FROM emp)
'create command object to work with SELECT
Dim cmd As New OracleCommand(SQL, cn)
'open the connection
cmd.Connection.Open()
'get the DataReader object from command object
Dim rdr As OracleDataReader = _
cmd.ExecuteReader(CommandBehavior.CloseConnection)
'check if it has any rows
If rdr.HasRows Then
Retrieving Data from Oracle Using ODP.NET
[ 44 ]
With Me.DataGridView1
'remove existing rows from grid
.Rows.Clear()
'get the number of columns
Dim ColumnCount As Integer = rdr.FieldCount
'add columns to the grid
For i As Integer = 0 To ColumnCount - 1
.Columns.Add(rdr.GetName(i), rdr.GetName(i))
Next
.AutoSizeColumnsMode =
DataGridViewAutoSizeColumnsMode.ColumnHeader
'loop through every row
While rdr.Read
'get all row values into an array
Dim objCells(ColumnCount - 1) As Object
rdr.GetValues(objCells)
'add array as a row to grid
.Rows.Add(objCells)
End While
End With
Else
'display message if no rows found
MessageBox.Show(Not found)
Me.DataGridView1.Rows.Clear()
End If
'clear up the resources
rdr.Close()
Catch ex As Exception
'display if any error occurs
MessageBox.Show(Error:   ex.Message)
'close the connection if it is still open
If cn.State = ConnectionState.Open Then
cn.Close()
End If
End Try
End Sub
End Class
Except the highlighted section, the rest of the code is already explained as part of the
previous section. You can observe that the SELECT statement now tries to retrieve all
rows from emp as follows:
SQL = String.Format(SELECT empno, ename, job, mgr,
hiredate, sal, comm, deptno FROM emp)
Chapter 3
[ 45 ]
Once the OracleDataReader is ready with rows, we need to start with clearing the
rows already displayed in the DataGridView with the help of the following code:
With Me.DataGridView1
'remove existing rows from grid
.Rows.Clear()
Once the rows are cleared, the first issue is the header of the grid. The moment we
add columns to the grid, the header row gets automatically populated (with the
column names). Before adding columns to the header, we should know the number
of columns being added (just for the loop iterations) with the FieldCount property
of DataGridView. The following is the code fragment that finds the number of
columns and adds the columns to DataGridView:
Dim ColumnCount As Integer = rdr.FieldCount
For i As Integer = 0 To ColumnCount - 1
.Columns.Add(rdr.GetName(i), rdr.GetName(i))
Next
All the columns get auto-sized based on the column header with the
following statement:
.AutoSizeColumnsMode =
DataGridViewAutoSizeColumnsMode.ColumnHeader
Once the columns are added, we need to read every successive row from the
OracleDataReader and add it to the DataGridview. To add all column values at a
time, we make use of the GetValues() method of OracleDataReader to push all the
values in to an array and finally add the array itself as a row to the DataGridView.
The following code fragment accomplishes this.
While rdr.Read
'get all row values into an array
Dim objCells(ColumnCount - 1) As Object
rdr.GetValues(objCells)
'add array as a row to grid
.Rows.Add(objCells)
End While
Another Random Scribd Document
with Unrelated Content
A. They never had a meeting after the 27th, that I know of, in
Pittsburgh.
Q. Did they at any other point?
A. Yes; the Trainmen's Union is still in existence.
Q. Was there any time arranged afterwards for a strike?
A. No; no time was agreed upon, but all labored under the
impression that the bubble had grown so large, that it would have to
burst sooner or later.
Q. Was there any pre-arranged plan, by which any strike was to take
place on the 19th of July?
A. No, there was not. There was some little talk about it, if the
railroad company would do so and so, that they would kick.
Q. Do what?
A. Put on double-headers.
By Senator Yutzy:
Q. What do you mean by kick?
A. Not stand it.
By Mr. Lindsey:
Q. Strike, do you mean?
A. Yes.
Q. Then there was no pre-arranged plan for that strike on the 19th?
A. There was no pre-arranged plan.
Q. Was it talked over?
A. Not on that day; but just as soon as they put on double-headers
they didn't propose to submit to it, as they thought seventeen cars
were enough for the men to take care of.
Q. These double-headers were only confined to the Pennsylvania
Central?
A. Yes.
Q. They didn't extend over any other roads leading into Pittsburgh?
A. No.
Q. Was it known to the men on any other roads that the men on the
Pennsylvania Central were going to strike?
A. I suppose they knew that they had their sympathy.
Q. I understood you to say that you left Pittsburgh the day before
the strike?
A. No; I left it about the 16th.
Q. Did you know any thing about it then, or understand that there
would be a strike then?
A. Yes; I remarked after the 27th day of June that I was positive
there would be a strike, sooner or later—that the thing would have
to come to a head itself.
Q. Did they say to you, or did you understand from any employés on
the Pennsylvania Central road, that there would be a strike on the
19th?
A. No one knew that they were going to strike on that day.
By Senator Reyburn:
Q. Then no time was set?
A. No.
By Mr. Lindsey:
Q. Was it understood that when the order was given to run the
double-headers that they would strike?
A. It was understood that just as soon as they put on double-
headers they wouldn't run them. The men couldn't stand it.
Q. Did you know any thing about the strike at Martinsburg?
A. Yes; I heard of it.
Q. Before it took place?
A. No; not before it took place. I knew of it as soon as it did take
place.
Q. Was there any general understanding that a strike would take
place at the time the strike broke out at Martinsburg?
A. No; the understanding we had of this thing—our object in
organizing the Trainmen's Union was, that the Pennsylvania
Company would make a reduction on the first of June of ten per
cent., and that, if their employés submitted to it, that the New York
Central would follow about the 1st of July, and if their employés
submitted to it—they had two roads, and had pooled their earnings
—they would make a reduction on the 15th of July on the Baltimore
and Ohio. They thought if they didn't get a strike before the 15th
day of July, then the Pennsylvania road and these other roads would
get so used to it, or that they would get us so frightened that we
would have the idea knocked out of us, if they could run their traffic
over those roads. They were not going to make a reduction over two
trunk lines at one time.
Q. Did all that happen?
A. No; there was a reduction on the Pennsylvania on the 1st of June,
and on Vanderbilt's road on the 1st of July, and on the Baltimore and
Ohio on the 15th or 16th, and on the 15th was the strike.
Q. Did you have any communication with the men at Martinsburg
before they struck?
A. I had some friends down there, and I used to hear from them
once in a while.
Q. About the strike—this particular strike that took place at
Martinsburg—did your union communicate with them? Was it
understood or arranged between you for that strike on the 16th?
A. No; although they said that just as soon as they got the reduction
they were going to strike.
Q. I understand you to say it was the double-headers, or the order
to run them, that caused the strike on the 16th, at Pittsburgh?
A. Yes; because it was the wrong time to put on the double-headers,
just following the strike at Martinsburg. That just started the whole
thing.
Q. This Trainmen's Union was organized, you say, for the purpose of
protecting yourself?
A. For protecting our own interests.
Q. What had you to complain of at the time of organizing the union?
A. The ten per cent. reduction. We thought we were getting little
enough money.
Q. Had you anything else to complain of?
A. Yes; we had something a little worse than the reduction. That was
all right. If they saw fit to reduce, and could get men to work at
their rate, all right. The officials of the road, and Mr. Scott, all
treated us all right. It was only the little under-officials who treated
us like dogs. I was told that if I voted for a certain man I would get
discharged off the road. I wanted to vote for a neighbor of mine.
Q. By whom were you told that?
A. By a petty under-official, the assistant day dispatcher.
Q. Had you anything to complain of, except this ten per cent.
reduction?
A. Not on our road—not on the Fort Wayne road.
Q. Had they on the Pennsylvania Central, before the order was
issued to run the double-headers?
A. No; I don't believe they had.
Q. That was the only thing you had to complain of?
A. Yes.
Q. Did you have any negotiations with the magnates of the road in
regard to that?
A. Yes; we appointed a committee to wait on them, and talk with
them, and try to get the thing settled up; but we couldn't reach
them with a forty-foot pole. We tried everything with reference to
avoiding a strike.
By Senator Reyburn:
Q. How long were you on the road?
A. About eleven months, I guess.
Q. Had there been any talk of striking before—during those eleven
months?
A. No.
Q. Were any committees appointed to wait on the officials?
A. That was when we heard of the ten per cent. reduction.
Q. Had you any grievances before?
A. No.
By Mr. Lindsey:
Q. It was arranged then by your union that you would strike in case
of a reduction?
A. That was what we organized for.
Q. Do you claim the right at all times to strike as a body? Do you
claim that it is one of the rights that you have?
A. I claim that every free born American citizen, if necessary, has the
right to quit work if he wants to. That is what I call striking—quitting
work.
Q. Doing anything more?
A. We have no right to destroy property.
Q. Do you claim it as a right to interfere with those who want to
work?
A. It is a right to use mere suasion. If I were to see you rushing on
headlong on the breakers, and I can stop you, I would do so.
Q. Do you claim that you have a right to assemble in crowds or
groups upon the property of the railroad company?
A. If that is where we are employed; yes.
Q. But when you strike, you are no longer in the employ of the
railroad company?
A. No; not when we have once struck.
Q. Then after you have struck you don't claim that you have the
right to assemble there?
A. Until we are ordered off?
Q. But when ordered off, have you the right to refuse to go?
A. It depends greatly upon who orders you off.
Q. When ordered off by an official of the railroad company?
A. If I am there for any unlawful purpose, I ought to go, but if I am
not there for any unlawful purpose, and if I run against a man who
wants to show fight or ride a big horse, I don't think I have any
business to go, if I want to stay.
By Senator Reyburn:
Q. But do you say that you have the right to go on another man's
property and stay there if he wants you to go away?
A. I don't recognize any one like a day dispatcher. It is not his
business.
Q. But it is his business to keep the track clear?
A. No; it is not.
By Mr. Lindsey:
Q. You did assemble at yard of the Fort Wayne and Chicago road,
one hundred and fifty or two hundred of you?
A. Yes.
Q. Were you ordered off—ordered to leave or disperse?
A. No; directly we were not.
Q. By any one belonging to the road?
A. The dispatcher told the chief of police to disperse this mob, that
they were not employés of the Fort Wayne road, but rioters and
loafers from Pittsburgh, and wouldn't allow their men to work.
Q. You resisted this? You refused to go?
A. I don't like a man to call me a liar.
Q. Did you refuse to go?
A. No one told me to go off the property.
Q. Didn't the policemen tell you to go?
A. No.
Q. Didn't they undertake to disperse you?
A. They got in amongst us, but they didn't push or tell us to go off.
Q. But you refused to go?
A. We didn't understand it that way.
Q. Was it not your duty to disperse when the policemen requested
you, having been instructed so to do by the officials of the railroad
company?
A. The police didn't tell us to disperse.
Q. You knew what they came among you for, and what commands
had been given to them by the officers of the railroad company?
A. I heard the dispatcher say, disperse this lot of loafers and rioters
from Pittsburgh. I don't know that he spoke to me.
Q. Did he refer to the crowd?
A. I don't know of any loafers or bummers in that crowd.
By Senator Yutzy:
Q. Were you ordered to disperse by anybody?
A. No; the dispatcher didn't speak to us, but to the chief of police,
that these men are a lot of rioters from Pittsburgh, and he wanted
them off the property.
By Mr. Lindsey:
Q. Did you consider you had the right to take that property and pack
it away on the side tracks?
A. I thought I did perfectly right.
Q. If it was in danger of being destroyed?
A. Everybody appeared to be excited, and they had lost their heads,
so that you couldn't get them to do anything. There were some
passenger and freight cars, and a lot of cars loaded with live stock
standing on one track, and nobody appeared to know what to do
with them. People came to me and asked what to do, from even the
dispatcher himself—he looked to me.
Q. But after you had refused to work, had you any right to interfere
with that property?
A. We didn't interfere with the property.
Q. Had you any right to do anything with it?
A. If we were asked to do it we had.
Q. Had you any right to interfere with that property in any way?
A. Yes.
Q. You understand what I mean by my question? Do you not think it
was your duty, after having refused to work, to leave the premises
entirely and go away?
A. That depends on circumstances.
Q. But if you were working for a man and stopped work, or he
turned you off, have you any right to remain around?
A. That depends a great deal on whether he wants me around or
not.
Q. But have you any right to interfere with his property in any way,
under any circumstances?
A. I would think I was a very foolish man. If my property was in
danger I would like him to come and lend a hand.
Q. I didn't ask any question about the property being in danger?
A. We didn't interfere with the property in any way or manner.
By Mr. Means:
Q. Had the commander of the military refused an interview with you,
or the party you represent, what would have been the consequences
—what was your determination?
A. I don't know as we figured that far ahead.
Q. But you must have had some plan, sir?
A. I didn't happen to meet him, therefore, I cannot tell you.
Q. I want to know what was your determination?
A. That is something nobody knows.
Q. I insist upon an answer?
A. It is a question I cannot answer.
Q. This is the question. Had the commander of the military refused
to have an interview with you or the party you represent, what was
your determination—what did you intend to do?
A. That would have depended greatly on circumstances. I don't
know what we would have done.
By Mr. Lindsey:
Q. Did you intend to resist the militia?
A. If you or any other man or the militia had raised a gun to shoot
me, I undoubtedly would have resisted.
Q. But answer yes or no, then explain after answering the question?
A. What is the question?
Q. Did you intend to resist the militia had they attempted to disperse
the crowd?
A. I will have to answer the question yes and no. If they had come
with the requisite authority from the Governor of the State and
ordered us to disperse, undoubtedly we would have obeyed them. If
they had authority from the Governor of the State, I, for one, would
have walked away.
Q. But suppose they had authority from General Latta?
A. I didn't recognize him.
Q. You didn't recognize him?
A. I didn't at that time.
Q. Certainly you couldn't have been a law-abiding citizen if you
didn't?
A. I didn't at that time.
By Mr. Lindsey:
Q. Then you intended to use your own judgment as to whether the
militia were there lawfully or unlawfully?
A. I look upon General Huidekoper as a gentleman, and don't think
he would lie.
Q. Suppose he had said he was there on authority from the
Governor?
A. I told you I would have gone off the premises and walked away.
If he had told me it was none of my business, I would have told him
I would make it my business. If he had told me he was there by
authority of some railroad official, I would have told him that the
best thing he could do for his own and for our sake, would be to
take the back track, and go away.
Q. Did you see the daily papers of that week?
A. No; I don't believe I did.
Q. Did you see a published proclamation of the Governor's?
A. I don't believe I did.
Q. Did you know a proclamation had been issued?
A. I had heard of it.
Q. Commanding all citizens to disperse?
A. I had heard of it, but I didn't read it.
By Mr. Means:
Q. Then you and your party were to be the judges, whether or not
General Latta had authority or not?
A. We were open to conviction. We thought we were endowed with
a little common sense.
Q. I don't doubt it for a moment—not at all. But you were to be the
judges whether General Latta had authority or not?
A. The way I came to get under that impression—an attorney, the
first day of the strike, who was around there when this question
came up about the Governor being out of the State, said that the
troops or military could not be ordered out, because the Governor
was not here.
Q. Give us his name?
A. I cannot give it.
Q. I insist upon it?
A. I refuse to answer the question.
Q. If the committee insists upon an answer you certainly will have to
answer, because you have sworn to tell the truth?
A. Well, I well give the committee the names of any of these parties
in confidence, but I don't care about telling their names to the
world. I am perfectly willing to give them to the committee in
confidence. I don't want to keep anything back, but I don't want to
tell tales on anybody else.
By Senator Reyburn:
Q. Did your association have an attorney employed—the Trainmen's
Union?
A. Two or three were around there, sort of acting as though they
were employed, but we never knew who employed them.
Q. Did you consult with them?
A. No; they came there and gave us advice.
By Senator Yutzy:
Q. Gratuitously?
A. That is about it.
By Mr. Lindsey:
Q. Were they ever paid any fees?
A. Not that I know of.
By Senator Reyburn:
Q. Were they practicing attorneys at the bar?
A. Yes.
By Mr. Lindsey:
Q. You continued to keep up the strike there, and hold possession of
the railroad property, until the arrival of the Governor of the State,
did you not?
A. I believe we were on the premises when the Governor arrived.
Q. And had possession of the property of the railroad?
A. I don't know. The property was all lying there. No one was
holding it?
Q. But didn't you guard it. Didn't you exercise care of it, and didn't
you afterwards deliver it over to the railroad officials?
A. Yes; we told them that we wouldn't have anything more to do
with it, that they must get somebody else to watch it.
Q. Who did you deliver it to?
A. A man I did not recognize came down and took possession for
Mayor Phillips or his police.
Q. You surrendered the property to him?
A. No, sir; I did not, but to the officers of the road.
Q. What day was that?
A. That was the evening the Governor came in.
Q. The evening the Governor arrived?
A. Yes.
Q. Did you have any interview with the Governor on his arrival?
A. Yes.
Q. Tell us what that was?
A. I had a little talk with him and passed the compliments of the day,
and asked him to come out and say a few words to the boys, and he
came out on the back platform and said something to them. We
then passed on to the round-house, where there was a crowd of
some five or six hundred, and he spoke a few words to them, and
then went on to the city of Allegheny, where the citizens met him
with a carriage and took him to Pittsburgh, by the suspension
bridge.
By Senator Yutzy:
Q. Did you telegraph to him?
A. I did.
By Mr. Lindsey:
Q. What was the nature of those telegrams?
A. Some of them are part of history. I telegraphed along the line not
to interfere with the train he was on, so as not to get him angry with
us, and I telegraphed him guaranteeing him a safe passage to
Allegheny city.
Q. You had the power to give him a safe passage through?
A. My name was good enough at that time.
Q. Over the length of the Fort Wayne and Chicago road?
A. Yes.
Q. You controlled the road at that time?
A. It appeared that they were not going to recognize any man's
orders but mine.
By Senator Reyburn:
Q. But they got obstreperous at last on your hands?
A. Towards the last.
Q. Didn't you go to a meeting with some citizens to a hall?
A. Yes.
Q. And there they thought you were taking too much authority on
you?
A. They thought I was going back on them. At least a scab did. He
supposed I was misrepresenting things at that time. At least I think
so now. They were starving, and wanted coal, and I ordered a
provision train and a coal train out, and one fellow wanted to kill me
right off.
By Mr. Lindsey:
Q. So they struck on you?
A. Yes; this was the following Thursday. I had not been down from
the Tuesday night when the Governor arrived until this afternoon of
Thursday.
By Senator Yutzy:
Q. What means did you take to enforce your orders after they struck
on you?
A. They did not strike on me.
By Mr. Lindsey:
Q. Didn't they refuse to obey your orders?
A. I had ceased to exist at that time. That was on the Tuesday night,
and this meeting was on Thursday afternoon. Because I would not
come up, I suppose they felt sick and sore, and thought I was trying
to sell them out.
By Senator Reyburn:
Q. Those citizens you talked about who offered you arms, were not
those men the ones who went with you to the meeting?
A. Neither one of them was there.
Q. Didn't they ask you to protect this property, and after a
conversation with you, didn't you agree to go with them to this
meeting and talk to the rioters?
A. There were no rioters on the Fort Wayne road.
Q. Or the strikers?
A. Yes.
Q. Didn't you promise them to keep order, and in consideration of
that didn't they agree to give you the arms to keep off the mob in
case any party came to burn the town?
A. No, sir; this was on the Thursday after the fire. I was at no
meeting from the 27th day of June until this Thursday.
By Mr. Larrabee:
Q. Was there no understanding between you and the strikers on the
Pennsylvania road during this time, after you got back to Allegheny
City and took charge of things—were you acting in concert in
preventing trains from going out?
A. I don't know that anything particular of that kind was agreed
upon. Of course we talked over things of that kind.
Q. But you had communications with the parties who were striking
on the Pennsylvania road?
A. Yes; men were going back and forth all the time.
Q. Was there anybody over there that had control of the strike there
or who was looked up to as a leader or recognized as such?
A. There were some three or four of them. The man supposed to be
the leader showed the white feather.
Q. Who was that?
A. Samuel Muckle, the president of the Pan Handle division.
Q. He was supposed to be the leader in the start?
A. Yes.
Q. Who was their leader after he showed the white feather?
A. I don't know, but I think Hice. He was at Torrens station.
By Senator Yutzy:
Q. How did he show the white feather?
A. He was a man who didn't live up to what he said he would do.
Q. In what respect?
A. He didn't live up to what he said he would do at the meeting.
Q. What did he agree to do in the first place?
A. He agreed to stand by the boys.
Q. What were the boys to do?
A. If the boys went out on a strike, Muckle was to stand by them.
Q. And prevent the running of trains?
A. The understanding was that every man was to quit work and go
away, but not to prevent the running of trains. Muckle was
discharged, and he tried to get a job in the employ of the road. His
object in getting the men to strike was to get them out and then
come in and scab it.
Q. That is, come in and offer his services to the railroad?
A. Yes.
By Mr. Larrabee:
Q. But were communications going on between you and the leaders
of the Pennsylvania road—the leaders of the strike? Was there any
concerted movement or action between you?
A. No, sir.
By Senator Yutzy:
Q. Give us a definition of your idea of a strike. What is generally
understood by railroad men, or what did the Trainmen's Union
understand by a strike?
A. So far as the Trainmen's Union was concerned, we considered by
a strike that every man on the three grand trunk lines should go
home when the hour came—just leave his train standing there.
Q. You mean refuse to work?
A. Yes.
Q. Nothing more?
A. That was our understanding.
Q. But you were not to prevent other men from working?
A. We had an understanding if a man was not a union man to coax
him off if we could.
Q. But if he would not be coaxed?
A. Then to leave him stay. We considered that his own conscience
would be enough for him.
Q. But you were not to try to drive him off?
A. No; a man who is a scab has a hard enough time of it. He has a
hard time enough of it to make his life unbearable to him.
Q. Was any violence used that you know of to prevent trains from
running on the Fort Wayne and Chicago railroad?
A. No, sir; none was used. I would not have allowed, so far as I was
concerned.
Q. By what authority did you assume charge of the Fort Wayne and
Chicago railroad?
A. I think I assumed authority of the Fort Wayne from telegrams I
received from Mr. Layng, who is the general manager from
Pittsburgh to Chicago.
Q. What were those telegrams?
A. I was asked to take charge of the trains and engines, and to
move them to places of safety.
Q. Have you those dispatches?
A. I have.
Q. Have you them here?
A. No.
Q. Can you produce them?
A. I can, sir.
Q. Will you produce them?
A. Not in this city.
Q. Where will you produce them?
A. I will produce them anywhere where I can get them. I asked to
have them sent here, but could not get them.
By Mr. Larrabee:
Q. Would this strike on the Fort Wayne and Chicago road have
occurred if the strike on the Pennsylvania road had not occurred at
that time?
A. That is a pretty hard question to answer.
Q. From your information—from what you know of the
circumstances and the men engaged in it?
A. I have not thought over that, and really I cannot give an answer.
Q. Do you know whether the men on the Fort Wayne and Chicago
road were making any preparations for a strike distinct from any
strike upon the Pennsylvania railroad?
A. Some of them were and some of them were not.
Q. At this particular time that the strike occurred?
A. Really, I have never thought the matter over, and I cannot answer
that question, because I have not thought it over in that light at all.
They may have and they may not.
Q. You say that the main cause of the strike on the Pennsylvania
road was the running of double-headers?
A. That is my impression.
Q. The cause of the strike upon the Fort Wayne road at that time
was what?
A. Several things combined. I think it was the abuse of power by the
under officials more than anything else.
Q. That and the ten per cent.?
A. Yes; that was pretty hard to swallow.
By Senator Reyburn:
Q. I understood you to say in talking to some citizens you had given
some figures as to the wages that could be earned after the ten per
cent. reduction. Can you give those figures to the committee now?
A. I didn't state the amount that could be earned, but the amount
they were paying—brakeman, $1 45.
Q. Per day?
A. Per trip, that is called a day.
By Mr. Englebert:
Q. How many hours?
A. The shortest run on the road was seven hours and twenty-five
minutes. The longest run was eight hours and thirty-five minutes.
Firemen the same as brakemen. Conductors, first class, $2 12;
second class, $1 89 or $1 91, I forget which. Engineers—I don't
remember the classified pay—first class, three dollars and eleven or
twelve cents. That had a great deal to do with the strike—the
classification—so far as the engineers were concerned.
By Mr. Lindsey:
Q. How many days could you average per week?
A. The year around, or at that time?
Q. At that time?
A. I think the month that I was discharged I drew twenty-nine
dollars and some cents—I don't know what.
By Senator Yutzy:
Q. As brakeman?
A. Yes. I had an income of forty dollars a month besides that, and it
was the only way I could live.
By Mr. Lindsey:
Q. Did you make all the time?
A. I believe I did. I believe I lost only one trip. My impression is I did
lose one trip.
By Senator Reyburn:
Q. Was not the amount you could earn governed by the amount of
business doing by the road at that time—if the freight shipments
were large you all got work?
A. We all had work any how. We all came in our turn.
Q. But the amount of money you made depended on the amount of
the business of the road?
A. Yes.
By Mr. Lindsey:
Q. You put in your six days a week—work a week at $1 40?
A. I undoubtedly worked six days.
Q. Every week?
A. Not at that time. We were not averaging six days' work at that
time.
Q. Were you prior to that time?
A. Really I have forgot; but the pay was running very poor. I think
the business was good in January and February, March and April, but
I think after that time it was very slack.
By Senator Yutzy:
Q. How many days did you make in any one month?
A. In the month of January I made forty-four days.
Q. By over work?
A. Yes.
By Senator Reyburn:
Q. Did not the officials, when you sent your committee to them,
didn't they talk over this matter with you?
A. Before the strike?
Q. Yes.
A. No, sir.
Q. Didn't you send a committee down to Philadelphia to see Mr.
Scott?
A. Of engineers, I believe. We heard what the engineers were doing,
and got enough of the engineers. They generally patched things up
for themselves. They didn't look after anything else. It was about the
time of taking the ten per cent. off.
By Mr. Engelbert:
Q. What position did you hold in Trainmen's Union?
A. I don't know that I held any position. I was appointed to organize
the unions, and had unlimited powers.
By Senator Yutzy:
Q. By whom?
A. By what we called—there were members appointed from each
division, and they constituted a sort of grand lodge. The division I
belonged to was first organized. That is where I got my power from.
They sent me right out. It was a Saturday night, and I left Pittsburgh
the following Monday, June 4.
Q. Who organized the first lodge?
A. I was the first man to take an oath. I guess all took a hand in it.
Q. Were you president of that lodge?
A. There was no president of that lodge at that time.
Q. Were you chief of that lodge?
A. I suppose I was that night.
Q. What did they call the chief of that lodge—what name?
A. The grand organizer.
Q. Then by delegations from other lodges, you were appointed to
organize lodges throughout the country?
A. Our lodge gave me authority, and as we formed lodges, they sent
in delegations to form a grand lodge, and they confirmed the action
of our lodge.
By Mr. Larrabee:
Q. Who paid your expenses going around?
A. The boys.
Q. As a union or a society, or did the boys contribute what they saw
fit?
A. All the money I ever got, I got from the union at that time.
By Mr. Lindsey:
Q. From the lodge?
A. Yes; from the treasurer of the lodge.
By Senator Yutzy:
Q. Was it an oath-bound association?
A. Yes.
By Mr. Means:
Q. Did you go to Martinsburg, Virginia?
A. I was in that neighborhood.
Q. Were you at Martinsburg, Virginia?
A. I was very near to it.
Q. That is not an answer to my question.
A. At what time?
Q. To organize a lodge there before the strike?
A. I did initiate men into the organization called the Trainmen's
Union, at Martinsburg.
By Senator Yutzy:
Q. Did you organize lodges over the Baltimore and Ohio road?
A. Yes.
By Mr. Means:
Q. Was it understood by your lodges that this strike was to
commence at Martinsburg?
A. No, sir.
Q. Did you know, before the strike commenced at Martinsburg,
Virginia, that it was going to take place?
A. No; of course I heard all that talk. They talked most loud at
Martinsburg, but I thought it was all wind. I didn't think they would
strike at all.
By Senator Yutzy:
Q. When you were telegraphed at Oil City, were you there for the
purpose of organizing lodges?
A. It was Parker City.
Q. Were you there for the purpose of organizing lodges?
A. At that time?
Q. Yes?
A. I went up there to get work.
By Mr. Lindsey:
Q. How long had you been railroading?
A. About eleven months altogether.
Q. What had been your business before that?
A. I was in the hotel business.
Q. Where?
A. At Collinwood, eight miles from Cleveland.
Q. Were you proprietor of the hotel?
A. Yes.
Q. For how long?
A. One year and nine months.
Q. What was your business before that?
A. I was in the insurance business.
Q. Where?
A. At Pittsburgh.
Q. Is that your home?
A. Yes; it is my native place.
By Senator Yutzy:
Q. Were you working for your father or for yourself in the insurance
business?
A. I represented four Chicago companies for myself.
Q. When you returned from the oil country, you say you met some
railroad men who belonged to the Baltimore and Ohio railroad?
A. Of the Connellsville division.
Q. Where did you meet them?
A. Around the Union depot.
Q. How many of them did you meet there?
A. I remember three engineers who were there.
Q. Any other trainmen?
A. O, yes.
Q. Of the Baltimore and Ohio road?
A. These three engineers are all I can remember.
Q. Were they the ones who telegraphed to you to come to
Pittsburgh?
A. No.
Q. Where did those men belong to—the Baltimore and Ohio or the
Pennsylvania Central? Who telegraphed you?
A. To neither road.
Q. Of what road were they employés?
A. Of the Fort Wayne road.
By Mr. Dewees:
Q. How many miles of railroad had this trouble?
A. I never figured it up. A good many miles.
By Senator Reyburn:
Q. You had a signal to stop trains?
A. You can stop any train if you have the signal.
Q. But did not your organization have a particular signal by which
you could stop the trains?
A. The Trainmen's Union?
Q. Yes?
A. Before the strike?
Q. Yes?
A. No, sir.
By Senator Yutzy:
Q. Different from the ordinary signal?
A. I don't comprehend the question exactly.
By Senator Reyburn:
Q. Was not there an understood signal among the trainmen by
which, if an engineer of a train undertook to run it, they would throw
him this signal, and he would stop the train and get off?
By Senator Yutzy:
Q. Some peculiar signal?
A. No; I saw lots of engineers that wanted the boys to do that.
By Mr. Larrabee:
Q. You say then that there was no signal?
A. No.
Welcome to our website – the perfect destination for book lovers and
knowledge seekers. We believe that every book holds a new world,
offering opportunities for learning, discovery, and personal growth.
That’s why we are dedicated to bringing you a diverse collection of
books, ranging from classic literature and specialized publications to
self-development guides and children's books.
More than just a book-buying platform, we strive to be a bridge
connecting you with timeless cultural and intellectual values. With an
elegant, user-friendly interface and a smart search system, you can
quickly find the books that best suit your interests. Additionally,
our special promotions and home delivery services help you save time
and fully enjoy the joy of reading.
Join us on a journey of knowledge exploration, passion nurturing, and
personal growth every day!
ebookbell.com

More Related Content

PPT
ow.ppt
PPT
kjdiakdnfdifjadsjkjklljlldasgjdjdljgfldjgldjgldjgl.ppt
PPT
Plantilla oracle
PPT
ow-123123123123123123123123123123123123123
PPT
Rajnish singh(presentation on oracle )
PPT
Oracle database connection with the .net developers
ow.ppt
kjdiakdnfdifjadsjkjklljlldasgjdjdljgfldjgldjgldjgl.ppt
Plantilla oracle
ow-123123123123123123123123123123123123123
Rajnish singh(presentation on oracle )
Oracle database connection with the .net developers

Similar to Odpnet Developers Guide Oracle Database 10g Development With Visual Studio 2005 And The Oracle Data Provider For Net Jagadish Pulakhandam Sunitha Paruchuri (20)

PPTX
Ado .net
PDF
(Ebook) Java Programming with Oracle JDBC by Donald Bales ISBN 9780596000882,...
PPT
Oracle Intro.ppt
PDF
Java Programming With Oracle Jdbc 1st Ed Donald Bales
PDF
Download full ebook of Oracle Sql Developer Narayanan Ajith instant download pdf
PPT
Apex ace update
PPT
PPTX
Oracle database introduction
PDF
(Ebook) Java Programming with Oracle JDBC by Donald Bales ISBN 9780596000882,...
PDF
Oracle Essentials Oracle Database 12c Fifth Edition Rick Greenwald download pdf
PDF
Oracle Essentials Oracle Database 12c Fifth Edition Rick Greenwald 2024 scrib...
PPTX
Oracle SQL Developer Data Modeler - for SQL Server
PPT
Chapter 4 event it theory programming.pptx
PDF
Whitepaper - Information management with oracle
PDF
Oracle 10g sql fundamentals i
DOC
DBMS Practical File
PPTX
111111112222223333335555555666Unit-4.pptx
PPT
Toc d17090 gc30
PDF
Oracle Sql Developer 21 Database Design And Development Using This Featureric...
Ado .net
(Ebook) Java Programming with Oracle JDBC by Donald Bales ISBN 9780596000882,...
Oracle Intro.ppt
Java Programming With Oracle Jdbc 1st Ed Donald Bales
Download full ebook of Oracle Sql Developer Narayanan Ajith instant download pdf
Apex ace update
Oracle database introduction
(Ebook) Java Programming with Oracle JDBC by Donald Bales ISBN 9780596000882,...
Oracle Essentials Oracle Database 12c Fifth Edition Rick Greenwald download pdf
Oracle Essentials Oracle Database 12c Fifth Edition Rick Greenwald 2024 scrib...
Oracle SQL Developer Data Modeler - for SQL Server
Chapter 4 event it theory programming.pptx
Whitepaper - Information management with oracle
Oracle 10g sql fundamentals i
DBMS Practical File
111111112222223333335555555666Unit-4.pptx
Toc d17090 gc30
Oracle Sql Developer 21 Database Design And Development Using This Featureric...
Ad

Recently uploaded (20)

PDF
01-Introduction-to-Information-Management.pdf
PDF
Supply Chain Operations Speaking Notes -ICLT Program
PPTX
Microbial diseases, their pathogenesis and prophylaxis
PDF
2.FourierTransform-ShortQuestionswithAnswers.pdf
PPTX
Final Presentation General Medicine 03-08-2024.pptx
PDF
O5-L3 Freight Transport Ops (International) V1.pdf
PDF
Computing-Curriculum for Schools in Ghana
PPTX
Institutional Correction lecture only . . .
PPTX
master seminar digital applications in india
PDF
Pre independence Education in Inndia.pdf
PDF
Basic Mud Logging Guide for educational purpose
PPTX
human mycosis Human fungal infections are called human mycosis..pptx
PDF
Sports Quiz easy sports quiz sports quiz
PDF
VCE English Exam - Section C Student Revision Booklet
PPTX
Cell Types and Its function , kingdom of life
PDF
Physiotherapy_for_Respiratory_and_Cardiac_Problems WEBBER.pdf
PPTX
GDM (1) (1).pptx small presentation for students
PDF
102 student loan defaulters named and shamed – Is someone you know on the list?
PPTX
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
PPTX
1st Inaugural Professorial Lecture held on 19th February 2020 (Governance and...
01-Introduction-to-Information-Management.pdf
Supply Chain Operations Speaking Notes -ICLT Program
Microbial diseases, their pathogenesis and prophylaxis
2.FourierTransform-ShortQuestionswithAnswers.pdf
Final Presentation General Medicine 03-08-2024.pptx
O5-L3 Freight Transport Ops (International) V1.pdf
Computing-Curriculum for Schools in Ghana
Institutional Correction lecture only . . .
master seminar digital applications in india
Pre independence Education in Inndia.pdf
Basic Mud Logging Guide for educational purpose
human mycosis Human fungal infections are called human mycosis..pptx
Sports Quiz easy sports quiz sports quiz
VCE English Exam - Section C Student Revision Booklet
Cell Types and Its function , kingdom of life
Physiotherapy_for_Respiratory_and_Cardiac_Problems WEBBER.pdf
GDM (1) (1).pptx small presentation for students
102 student loan defaulters named and shamed – Is someone you know on the list?
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
1st Inaugural Professorial Lecture held on 19th February 2020 (Governance and...
Ad

Odpnet Developers Guide Oracle Database 10g Development With Visual Studio 2005 And The Oracle Data Provider For Net Jagadish Pulakhandam Sunitha Paruchuri

  • 1. Odpnet Developers Guide Oracle Database 10g Development With Visual Studio 2005 And The Oracle Data Provider For Net Jagadish Pulakhandam Sunitha Paruchuri download https://ebookbell.com/product/odpnet-developers-guide-oracle- database-10g-development-with-visual-studio-2005-and-the-oracle- data-provider-for-net-jagadish-pulakhandam-sunitha- paruchuri-4104880 Explore and download more ebooks at ebookbell.com
  • 2. Here are some recommended products that we believe you will be interested in. You can click the link to download. Odpnet Developers Guide Oracle Database 10g Development With Visual Studio 2005 And The Oracle Data Provider For Net A Practical Guide For Developers Developer Tools For Visual Studio 2005 1st Ed Jagadish Chatarji Pulakhandam https://ebookbell.com/product/odpnet-developers-guide-oracle- database-10g-development-with-visual-studio-2005-and-the-oracle-data- provider-for-net-a-practical-guide-for-developers-developer-tools-for- visual-studio-2005-1st-ed-jagadish-chatarji-pulakhandam-1213244 Pro Odpnet For Oracle Database 11g 2nd Edition Edmund Zehoo Yap Wai Hong https://ebookbell.com/product/pro-odpnet-for-oracle-database-11g-2nd- edition-edmund-zehoo-yap-wai-hong-33448242 Pro Odpnet For Oracle Database 11g 1st Edition Edmund Zehoo Yap Wai Hong https://ebookbell.com/product/pro-odpnet-for-oracle-database-11g-1st- edition-edmund-zehoo-yap-wai-hong-34783930 Building Enterprise Systems With Odp An Introduction To Open Distributed Processing Linington https://ebookbell.com/product/building-enterprise-systems-with-odp-an- introduction-to-open-distributed-processing-linington-4393208
  • 3. Building Enterprise Systems With Odp An Introduction To Open Distributed Processing 1st Edition Peter F Linington https://ebookbell.com/product/building-enterprise-systems-with-odp-an- introduction-to-open-distributed-processing-1st-edition-peter-f- linington-4440298
  • 4. ODP.NET Developer's Guide Oracle Database 10g Development with Visual Studio 2005 and the Oracle Data Provider for .NET A practical guide for developers working with the Oracle Data Provider for .NET and the Oracle Developer Tools for Visual Studio 2005 Jagadish Chatarji Pulakhandam Sunitha Paruchuri BIRMINGHAM - MUMBAI
  • 5. ODP.NET Developer's Guide Oracle Database 10g Development with Visual Studio 2005 and the Oracle Data Provider for .NET Copyright © 2007 Packt Publishing All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews. Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the authors, Packt Publishing, nor its dealers or distributors will be held liable for any damages caused or alleged to be caused directly or indirectly by this book. Packt Publishing has endeavored to provide trademark information about all the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information. First published: June 2007 Production Reference: 1150607 Published by Packt Publishing Ltd. 32 Lincoln Road Olton Birmingham, B27 6PA, UK. ISBN 978-1-847191-96-0 www.packtpub.com Cover Image by www.visionwt.com
  • 6. Table of Contents Preface 1 Chapter 1: Introduction to ODP.NET 5 Introduction to ODP.NET 5 Why Use ODP.NET? 7 Oracle Database Access from .NET Applications 7 What Do We Require to Work with ODP.NET? 9 Introduction to Oracle Database Extensions for .NET 10 Oracle Database Extensions for .NET 10 How does .NET Work within Oracle Database? 10 Processing of .NET Stored Procedure with Oracle 11 Introduction to Oracle Developer Tools for Visual Studio 11 Summary 13 Chapter 2: Connecting to Oracle 15 Provider-Independent Model in ADO.NET 2.0 15 Listing All Installed .NET Data Providers 16 Enumerating all Oracle Data Sources Available 17 Connecting to Oracle Databases from .NET 19 Connecting Using .NET Data Provider Factory Classes 20 Connecting Using .NET Data Provider for OLEDB 22 Connecting Using .NET Data Provider for ODBC 23 Connecting using Microsoft's .NET Data Provider for Oracle 24 Connecting Using Oracle Data Provider for .NET (ODP.NET) 25 Connecting with Connection Pooling 27 Connecting with System-Level Privileges or DBA Privileges 28 Dynamic Connecting String Using OracleConnectionStringBuilder and app.config29 Embedding a tnsnames.ora Entry-like Connection String 31 Connecting to a Default Oracle Database 32 Connecting Using Windows Authentication (Single Sign‑On) 33 Summary 35
  • 7. Table of Contents [ ii ] Chapter 3: Retrieving Data from Oracle Using ODP.NET 37 Fundamental ODP.NET Classes to Retrieve Data 37 Retrieving Data Using OracleDataReader 39 Retrieving a Single Row of Information 39 Using Using for Simplicity 42 Retrieving Multiple Rows on to the Grid 43 Pulling Information Using Table Name 46 Retrieving Typed Data 47 Working with Data Tables and Data Sets 48 Retrieving Multiple Rows into a DataTable Using OracleDataAdapter 48 Filling a DataTable Using OracleDataReader 51 Retrieving a Single Row of Information Using OracleDataAdapter 52 Working with DataTableReader 54 Populating a Dataset with a Single Data Table 55 Populating a Dataset with Multiple Data Tables 56 Presenting Master-Detail Information Using a Dataset 58 More About the OracleCommand Object 61 Retrieving a Single Value from the Database 61 Handling Nulls when Executing with ExecuteScalar 62 Handling Nulls when Working with OracleDataReader 63 Working with Bind Variables together with OracleParameter 64 Working with OracleDataAdapter together with OracleCommand 66 Techniques to Improve Performance while Retrieving Data 67 Summary 69 Chapter 4: Manipulating Data in Oracle Using ODP.NET 71 Executing DML or DDL Statements Using OracleCommand 71 Using INSERT with OracleCommand 72 Using UPDATE with OracleCommand 73 Using DELETE with OracleCommand 75 Multiple Inserts Using Statement Caching 76 Multiple Inserts Using Array Binding 78 Creating an Oracle Table Dynamically Using ODP.NET 81 Updating Offline Data to the Database Using OracleDataAdapter 82 Working with OracleCommandBuilder and OracleDataAdapter 84 Working with Transactions Using ODP.NET 86 Handling Oracle Errors and Exceptions 88 Displaying a Single or First Error 88 Displaying Multiple Errors 89 Summary 92
  • 8. Table of Contents [ iii ] Chapter 5: Programming ODP.NET with PL/SQL 93 Working with Anonymous PL/SQL Blocks 93 Executing Anonymous PL/SQL Blocks 94 Passing Information to Anonymous PL/SQL Blocks 95 Retrieving Information from Anonymous Blocks 96 Working with PL/SQL Stored Procedures and Functions 98 Executing a PL/SQL Stored Procedure 98 Passing Parameter Values to a PL/SQL Stored Procedure 100 Using an Anonymous PL/SQL Block to Execute a PL/SQL Stored Procedure102 Retrieving Output Parameters from a PL/SQL Stored Procedure 103 Passing IN and Getting OUT Simultaneously 105 Handling User-Defined Application Errors 107 Executing a PL/SQL User-Defined Function 109 PL/SQL Packages, Tables, and REF CURSOR 111 Executing Routines in a PL/SQL Package 111 Executing a Procedure in a PL/SQL Package 112 Executing a User-Defined Function in a PL/SQL Package 114 Passing Arrays to and Receiving Arrays from Oracle Database 116 Sending an Array to Oracle Database 116 Receiving an Array from Oracle Database 119 Working with REF CURSOR Using ODP.NET 122 Pulling from REF CURSOR Using OracleDataReader 122 Filling a Dataset from REF CURSOR 125 Working with Multiple Active Result Sets (MARS) 126 Summary 130 Chapter 6: Dealing with Large Objects (LOBs) 131 Working with BFILEs 131 Setting Up the Environment to Work with BFILEs 132 Adding a New Row Containing BFILE 133 Updating an Existing BFILE Row 135 Retrieving BFILE Information from a Database 136 Retrieving Properties of a BFILE 138 Working with CLOBs 140 Inserting Huge Text Information into Oracle Database 140 Updating CLOB Information Using OracleClob 142 Retrieving CLOB Information from Oracle Database 143 Reading a Text File and Uploading as CLOB 144 Working with BLOBs 147 Setting Up the Environment to Work with BLOBs 148 Uploading Images to Oracle Database Using BLOB 150
  • 9. Table of Contents [ iv ] Retrieving Images from Oracle Database Using BLOB 153 Uploading Documents to and Retrieving Documents from Oracle Database 154 Summary 158 Chapter 7: XML and XML DB Development with ODP.NET 159 A Fast Track on XML with Oracle 160 Generating XML from Existing Rows in Tables 163 Generate XML Using ADO.NET DataSet 163 Generate XML Using ExecuteXMLReader 164 Generate XML Using DBMS_XMLGEN 166 Converting Rows to HTML Using XML and XSLT 167 Manipulating Rows in a Table Using XML 171 Inserting Rows into Oracle Using XML 171 Updating Rows into Oracle Using XML 174 Working with Native XML in Oracle Database 175 Inserting XML Data into XMLType Using Traditional INSERT 175 Updating XML Data in XMLType Using Traditional UPDATE 177 Inserting XML Data Using OracleXmlType 178 Retrieving and Updating XML Data Using OracleXmlType 179 Extracting Individual Node Information of an XMLType Value 181 Summary 183 Chapter 8: Application Development Using ODP.NET 185 Notifying Applications of Database Changes 185 Catching Notifications 186 Catching Multiple Notifications 189 Identifying Rows Modified During Notifications 190 Developing Long-Running Applications 193 The Devil of Applications: Not Responding 194 Asynchronous Task with Multi-Threading 195 Developing Web Applications Using ASP.NET and ODP.NET 199 Web Development Using Smart Data Binding 199 Populating an ASP.NET DropDownList Control 199 Linking an ASP.NET GridView Control with a DropDownList Control 207 Add, Update, or Delete a Row Using GridView and FormView 212 Working with Web Controls Manually 218 Developing Web Reports Using ASP.NET 221 Creating a Strongly-Typed Dataset Using Designer 221 Designing and Binding a Report to the Dataset 224 Grouping and Displaying Sub-Totals 228 Embedding Charts (Graphs) in Reports 232
  • 10. Table of Contents [ ] Object-Oriented Development Using ASP.NET and ODP.NET 235 Developing a Simple Oracle Database Helper Class 236 Developing a Simple Business Logic Class 238 Working with ObjectDataSource in an ASP.NET 2.0 Web Form 241 Developing Web Services Using ODP.NET 247 Creating the .NET XML Web Service 247 Consuming the Web Service from ASP.NET 255 Developing Smart Device Applications 259 Introducing Microsoft Windows Mobile 259 Consuming a Web Service from Pocket PC 260 Summary 263 Chapter 9: Introduction to Oracle Developer Tools for Visual Studio 2005265 Features of Oracle Developer Tools 265 Connecting to Oracle from Visual Studio Using Oracle Explorer 266 Retrieving Oracle Information from Visual Studio Using ODT 270 Working with Oracle Database Objects from Visual Studio Using ODT 274 Dealing with Tables, Views, and Sequences Using ODT 274 Creating Stored Procedures Using ODT 277 Debugging PL/SQL Stored Procedures from Visual Studio 279 .NET CLR Stored Procedures in Oracle 289 Taking Advantage of Automatic .NET Code Generation 296 Summary 307 Index 309
  • 11. Preface Oracle's ODP.NET is a .NET data provider that can connect to and access Oracle databases with tight integrity. It can be used from any .NET language, including C# and VB.NET. This book will show you how ODP.NET is the best choice for connecting .NET applications with Oracle database. We will be dealing with the concepts of ODP.NET and its requirements, working with SQL, PL/SQL, and XML DB using ODP.NET, looking at application development with ODP.NET: Web Applications, Web Services, and Mobile Applications. We will also learn to manipulate Oracle databases from within Visual Studio using Oracle Developer Tools for Visual Studio. What This Book Covers Chapter 1 introduces the concept of Oracle Database Extensions for .NET and provides information about Oracle Developer Tools for Visual Studio. Chapter 2 introduces the Provider-Independent Model in ADO.NET 2.0, and shows how to connect to Oracle databases from .NET, working with .NET data providers, connection pooling, system privileged connection, and single sign-on etc. Chapter 3 shows you several methods to retrieve data from an Oracle database. You will work with the core ODP.NET classes like OracleCommand, OracleDataReader, OracleDataAdapter, OracleParameter, and ADO.NET classes like DataSet, DataTable, and DataRow etc. Chapter 4 is about inserting, updating, and deleting data in the database. You will also learn about statement caching, array binding, working with offline data, implementing transactions, and handling errors and exceptions encountered during database work.
  • 12. Preface [ ] Chapter 5 deals with working with PL/SQL blocks, PL/SQL stored procedures, and functions. It also teaches you how to execute routines in PL/SQL packages, how to pass arrays to and receive arrays from the Oracle database, and working with REF CURSOR using ODP.NET. Chapter 6 is completely dedicated to dealing with large objects in Oracle. This chapter illustrates concepts, configurations, and programming for BFILE, BLOB, and CLOB (or NCLOB) in conjunction with ODP.NET. Chapter 7 gives details about Oracle XML DB, an add-on feature of Oracle database. It provides information about generating XML from existing rows in tables, manipulating rows in a table using XML, and working with native XML in the Oracle database. Chapter 8 deals with real-time application development scenarios like Oracle database change notifications, asynchronous application development, web application development using ASP.NET 2.0, web reporting (including grouping, sub-totals, charts, etc.), Object-Oriented development with ODP.NET and ASP.NET, XML web-services development using ODP.NET, and Smart Device Application development (for clients like the Pocket PC). Chapter 9 introduces you to Oracle Developer Tools for Visual Studio 2005. It teaches you to connect to Oracle from the Visual Studio 2005 environment, retrieve Oracle information from Visual Studio, and work with database objects from Visual Studio. It also provides information about how to create and debug PL/SQL stored procedures and .NET CLR stored procedures in Oracle. Conventions In this book, you will find a number of styles of text that distinguish between different kinds of information. Here are some examples of these styles, and an explanation of their meaning. There are three styles for code. Code words in text are shown as follows: ����������� Connecting to a default Oracle database is purely dependent on the ORACLE_SID key available in your registry.� A block of code will be set as follows: Dim ProviderName As String = _ Oracle.DataAccess.Client Dim fctry As DbProviderFactory = - DbProviderFactories.GetFactory(ProviderName)
  • 13. Preface [ ] When we wish to draw your attention to a particular part of a code block, the relevant lines or items will be made bold: Dim dt As DataTable = _ DbProviderFactories.GetFactoryClasses() Me.DataGridView1.DataSource = dt New terms and important words are introduced in a bold-type font. Words that you see on the screen, in menus or dialog boxes for example, appear in our text like this: clicking the Next button moves you to the next screen. Warnings or important notes appear in a box like this. Tips and tricks appear like this. Reader Feedback Feedback from our readers is always welcome. Let us know what you think about this book, what you liked or may have disliked. Reader feedback is important for us to develop titles that you really get the most out of. To send us general feedback, simply drop an email to feedback@packtpub.com, making sure to mention the book title in the subject of your message. If there is a book that you need and would like to see us publish, please send us a note in the SUGGEST A TITLE form on www.packtpub.com or email suggest@packtpub.com. If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide on www.packtpub.com/authors.
  • 14. Preface [ ] Customer Support Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase. Downloading the Example Code for the Book Visit http://www.packtpub.com/support, and select this book from the list of titles to download any example code or extra resources for this book. The files available for download will then be displayed. The downloadable files contain instructions on how to use them. Errata Although we have taken every care to ensure the accuracy of our contents, mistakes do happen. If you find a mistake in one of our books—maybe a mistake in text or code—we would be grateful if you would report this to us. By doing this you can save other readers from frustration, and help to improve subsequent versions of this book. If you find any errata, report them by visiting http://www.packtpub. com/support, selecting your book, clicking on the Submit Errata link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata added to the list of existing errata. The existing errata can be viewed by selecting your title from http://www.packtpub.com/support. Questions You can contact us at questions@packtpub.com if you are having a problem with some aspect of the book, and we will do our best to address it.
  • 15. Introduction to ODP.NET In the early days of databases, developers used to have knowledge on only one data access technology as they would usually concentrate on a single database. Later, numerous database products advanced quickly, leaving programmers in a confused state when selecting a particular data access methodology. The era of evolving architectures like client/server (two tier), three tier, and multi-tier (which includes web-enabled) has dramatically changed the way of accessing databases. The paradigm got shifted from simple connection-oriented applications to connection-less or disconnected (or offline) applications to meet the demands of devices like PDAs/Handhelds, Smart Phones, Pocket PCs etc. Introduction to ODP.NET We now have several types of data access methodologies to develop applications. Choosing the best data access methodology is totally dependent on the type of application you are working on. ADO.NET is a rock-solid technology and a proof of Microsoft's commitment to the UDA (Universal Data Access) strategy. The ADO.NET layer in the .NET architecture internally contains a few .NET data components (or .NET data providers), which can be used to connect to and access any database.
  • 16. Introduction to ODP.NET [ ] The data access through ADO.NET is shown in the following figure (along with other data access methodologies available prior to .NET): Traditional VB/ASP application .NET Applications ADO.NET C/C++ Applications Microsoft SQL Server .NET Data Provider Microsoft Oracle .NET Data Microsoft ODBC .NET Data Microsoft OLEDB .NET Data Provider Oracle Data Provider (ODP .NET) Other / 3rd party .NET Data Provider DAO ADO RDO OLEDB (with OLEDB Providers) ODBC (with ODBC Mgr. and ODBC Drivers) Respective libraries Access MS SQL Server Oracle Other RDBMS Flat files, XML, Mail Servers Other Legacy Systems Even though Microsoft designed its own .NET data providers, it has also opened its doors (specification) to the public and is encouraging other database companies to develop their own .NET data providers. Microsoft made the data access model consistent among all of the .NET data providers and thus any .NET data provider should definitely conform to the standards and architecture of ADO.NET. One of those is Oracle's ODP.NET, a .NET data provider that can connect to and access Oracle databases with tight integrity.
  • 17. Chapter 1 [ ] The ODP.NET features optimized data access to the Oracle database from a .NET environment. It is one of the several data access methods to connect to and access Oracle databases. Oracle didn't simply stop giving support to Microsoft platform with only ODP.NET. Instead, it has extended its commitment for Microsoft .NET by adding� Oracle database extensions for .NET and Oracle Developer Tools for Visual Studio. The upcoming sections will give you a solid understanding of ODP.NET along with its features. Why Use ODP.NET? Can't we access Oracle without ODP.NET? Yes, we can. It is not compulsory for you to work with ODP.NET. As mentioned in the following section, we can still connect to and access Oracle using other alternative methods. But, in terms of features and performance, ODP .NET is your best choice for connecting .NET applications with Oracle database. Let us see how! I am limiting the discussion to only .NET applications or clients that are trying to access Oracle databases. I will not be discussing application development prior to .NET. Oracle Database Access from .NET Applications There exist four main methodologies to access Oracle database from a .NET application: Microsoft's .NET data provider for ODBC (or ODBC.NET) Microsoft's .NET data provider for OLEDB (or OLEDB.NET) Microsoft's .NET data provider for Oracle Oracle's data provider for .NET (or ODP.NET) • • • •
  • 18. Introduction to ODP.NET [ ] Before discussing each of the above methodologies, let us understand their nature from the following figure: Any .NET Client VB.NET C# C++.NET ASP .NET … ODBC.NET OLEDB.NET Oracle ODBC Oracle OLEDB Microsoft's .NET data provider for Oracle Oracle database Oracle's Data Provider (ODP .NET) Oracle Client ADO.NET Microsoft's .NET data providers for ODBC and OLEDB are not intentionally developed exclusively for Oracle database. Those are generic .NET data providers mainly targeted for most of the common data sources. If you plan to use either of those two .NET data providers, you are likely to face performance problems. From the above figure, you can observe that there exists a separate layer for each of those .NET data providers. In other words, ODBC.NET or OLEDB.NET would not directly execute the queries or commands. Those operations would be carried to another intermediate layer (or data access bridge) and further get executed at Oracle database. The existence of this intermediate layer really kills the performance (or response time) of execution. So, if you are trying to access Oracle database from a .NET application, neither of those would be a good choice. Coming to the next choice, it is somewhat promising. Microsoft contributed a separate .NET Framework data provider (or Microsoft's Data Provider for Oracle) to connect to and access Oracle. It enables data access to Oracle data sources through Oracle client connectivity software without having any intermediate layers. This really improves performance over the previous two choices. Before using this provider in your .NET applications, you should install and configure Oracle client software (version 8.1.7 or later) on the development machine and test it.
  • 19. Chapter 1 [ ] The Oracle Data Provider for .NET (ODP.NET) features optimized data access to the Oracle database from any .NET client. It is the best in performance together with great flexibility. It allows developers to take advantage of native Oracle data types (including XML data type), XML DB, binding array parameters, Multiple Active Result Sets (MARS), Real Application Clusters (RAC), advanced security, etc. What Do We Require to Work with ODP.NET? As we are trying to develop .NET applications with access to Oracle database, we must have .NET Framework installed on our machine. Any Windows Operating System (preferably Windows Server 2003 or Windows XP Professional) supporting .NET can be used to work with ODP.NET. At the time of this writing, .NET Framework 3.0 is the latest in market; but Oracle hasn't released ODP.NET compatible with that version yet. Not only that, Visual Studio 2008 (or Orcas) supporting .NET Framework 3.0/3.5 is still in its beta version. For our purpose .NET Framework 2.0 is the latest in market, and you can download it free from Microsoft's website. Even though .NET Framework (including SDK and .NET runtime) alone is enough to develop .NET-based applications, it is better to have some GUI-based RAD environment (or IDE) installed, so that we can develop .NET applications in no time. Microsoft Visual Studio 2005 Professional Edition is the preferred GUI to develop .NET 2.0-based applications. If you install Microsoft Visual Studio 2005 Professional Edition, all the necessary components (including .NET Framework SDK and runtime) get automatically installed. The next is Oracle database. It is preferred to have at least Oracle 8.1 on your machine (or on a separate server). If you want to test with the latest version of Oracle on your own machine, you can download it free from Oracle's website for your development purposes. The lightest Oracle database version available (free) at the time of this writing is Oracle Database 10g Express Edition (or XE). Certain of the features like .NET CLR extensions (for .NET CLR-based stored procedure development) for Oracle are available only from Oracle 10g version 2.0 (Oracle 10.2) onwards. If you want to have distributed transaction support (like COM+ or Enterprise Services, etc.), then you may have install and configure Oracle Services for MTS. If you install Oracle database version 9i release 2 or later on your own system, no special Oracle client is necessary to work with ODP.NET. If your database is at some other location, then you may have to install and configure Oracle 9i Release 2 or higher client on your machine to work with ODP.NET. Oracle Net Services get automatically installed when Oracle 9i Release 2 or higher client is installed on your machine. This may be required when you try to access an Oracle database on a network.
  • 20. Introduction to ODP.NET [ 10 ] Another important optional component is Oracle Developer Tools for Visual Studio 2005. This is a wonderful add-in, which gets injected right into Visual Studio 2005. Using this add-in (called Oracle Explorer), you can connect to any Oracle database and work with schema or data without leaving the Visual Studio 2005 environment. It is particularly useful if you are likely to deal with .NET CLR extensions for Oracle. I strongly recommend having it installed on your machine, if you are working with Visual Studio Environment. If you are developing ASP.NET applications, it is better to have IIS configured on your machine, to test web applications over the network. If you are developing Smart Phone or Pocket PC applications, you may need to install Smart Device Extensions for Visual Studio (which automatically installs .NET Compact Framework for Smart Devices). Introduction to Oracle Database Extensions for .NET The Oracle Database Extensions for .NET is a new feature of Oracle Database 10g Release 2 on Windows that makes it easy to develop, deploy, and run stored procedures and functions written in any .NET-compliant language. Oracle Database Extensions for .NET Oracle Database Extensions for .NET makes it possible to build and run any .NET- based stored procedures or functions with Oracle Database for Microsoft Windows. This feature is supported only from Oracle 10g version 2 (on Windows) onwards or Oracle 10g Express Edition (or Oracle 10g XE). How does .NET Work within Oracle Database? How come Oracle understands .NET? Oracle database doesn't need to understand .NET at all. It simply hosts the Microsoft .NET Common Language Runtime (CLR) in an external process, outside of the Oracle database process, but on the same computer. The integration of Oracle database with the Microsoft Common Language Runtime (CLR) enables applications to run .NET stored procedures or functions on Oracle database without any hurdles. Application developers can write stored procedures and functions using any .NET-compliant language, such as C# and VB.NET, and use these .NET stored procedures in the database, in the same manner as other PL/SQL or Java stored procedures. .NET stored procedures can be used from PL/SQL packages, procedures, functions, and triggers.
  • 21. Chapter 1 [ 11 ] Once the caller (or other PL/SQL stored procedures, packages, etc.) calls any of these .NET routines (stored procedures or functions), they get executed by the Oracle hosted Microsoft CLR and the results are automatically picked up by the Oracle PL/SQL engine. Once the control comes back to PL/SQL engine, it proceeds with the normal and traditional the PL/SQL process flow of execution. Processing of .NET Stored Procedure with Oracle To develop .NET CLR-based stored procedures or functions, you may need to have Oracle 10g version 2 or higher (for Windows) or at least Oracle 10g Express Edition together with Oracle Database Extensions for .NET installed. If you use Oracle 10g Express Edition, the extensions get automatically installed. But, if you install Oracle 10g version 2 (for Windows), you may have to go to custom install and select the extensions. Apart from the extensions, you also need to download Oracle Developer Tools for Visual Studio (with appropriate version) to develop and deploy .NET CLR- based routines in Oracle database. Application developers build .NET stored procedures or functions using any .NET compliant language, such as C# and VB.NET, into a .NET assembly (generally a DLL), typically using Microsoft Visual Studio .NET 2003/2005. Obviously, we use Oracle Data Provider for .NET (ODP.NET) in .NET stored procedures and functions for Oracle data access. After building .NET procedures and functions into a .NET assembly, developers deploy them in Oracle database, using the Oracle Deployment Wizard for .NET, a component of the Oracle Developer Tools for Visual Studio .NET. Once the .NET stored procedure gets deployed, the PL/SQL wrappers for all of those routines get automatically created within the schema. The user invokes a .NET stored procedure or function through this PL/SQL wrapper (which would be the same as for normal PL/SQL stored procedures or functions). Oracle Deployment Wizard for .NET determines the probable mappings between Oracle data types and .NET data types, which the user can override. The mappings are handled seamlessly by the PL/SQL wrapper. Introduction to Oracle Developer Tools for Visual Studio Oracle Developer Tools for Visual Studio is an add-in for Microsoft Visual Studio that tightly integrates the Visual Studio environment with Oracle database. You will be able to manipulate Oracle databases from within Visual Studio and without leaving Visual Studio.
  • 22. Introduction to ODP.NET [ 12 ] At the time of this writing, Oracle Developer Tools for Visual Studio is available for both Microsoft Visual Studio.NET 2003 and Microsoft Visual Studio.NET 2005 versions. If you have both versions on your computer, you can install for both of those IDEs by installing Oracle Developer Tools for Visual Studio 2005. Once you install Oracle Developer Tools for Visual Studio, Oracle Explorer automatically shows up in the View menu of Visual Studio as shown in the following figure: Using Oracle Explorer in the Visual Studio environment, you can browse through your entire Oracle schema, launch several designers and wizards to work with different schema objects (like tables, views, etc.), execute queries directly against your schema (using SQL Query Window), automatically generate .NET code, and several more. The following is a small glimpse of Oracle Explorer:
  • 23. Chapter 1 [ 13 ] To work with database tables (for example inserting, updating, etc.) you can keep yourself tied with Oracle Data Window. It also gives you the flexibility to run and test your PL/SQL stored procedures. Oracle Explorer also includes a fully integrated PL/SQL debugger (for Visual Studio 2005). Apart from all of the above, you can easily develop and deploy .NET stored procedures and functions using .NET Deployment Wizard. Summary In this chapter, we have covered the concepts of ODP.NET, requirements to work with ODP.NET, Oracle Database Extensions for .NET, and finally concluded with an introduction to Oracle Developer Tools for Visual Studio.NET
  • 24. Connecting to Oracle From this chapter on, we will start programming with ODP.NET. This chapter mainly concentrates on the following: Introducing the Provider-Independent Model in ADO.NET 2.0 Working with .NET data providers Different ways to connect to Oracle database from ADO.NET 2.0 Connection pooling, system privileged connection, Windows authentication Provider-Independent Model in ADO.NET 2.0 ADO.NET internally works with .NET data providers (or .NET data bridge provider) to connect to and access data from different kinds of data sources (including databases). The same data provider model existing in ADO.NET 1.1 is further enhanced in ADO.NET 2.0 (with new factory classes) to leverage the flexibility of developing database-independent applications. What exactly is a ��������������������������������������������������������������� factory class?������������������������������������������������� ������������������������������������������������ The purpose of a factory class is to provide an interface for creating families of related objects, with or without specifying their concrete (method implementation) classes. If the factory class is created without one or more implementations of methods, we call it as an abstract factory class. The provider-independent programming model in ADO.NET 2.0 revolves around the classes in the System.Data.Common namespace. There are mainly two new factory classes that implement the provider-independent model (within the same namespace): DbProviderFactories DbProviderFactory • • • • • •
  • 25. Connecting to Oracle [ 16 ] Listing All Installed .NET Data Providers Now, let us start our programming with listing all .NET data providers installed on your machine. All .NET data provider-related information gets listed in the machine. config file on your machine������������������������������������������������� . Each provider is generally identified with its invariant name. The invariant name (in most cases) is the same as its namespace. The following code gives out the list of all .NET data providers installed on your machine: Imports System.Data.Common Public Class Form1 Private Sub btnProviders_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnProviders.Click Dim dt As DataTable = _ DbProviderFactories.GetFactoryClasses() Me.DataGridView1.DataSource = dt End Sub End Class Within the above code, the DbProviderFactories class is mainly used to enumerate all .NET data providers installed on your machine. Using the same class, we can also create instances related to a specific provider (to access databases specific to that provider). To list all the .NET data providers installed on your machine, we can use a GetFactoryClasses() ������������������������ method available in the DbProviderFactories class. The highlighted line of code finds and lists all the .NET data providers installed on your machine (and populates them into a data table). When that code gets executed, the output should look similar to the following:
  • 26. Chapter 2 [ 17 ] According to the preceding figure, you can see that the machine has six .NET data providers installed. The third column represents the invariant names to identify each of those providers. Enumerating all Oracle Data Sources Available In the previous section, we enumerated the list of all .NET data providers installed on the machine. In the previous screenshot, you should observe that the machine in this example has the Oracle Data Provider for .NET installed, �������������������� which is identified with invariant name Oracle.DataAccess.Client. In this section, we shall enumerate the list of all Oracle data sources available. Let us go through the following code first: Imports System.Data.Common Public Class Form2 Private Sub btnDataSources_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDataSources.Click Dim ProviderName As String = _ Oracle.DataAccess.Client Dim fctry As DbProviderFactory = _ DbProviderFactories.GetFactory(ProviderName) If (fctry.CanCreateDataSourceEnumerator) Then Dim dsenum As DbDataSourceEnumerator = _ fctry.CreateDataSourceEnumerator() Dim dt As DataTable = dsenum.GetDataSources() Me.DataGridView1.DataSource = dt Else MessageBox.Show(No datasources found) End If End Sub End Class Let us go through the above code step by step. The following is the statement that selects the ODP.NET data provider: Dim ProviderName As String = Oracle.DataAccess.Client
  • 27. Connecting to Oracle [ 18 ] The .NET data provider name is nothing but the invariant name available for the respective .NET data provider. In the previous screenshot, you can observe that there is a special column named InvariantName to identify the respective .NET data provider. The following statement creates a factory instance of the data provider selected: Dim fctry As DbProviderFactory = _ DbProviderFactories.GetFactory(ProviderName) Once the factory instance is created, we need to determine whether the provider (or instance) supports enumerating of data sources or not. This is easily accomplished with the CanCreateDataSourceEnumerator() ���������������������������������� method���������������������������� (which returns a Boolean). If the underlying .NET data provider supports enumerating the data sources, we can find and retrieve all the data sources for respective .NET data provider using the following code: If (fctry.CanCreateDataSourceEnumerator) Then Dim dsenum As DbDataSourceEnumerator = _ fctry.CreateDataSourceEnumerator() Dim dt As DataTable = dsenum.GetDataSources() Me.DataGridView1.DataSource = dt Else MessageBox.Show(No datasources found) End If The CreateDataSourceEnumerator() method simply creates an enumerator. The method GetDataSources() enumerates through all existing Oracle data sources. When the above code gets executed, the output should look similar to the following:
  • 28. Chapter 2 [ 19 ] Here, the XE is nothing but the name of the Oracle instance (SID) running on the system, which has Oracle 10g Express Edition installed. So far we have just enumerated all the .NET data providers installed on our machine and the list of Oracle data sources. We haven't connected to an Oracle database yet in the preceding code. Connecting to Oracle Databases from .NET There are several ways to connect to Oracle database from within .NET. Each of those methods has its own pros and cons as described in Chapter 1. Now, we will explore the most popular methodologies to connect to Oracle database through .NET. To connect to Oracle, we need to have proper connection descriptors configured on the system. This is usually taken care by the� tnsnames.ora file. TNS stands for Transparent Network Substrate. It provides a uniform application interface to enable network applications to access the underlying network protocols. tnsnames. ora �������������������������������������������������������������������������������� is simply a text file that provides SQL*Net with the Oracle server location and the necessary connection strings to connect to Oracle databases. This file always resides in the �������������� Oracle home's NetworkAdmin folder. If the Oracle client (or SQL*Plus) is already able to connect to the Oracle database server, the tnsnames.ora file is already correctly configured and you need not disturb it. But, it is beneficial for you to look at the content of tnsnames.ora to have a better understanding of the connection descriptors. The following is an example entry available in the tnsname.ora file on a machine to get connected to Oracle (yours could be different): XE = (DESCRIPTION = (ADDRESS_LIST = (ADDRESS = (PROTOCOL = TCP)(HOST = 127.0.0.1) (PORT = 1521)) ) (CONNECT_DATA = (SERVICE_NAME = xe) ) ) The above configuration script shows that the Oracle database server is available at 127.0.0.1 (local machine) and listening at port 1521. The service name (or SID) to connect to the server is xe. The whole description is assigned to a name XE. We will make use of the above specification in most of the connection strings available in the examples.
  • 29. Connecting to Oracle [ 20 ] Before building the connection strings, make sure that you configured and tested tnsnames.ora properly and can connect to the Oracle database. If you can already connect to the Oracle database server, you need not modify further. But you should know to which host you are going to connect. This is essential, as an Oracle client could be configured to connect to more than one Oracle database server simultaneously. You can also configure and test these connections using a graphical wizard, Net Configuration Assistant. Connecting Using .NET Data Provider Factory Classes The previous topic introduced .NET data provider factory classes and this section will use those classes to connect to an Oracle database. The following code demonstrates how to connect to an Oracle database using the .NET data provider factory classes: Imports System.Data.Common Public Class Form3 Private Sub btnConnect_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnConnect.Click 'specify provider's invariant name Dim ProviderName As String = _ Oracle.DataAccess.Client 'create factory instance for the provider Dim fctry As DbProviderFactory = _ DbProviderFactories.GetFactory(ProviderName) 'create connection based on the factory Dim Connection As Data.Common.DbConnection Connection = fctry.CreateConnection 'specify connection string Connection.ConnectionString = _ Data Source=xe;user id=scott;password=tiger Try 'try connecting to oracle Connection.Open() 'close the connection before exiting Connection.Close() MessageBox.Show(Succesfully connected)
  • 30. Chapter 2 [ 21 ] Catch ex As Exception 'display error message if not connected MessageBox.Show(Unable to connect. ex.Message) End Try End Sub End Class From the preceding code we have the following statements that are used to create a factory instance for the .NET data provider selected (in this case it is Oracle. DataAccess.Client). Dim ProviderName As String = _ Oracle.DataAccess.Client Dim fctry As DbProviderFactory = _ DbProviderFactories.GetFactory(ProviderName) Further moving down, we have the following: Dim Connection As Data.Common.DbConnection Connection = fctry.CreateConnection Data.Common.DbConnection can simply hold any type of database connection irrespective of the data source or data provider. To create a database connection object from the factory instance, we can make use of the CreateConnection() method, which in turn returns an object of the type Data.Common.DbConnection. Once the DbConnection object is created (for the respective .NET data provider through the factory instance), it needs to be provided with database connection string information as follows: Connection.ConnectionString = _ Data Source=xe;user id=scott;password=tiger Once the DbConnection object is ready, we can open the connection to connect and work with the database. It is always suggested to open a database connection as late as possible and close it as early as possible. The following code fragment tries to open the connection using the Open() method and closes using the Close() method: Try 'try connecting to oracle Connection.Open() 'close the connection before exiting Connection.Close() MessageBox.Show(Succesfully connected) Catch ex As Exception 'display error message if not connected MessageBox.Show(Unable to connect. ex.Message) End Try
  • 31. Connecting to Oracle [ 22 ] This model (and method) of connectivity is mostly preferred when you are trying to develop database-independent applications. Connecting Using .NET Data Provider for OLEDB This method is mostly preferred when you are trying to develop database- independent applications based on ADO.NET 1.1. If you are trying to develop a database-independent application based on ADO.NET 2.0, the method provided in the previous section is preferred. The following is the code to connect to Oracle database using .NET data provider for OLEDB: Imports System.Data.OleDb Public Class Form4 Private Sub btnConnect_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnConnect.Click Dim cn As New OleDbConnection cn.ConnectionString = Provider=msdaora; Data Source=xe;User Id=scott;Password=tiger; Try 'try connecting to oracle cn.Open() 'close the connection before exiting cn.Close() MessageBox.Show(Succesfully connected) Catch ex As Exception 'display error message if not connected MessageBox.Show(Unable to connect. ex.Message) End Try End Sub End Class In the above code, the System.Data.oleDb namespace is used to deal with .NET Data Provider for OLEDB. When we are working with OLEDB data sources, we need to connect through the OleDbConnection class. The connection string information would also be different when we deal with .NET Data Provider for OLEDB to connect to Oracle.
  • 32. Chapter 2 [ 23 ] The following is the new connection string used to get connected to Oracle database using .NET Data Provider for OLEDB: cn.ConnectionString = Provider=msdaora; Data Source=xe;User Id=scott;Password=tiger; Connecting Using .NET Data Provider for ODBC This method is used when you are trying to develop multi-platform database‑independent applications using ADO.NET. This method is preferable, if you want to connect to legacy systems or database systems existing on other platforms. The following is the code to connect to Oracle database using .NET data provider for ODBC: Imports System.Data.odbc Public Class Form5 Private Sub btnConnect_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnConnect.Click Dim cn As New OdbcConnection cn.ConnectionString = Driver={Microsoft ODBC for Oracle}; Server=xe;Uid=scott;Pwd=tiger; Try 'try connecting to oracle cn.Open() 'close the connection before exiting cn.Close() MessageBox.Show(Succesfully connected) Catch ex As Exception 'display error message if not connected MessageBox.Show(Unable to connect. ex.Message) End Try End Sub End Class
  • 33. Connecting to Oracle [ 24 ] In the preceding code, the System.Data.odbc namespace is used to deal with .NET Data Provider for ODBC. When we are working with ODBC data sources, we need to connect through the OdbcConnection class. The connection string information would also be different when we deal with .NET Data Provider for ODBC to connect to Oracle. The following is the new connection string used to get connected to Oracle database using .NET Data Provider for ODBC: cn.ConnectionString = Driver={Microsoft ODBC for Oracle}; Server=xe;Uid=scott;Pwd=tiger; Connecting using Microsoft's .NET Data Provider for Oracle This provider is added by Microsoft to facilitate developers connecting and accessing Oracle databases. This method is mostly preferred when you are trying to access only Oracle databases and when you don't have ODP.NET installed on your machine. Before you start working with this provider, you need to add a reference to the assembly System.Data.OracleClient as shown in following figure:
  • 34. Chapter 2 [ 25 ] Once you add a reference as shown in the preceding figure, you can proceed with the following code to connect to Oracle database using Microsoft's .NET data provider for Oracle: Imports System.Data.OracleClient Public Class Form6 Private Sub btnConnect_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnConnect.Click Dim cn As New OracleConnection cn.ConnectionString = _ Data Source=xe; User Id=scott;Password=tiger; Try 'try connecting to oracle cn.Open() 'close the connection before exiting cn.Close() MessageBox.Show(Succesfully connected) Catch ex As Exception 'display error message if not connected MessageBox.Show(Unable to connect. ex.Message) End Try End Sub End Class In the above code, we are making use of the System.Data.OracleClient namespace to deal with ������������ Microsoft's� .NET Data Provider for Oracle. The OracleConnection class used in the above code is available as part of the same namespace (and not to be confused with the same class available in Oracle.DataAccess.Client). Connecting Using Oracle Data Provider for .NET (ODP.NET) This provider is contributed by Oracle to facilitate developers connecting and accessing Oracle databases with tight integration (along with best performance) and advanced features. This method is the best even when you are trying to access Oracle, as ODP.NET has tight integration with Oracle database. To use this method, you must have ODP.NET downloaded (available free) and installed on your machine.
  • 35. Connecting to Oracle [ 26 ] Once you have ODP.NET installed on your machine, you need to add a reference to the assembly Oracle.DataAccess. If you have more than one version installed, you may have to choose the right one. If you are using Visual Studio 2005 and ODP.NET 10.2.0.2.20 (with support for ADO.NET 2.0) choose as shown in following figure: Once you add a reference as shown in the above figure, you can proceed with the following code to connect to Oracle database using ODP.NET: Imports oracle.DataAccess.Client Public Class Form7 Private Sub btnConnect_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnConnect.Click Dim cn As New OracleConnection cn.ConnectionString = _ Data Source=xe;User Id=scott;Password=tiger; Try 'try connecting to oracle cn.Open() 'close the connection before exiting cn.Close() MessageBox.Show(Succesfully connected) Catch ex As Exception
  • 36. Chapter 2 [ 27 ] 'display error message if not connected MessageBox.Show(Unable to connect. ex.Message) End Try End Sub End Class In the above code, the namespace Oracle.DataAccess.Client is used to deal with Oracle Data Provider for .NET (ODP.NET). The OracleConnection class used in the above code is available as part of the same namespace (and not to be confused with the same class available in System.data.OracleClient). The connection string information for this data provider and .NET data provider factory classes could be the same (as both of them deal with the namespace internally). Connecting with Connection Pooling Opening and maintaining a database connection for each client (or application/ user) is expensive and wastes lots of resources. This is true especially during web application development. To overcome such scenarios, Connection Pooling can be implemented. A Connection Pool is simply a cache of database connections. These connections can be reused when the database receives future requests from clients (or applications) for data. The clients (or applications) will feel as if each of them has a separate connection to the database. Connection Pooling is enabled by default and it is not only limited to ODP.NET but also available with other .NET data providers. You can simply add pooling=false to your connection string to disable Connection Pooling. You can customize pooling with your own specification within the connection string. The following is a simple demonstration of customizing the Connection Pooling as part of the connection string: Imports oracle.DataAccess.Client Public Class Form7 Private Sub btnConnect_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnConnect.Click Dim cn As New OracleConnection cn.ConnectionString = Data Source=xe; User id=scott;Password=tiger; Min Pool Size= 5; Connection Lifetime=120;
  • 37. Connecting to Oracle [ 28 ] Connection Timeout=60; Incr Pool size=2; Decr Pool size=1 Try 'try connecting to oracle cn.Open() 'close the connection before exiting cn.Close() MessageBox.Show(Succesfully connected) Catch ex As Exception 'display error message if not connected MessageBox.Show(Unable to connect. ex.Message) End Try End Sub End Class The connection string in the code above is defined with several parameters. Connection Lifetime sets the maximum duration in seconds of the connection object in the pool. Connection Timeout is the maximum number of seconds to wait for the connection to the server (before raising an error). Min Pool Size is the number of connection objects it needs to hold at any time (similarly Max Pool Size is also available). Based on the demands of requests and activity, the number of connections in the pool gets decreased or increased based on the specification of Incr Pool size and Decr Pool size. Connecting with System-Level Privileges or DBA Privileges DBA-level privileges are primarily focussed on database object-level access of a particular user. System-level privileges are more special when compared with ordinary database-level (or even object-level) privileges. When connecting with system-level����������������������������������������������������������������������� privileges, you have the opportunity to administer the database, even before it starts up. The two main system-level privileges are SYSDBA and SYSOPER. When you log in as SYSDBA, the default schema is SYS, whereas with SYSOPER the default schema is PUBLIC. SYSDBA is a superset of SYSOPER. While connecting with system-level privileges, it is obvious to work with DBA privileges as well. If you don't need to work at system level, and simply want to access few of the DBA objects, it is not really necessary to connect using system-level privileges.
  • 38. Chapter 2 [ 29 ] If you need .NET applications to connect to Oracle with system-level privileges, you just need to add connection parameters to the existing connection string as follows: Imports oracle.DataAccess.Client Public Class Form7 Private Sub btnConnect_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnConnect.Click Dim cn As New OracleConnection cn.ConnectionString = Data Source=xe; User id=system;Password=manager; DBA Privilege=SYSOPER Try 'try connecting to oracle cn.Open() 'close the connection before exiting cn.Close() MessageBox.Show(Succesfully connected) Catch ex As Exception 'display error message if not connected MessageBox.Show(Unable to connect. ex.Message) End Try End Sub End Class In the above statement, you can observe that the user name is system (which is a DBA user) and privilege is SYSDBA. Dynamic Connecting String Using OracleConnectionStringBuilder and app.config You can dynamically build a connection string using the OracleConnectionStringBuilder class available in ODP.NET 10.2.0.2. This is very helpful if you have any Oracle connectivity parameters in the .NET configuration files like app.config or web.config.
  • 39. Connecting to Oracle [ 30 ] Now, let us add few of the Oracle connectivity parameters to the app.config file by using solution properties as follows: Once you add the parameters as shown in the above figure, you can develop the code as follows to dynamically create a connection string using OracleConnectionStringBuilder (explained later)� : Imports Oracle.DataAccess.Client Public Class Form9 Private Function getConnectionString() As String Dim cnBuilder As New OracleConnectionStringBuilder With cnBuilder .DataSource = My.Settings.DataSource .UserID = My.Settings.UserID .Password = My.Settings.Password End With Return cnBuilder.ConnectionString End Function
  • 40. Chapter 2 [ 31 ] Private Sub btnConnect_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnConnect.Click Dim cn As New OracleConnection cn.ConnectionString = getConnectionString() Try 'try connecting to oracle cn.Open() 'close the connection before exiting cn.Close() MessageBox.Show(Succesfully connected) Catch ex As Exception 'display error message if not connected MessageBox.Show(Unable to connect. ex.Message) End Try End Sub End Class From the above code, you can observe that we are trying to retrieve all the connection parameters from the app.config file using the My object introduced in .NET Framework 2.0. The OracleConnectionStringBuilder object simply needs to have a few properties (like DataSource, UserID, Password etc.) set. Once the properties are set, it automatically frames a connection string internally and returns this when used with the ConnectionString property. Embedding a tnsnames.ora Entry-like Connection String In all of the above examples, we directly used the specification available in the tnsnames.ora file. You can even define your own entry in the style of tnsnames. ora,������������������������������������������������������������������������ directly within the connection string. The following is the code for a tnsnames. ora-less connection: Imports oracle.DataAccess.Client Public Class Form7 Private Sub btnConnect_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnConnect.Click Dim cn As New OracleConnection Dim ConnStr As String
  • 41. Connecting to Oracle [ 32 ] ConnStr = Data Source = ConnStr = (DESCRIPTION = ConnStr = (ADDRESS_LIST = ConnStr = (ADDRESS = (PROTOCOL = TCP) (HOST = 127.0.0.1)(PORT = 1521)) ConnStr = ) ConnStr = (CONNECT_DATA = ConnStr = (SERVICE_NAME = xe) ConnStr = ) ConnStr = ); ConnStr = User Id=scott; ConnStr = password=tiger; cn.ConnectionString = ConnStr Try 'try connecting to oracle cn.Open() 'close the connection before exiting cn.Close() MessageBox.Show(Succesfully connected) Catch ex As Exception 'display error message if not connected MessageBox.Show(Unable to connect. ex.Message) End Try End Sub End Class In the above code, we simply copied and pasted the entry available in tnsnames.ora and it worked like a charm. You can also make the above connection string dynamic (say, if you want to connect to different data sources at different times), by adding text boxes to your form and concatenating those values with the above connection string. Connecting to a Default Oracle Database In all of the previous methods, within the connection string, we specified the data source or server values to connect to an Oracle instance (using SID). Sometimes, it may be necessary for us to get connected to the default Oracle database existing on the same machine as of the .NET application (but not on any other network server). Connecting to a default Oracle database is purely dependent on the ORACLE_SID key available in your registry (as shown in the following). You can even add it manually if it is not available in your Oracle home. Once that is added, you can define connection strings without the specification of data source or server.
  • 42. Chapter 2 [ 33 ] Even though you can add this ORACLE_SID using the Environment Variables dialog box, this method is not suggested if you have multiple versions of Oracle installed on the same machine. Once you set up the default Oracle database using the ORACLE_SID registry key in your registry, the connection string could be modified and made simple (without specifying any data source or server specification) as follows: cn.ConnectionString = User Id=scott;Password=tiger; Connecting Using Windows Authentication (Single Sign‑On) This is totally a different scenario from any of the previous types of connectivity to Oracle databases. A Windows Authentication is simply a process of authenticating against Oracle database using the Windows-user credentials. A Single Sign-on is the process of authenticating against Oracle database even without providing any credentials (by taking into the account of existing Windows-user credentials). There exists no direct solution to achieve 100% ������������������������������� single sign-on����������������� to authenticate against Oracle database. However, we need to provide the user ID as /, which automatically carries our current Windows-user credentials to authenticate against Oracle database. By using this facility, we can develop .NET applications implementing 100% ���������������������������������������� single sign-on against Oracle databases.
  • 43. Connecting to Oracle [ 34 ] Primarily, a Windows Authentication to an Oracle database is not a straight process. Even though, it is not very complicated process, we do have some configuration, which needs to be set up using database administrator privileges. To get a Windows user for a successful Windows authentication (or single sign-on) against Oracle database, we must start by finding two important values as follows: Operating System Authentication Prefix (os_authent_prefix parameter in the init.ora file) Windows user name (along with either host name or domain name) The ��������������������������������������������������������������������� Operating System Authentication Prefix������������������������������� gets configured during Oracle installation and is available as an os_authent_prefix ����������������� parameter in the init.ora file. We need to use this value as a prefix to the Windows-user credentials. To retrieve the value of that parameter, you need to use the following statement: SQL show parameter os_authent_prefix You may need to have DBA privileges (or log in as system/sysdba/sysoper user) to carry out these tasks. You can easily get your complete user name (along with your host name or domain name) from your login dialog box. You can even get it dynamically using the following VB.NET code: Private Sub btnWindowsUser_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnWindowsUser.Click Dim WindowsUser As String = My.User.Name MessageBox.Show(WindowsUser) End Sub Once you find out those two values, you need to create a user in Oracle with the same Windows user name (along with host/domain name) preceded with the value of os_authent_prefix and grant enough privileges to get the user connected. Sometimes, the value of os_authent_prefix could be empty (or no value). In such scenarios, you need not prefix the Windows user with any value. • •
  • 44. Chapter 2 [ 35 ] You can issue the following statements to create and grant privileges to the Windows user in Oracle: SQL CREATE USER PS$LAPTOP2K3ADMINISTRATOR IDENTIFIED EXTERNALLY; SQL GRANT connect, resource TO PS$LAPTOP2K3ADMINISTRATOR In the above commands, PS$ is the parameter value of os_authent_prefix on my machine and LAPTOP2K3ADMINISTRATOR is the Windows user. If there is no value (or empty) for os_authent_prefix, you need not prefix the Windows user with any value. Once the above setup is perfectly configured, you must be able to connect to that user using the following command at the SQL prompt: SQL connect / You can observe that it is quite simple to connect to Oracle database using /, which informs it to use a Windows authentication. In the same manner, you can modify your connection string in .NET as follows to achieve a single sign-on authentication (with Windows authentication) to Oracle database: Dim cn As New OracleConnection cn.ConnectionString = Data Source=xe;User Id=/; Summary In this chapter, we have reviewed the strategy of the Provider-Independent Model in ADO.NET 2.0, used this model to list installed .NET data providers and data sources, and finally developed code to connect to Oracle database from .NET using all the available methods.
  • 45. Retrieving Data from Oracle Using ODP.NET We have several methodologies to retrieve information from Oracle using ODP.NET. Sometimes, we may have to use few of the ODP.NET classes together with few of the ADO.NET classes to develop .NET applications efficiently. In this chapter, we will concentrate on the following: Executing queries with OracleCommand Retrieving data using OracleDataReader Retrieving data using OracleDataAdapter Working with DataTable and Dataset when offline (disconnected mode) Using DataTableReader with DataTable Bind variables using OracleParameter Performance techniques If you would like to work with stored procedures to retrieve data, you should skip to Chapter 5 (provided you are familiar with all the concepts discussed here). Fundamental ODP.NET Classes to Retrieve Data To retrieve data from an Oracle database using ODP.NET, we need to work with a few of the ODP.NET classes. At this point, we will discuss the most fundamental classes available in ODP.NET for retrieving data. • • • • • • •
  • 46. Retrieving Data from Oracle Using ODP.NET [ 38 ] The following is the list of fundamental ODP.NET classes: OracleConnection OracleCommand OracleParameter OracleDataReader OracleDataAdapter The OracleConnection class provides the means to connect to the Oracle database. We have already used this class several number of times in the previous chapter. It connects to Oracle database and performs all the operations we need to carry out. Without this class, we would never be able to perform any database operation. It also manages transactions and connection pooling. The OracleCommand class is mainly used to execute commands against Oracle database. It supports the execution of SQL commands (like SELECT, INSERT, and CREATE), stored procedures, etc. We can even specify table or view names (without even providing a SELECT statement) to retrieve the rows available through them. It works in conjunction with OracleConnection to connect to Oracle database. The OracleParameter class is complementary to the OracleCommand class to provide run‑time parameters along with their values to SQL queries or stored procedures. You can even work with different types of stored-procedure parameters like IN, OUT, or IN OUT. It is also mostly used whenever you want to execute the same SQL command frequently or continuously. The OracleDataReader class is simply a read-only and forward-only result set. As the data retrieved using this class is non-updatable and only forward-navigable, this is the fastest retrieval mechanism available. The most important point to remember while using OracleDataReader is that it needs a dedicated connection to Oracle database while it retrieves information. It is best used to fill in drop-down lists, data grids, etc. It works in conjunction with OracleCommand to connect to and retrieve information from Oracle database. The� OracleDataAdapter class is mainly used to populate datasets or data tables for offline use (disconnected use). The OracleDataAdapter simply connects to the database, retrieves the information (or data), populates that information into datasets or data tables, and finally disconnects the connection to the database. It works with OracleConnection to connect to Oracle database. It can also work with OracleCommand if necessary. A data table is very similar to a disconnected result set (or record set). A dataset is simply a set of data tables along with their relations (if available). A dataset is a kind of small scale in-memory RDBMS, which gets created on demand. • • • • •
  • 47. Chapter 3 [ 39 ] DataTable and DataSet are the two classes for these in ADO.NET that are used in combination with OracleDataAdapter. The data in a dataset (or data table) can be modified offline (in disconnected mode) and later can be updated back to the database using the same OracleDataAdapter. In simple words, OracleDataAdapter works as a bridge between offline data (or a dataset) and Oracle database. Retrieving Data Using OracleDataReader OracleDataReader is simply a read-only and forward-only result set. It works only if the database connection is open and it makes sure that the connection is open while you are retrieving data. As the data that it retrieves is read-only, it is a bit faster than any other method to retrieve data from Oracle. You need to work with OracleCommand together with OracleConnection to get access to OracleDataReader. ������������ There is an ExecuteReader method in the OracleCommand class���������������������� , which gives you the OracleDataReader. Retrieving a Single Row of Information Let us start by retrieving a single row from Oracle database using ODP.NET and populate the data into few textboxes on a WinForm. To connect to and work with Oracle database, we need to start with OracleConnection. Once a connection to the database is established, we need to issue a SELECT statement to retrieve some information from the database. A query (or any SQL command) can be executed with the help of an OracleCommand object. Once the SELECT statement gets executed, we can use OracleDataReader to retrieve the information. The following code accepts an employee number from the user and gives you the details of that employee: Imports Oracle.DataAccess.Client Public Class Form1 Private Sub btnGetEmployee_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnGetEmployee.Click 'create connection to db Dim cn As New OracleConnection(Data Source=xe; _ User Id=scott;Password=tiger) Try Dim SQL As String 'build the SELECT statement
  • 48. Retrieving Data from Oracle Using ODP.NET [ 40 ] SQL = String.Format(SELECT ename, sal, job FROM emp WHERE empno={0}, Me.txtEmpno.Text) 'create command object to work with SELECT Dim cmd As New OracleCommand(SQL, cn) 'open the connection cmd.Connection.Open() 'get the DataReader object from command object Dim rdr As OracleDataReader = _ cmd.ExecuteReader(CommandBehavior.CloseConnection) 'check if it has any rows If rdr.HasRows Then 'read the first row rdr.Read() 'extract the details Me.txtEname.Text = rdr(ename) Me.txtSal.Text = rdr(sal) Me.txtJob.Text = rdr(job) Else 'display message if no rows found MessageBox.Show(Not found) End If 'clear up the resources rdr.Close() Catch ex As Exception 'display if any error occurs MessageBox.Show(Error: ex.Message) 'close the connection if it is still open If cn.State = ConnectionState.Open Then cn.Close() End If End Try End Sub End Class As explained earlier, the above program creates an OracleConnection object as follows: Dim cn As New OracleConnection(Data Source=xe; _ User Id=scott;Password=tiger)
  • 49. Chapter 3 [ 41 ] Next, we need to create an OracleCommand object by providing a SELECT query and the connection object (through which it can connect to the database): Dim SQL As String SQL = String.Format(SELECT ename, sal, job FROM emp WHERE empno={0}, Me.txtEmpno.Text) Dim cmd As New OracleCommand(SQL, cn) Once the OracleCommand object is created, it is time to open the connection and execute the SELECT query. The following does this: cmd.Connection.Open() Dim rdr As OracleDataReader = _ cmd.ExecuteReader(CommandBehavior.CloseConnection) You must observe that the query gets executed using the ExecuteReader method of OracleCommand object, which in turn returns an OracleDataReader object. In the above statement, the ExecuteReader method is specified with CommandBehavior. CloseConnection, which simply closes the database connection once the OracleDataReader and OracleCommand are disposed. We can use the HasRows property of OracleDataReader to test whether the reader retrieved any rows or not. If any rows are retrieved, we can read each successive row using the Read method of OracleDataReader. The Read method returns a Boolean value to indicate whether it has successfully read a row or not. Once the Read succeeds, we can retrieve each value in the row with the column name as follows: If rdr.HasRows Then 'read the first row rdr.Read() 'extract the details Me.txtEname.Text = rdr(ename) Me.txtSal.Text = rdr(sal) Me.txtJob.Text = rdr(job) Else 'display message if no rows found MessageBox.Show(Not found) End If Finally, we close the OracleDataReader object using the Close method as follows: rdr.Close()
  • 50. Retrieving Data from Oracle Using ODP.NET [ 42 ] If it could read successfully, the output for this code would look similar to the following figure: Using Using for Simplicity The above program can be made simple by using the Using statement together with ODP.NET classes as follows: Using cn As New OracleConnection(Data Source=xe; User Id=scott;Password=tiger) Try cn.Open() Dim SQL As String SQL = String.Format(SELECT ename, sal, job FROM emp WHERE empno={0}, Me.txtEmpno.Text) Using cmd As New OracleCommand(SQL, cn) Using rdr As OracleDataReader = cmd.ExecuteReader If rdr.HasRows Then 'read the first row rdr.Read() 'extract the details Me.txtEname.Text = rdr(ename) Me.txtSal.Text = rdr(sal) Me.txtJob.Text = rdr(job) Else 'display message if no rows found MessageBox.Show(Not found) End If End Using End Using Catch ex As Exception MessageBox.Show(Error: ex.Message) If cn.State = ConnectionState.Open Then
  • 51. Chapter 3 [ 43 ] cn.Close() End If End Try End Using The Using keyword is new in Visual Basic 2005, which internally generates try and finally blocks around the object being allocated and calls Dispose() for you saving you the hassle of manually creating it. The objects created using the Using keyword are automatically erased (and respective resources would be automatically cleared) from the memory once it is out of using scope. Even though it is very flexible to use the Using statement, for the sake of clarity, we will go without using it in the examples of this book. Retrieving Multiple Rows on to the Grid In the previous section, we tried to retrieve only one row using OracleDataReader. In this section, we will try to retrieve more than one row (or a result set) and populate a DataGridView on a WinForm. The following code lists out the details of all employees available in the emp table: Imports Oracle.DataAccess.Client Public Class Form2 Private Sub btnGetEmployees_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnGetEmployees.Click 'create connection to db Dim cn As New OracleConnection(Data Source=xe; User Id=scott;Password=tiger) Try Dim SQL As String 'build the SELECT statement SQL = String.Format(SELECT empno, ename, job, mgr, hiredate, sal, comm, deptno FROM emp) 'create command object to work with SELECT Dim cmd As New OracleCommand(SQL, cn) 'open the connection cmd.Connection.Open() 'get the DataReader object from command object Dim rdr As OracleDataReader = _ cmd.ExecuteReader(CommandBehavior.CloseConnection) 'check if it has any rows If rdr.HasRows Then
  • 52. Retrieving Data from Oracle Using ODP.NET [ 44 ] With Me.DataGridView1 'remove existing rows from grid .Rows.Clear() 'get the number of columns Dim ColumnCount As Integer = rdr.FieldCount 'add columns to the grid For i As Integer = 0 To ColumnCount - 1 .Columns.Add(rdr.GetName(i), rdr.GetName(i)) Next .AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.ColumnHeader 'loop through every row While rdr.Read 'get all row values into an array Dim objCells(ColumnCount - 1) As Object rdr.GetValues(objCells) 'add array as a row to grid .Rows.Add(objCells) End While End With Else 'display message if no rows found MessageBox.Show(Not found) Me.DataGridView1.Rows.Clear() End If 'clear up the resources rdr.Close() Catch ex As Exception 'display if any error occurs MessageBox.Show(Error: ex.Message) 'close the connection if it is still open If cn.State = ConnectionState.Open Then cn.Close() End If End Try End Sub End Class Except the highlighted section, the rest of the code is already explained as part of the previous section. You can observe that the SELECT statement now tries to retrieve all rows from emp as follows: SQL = String.Format(SELECT empno, ename, job, mgr, hiredate, sal, comm, deptno FROM emp)
  • 53. Chapter 3 [ 45 ] Once the OracleDataReader is ready with rows, we need to start with clearing the rows already displayed in the DataGridView with the help of the following code: With Me.DataGridView1 'remove existing rows from grid .Rows.Clear() Once the rows are cleared, the first issue is the header of the grid. The moment we add columns to the grid, the header row gets automatically populated (with the column names). Before adding columns to the header, we should know the number of columns being added (just for the loop iterations) with the FieldCount property of DataGridView. The following is the code fragment that finds the number of columns and adds the columns to DataGridView: Dim ColumnCount As Integer = rdr.FieldCount For i As Integer = 0 To ColumnCount - 1 .Columns.Add(rdr.GetName(i), rdr.GetName(i)) Next All the columns get auto-sized based on the column header with the following statement: .AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.ColumnHeader Once the columns are added, we need to read every successive row from the OracleDataReader and add it to the DataGridview. To add all column values at a time, we make use of the GetValues() method of OracleDataReader to push all the values in to an array and finally add the array itself as a row to the DataGridView. The following code fragment accomplishes this. While rdr.Read 'get all row values into an array Dim objCells(ColumnCount - 1) As Object rdr.GetValues(objCells) 'add array as a row to grid .Rows.Add(objCells) End While
  • 54. Another Random Scribd Document with Unrelated Content
  • 55. A. They never had a meeting after the 27th, that I know of, in Pittsburgh. Q. Did they at any other point? A. Yes; the Trainmen's Union is still in existence. Q. Was there any time arranged afterwards for a strike? A. No; no time was agreed upon, but all labored under the impression that the bubble had grown so large, that it would have to burst sooner or later. Q. Was there any pre-arranged plan, by which any strike was to take place on the 19th of July? A. No, there was not. There was some little talk about it, if the railroad company would do so and so, that they would kick. Q. Do what? A. Put on double-headers. By Senator Yutzy: Q. What do you mean by kick? A. Not stand it. By Mr. Lindsey: Q. Strike, do you mean? A. Yes. Q. Then there was no pre-arranged plan for that strike on the 19th? A. There was no pre-arranged plan. Q. Was it talked over?
  • 56. A. Not on that day; but just as soon as they put on double-headers they didn't propose to submit to it, as they thought seventeen cars were enough for the men to take care of. Q. These double-headers were only confined to the Pennsylvania Central? A. Yes. Q. They didn't extend over any other roads leading into Pittsburgh? A. No. Q. Was it known to the men on any other roads that the men on the Pennsylvania Central were going to strike? A. I suppose they knew that they had their sympathy. Q. I understood you to say that you left Pittsburgh the day before the strike? A. No; I left it about the 16th. Q. Did you know any thing about it then, or understand that there would be a strike then? A. Yes; I remarked after the 27th day of June that I was positive there would be a strike, sooner or later—that the thing would have to come to a head itself. Q. Did they say to you, or did you understand from any employés on the Pennsylvania Central road, that there would be a strike on the 19th? A. No one knew that they were going to strike on that day. By Senator Reyburn: Q. Then no time was set?
  • 57. A. No. By Mr. Lindsey: Q. Was it understood that when the order was given to run the double-headers that they would strike? A. It was understood that just as soon as they put on double- headers they wouldn't run them. The men couldn't stand it. Q. Did you know any thing about the strike at Martinsburg? A. Yes; I heard of it. Q. Before it took place? A. No; not before it took place. I knew of it as soon as it did take place. Q. Was there any general understanding that a strike would take place at the time the strike broke out at Martinsburg? A. No; the understanding we had of this thing—our object in organizing the Trainmen's Union was, that the Pennsylvania Company would make a reduction on the first of June of ten per cent., and that, if their employés submitted to it, that the New York Central would follow about the 1st of July, and if their employés submitted to it—they had two roads, and had pooled their earnings —they would make a reduction on the 15th of July on the Baltimore and Ohio. They thought if they didn't get a strike before the 15th day of July, then the Pennsylvania road and these other roads would get so used to it, or that they would get us so frightened that we would have the idea knocked out of us, if they could run their traffic over those roads. They were not going to make a reduction over two trunk lines at one time. Q. Did all that happen?
  • 58. A. No; there was a reduction on the Pennsylvania on the 1st of June, and on Vanderbilt's road on the 1st of July, and on the Baltimore and Ohio on the 15th or 16th, and on the 15th was the strike. Q. Did you have any communication with the men at Martinsburg before they struck? A. I had some friends down there, and I used to hear from them once in a while. Q. About the strike—this particular strike that took place at Martinsburg—did your union communicate with them? Was it understood or arranged between you for that strike on the 16th? A. No; although they said that just as soon as they got the reduction they were going to strike. Q. I understand you to say it was the double-headers, or the order to run them, that caused the strike on the 16th, at Pittsburgh? A. Yes; because it was the wrong time to put on the double-headers, just following the strike at Martinsburg. That just started the whole thing. Q. This Trainmen's Union was organized, you say, for the purpose of protecting yourself? A. For protecting our own interests. Q. What had you to complain of at the time of organizing the union? A. The ten per cent. reduction. We thought we were getting little enough money. Q. Had you anything else to complain of? A. Yes; we had something a little worse than the reduction. That was all right. If they saw fit to reduce, and could get men to work at their rate, all right. The officials of the road, and Mr. Scott, all
  • 59. treated us all right. It was only the little under-officials who treated us like dogs. I was told that if I voted for a certain man I would get discharged off the road. I wanted to vote for a neighbor of mine. Q. By whom were you told that? A. By a petty under-official, the assistant day dispatcher. Q. Had you anything to complain of, except this ten per cent. reduction? A. Not on our road—not on the Fort Wayne road. Q. Had they on the Pennsylvania Central, before the order was issued to run the double-headers? A. No; I don't believe they had. Q. That was the only thing you had to complain of? A. Yes. Q. Did you have any negotiations with the magnates of the road in regard to that? A. Yes; we appointed a committee to wait on them, and talk with them, and try to get the thing settled up; but we couldn't reach them with a forty-foot pole. We tried everything with reference to avoiding a strike. By Senator Reyburn: Q. How long were you on the road? A. About eleven months, I guess. Q. Had there been any talk of striking before—during those eleven months? A. No.
  • 60. Q. Were any committees appointed to wait on the officials? A. That was when we heard of the ten per cent. reduction. Q. Had you any grievances before? A. No. By Mr. Lindsey: Q. It was arranged then by your union that you would strike in case of a reduction? A. That was what we organized for. Q. Do you claim the right at all times to strike as a body? Do you claim that it is one of the rights that you have? A. I claim that every free born American citizen, if necessary, has the right to quit work if he wants to. That is what I call striking—quitting work. Q. Doing anything more? A. We have no right to destroy property. Q. Do you claim it as a right to interfere with those who want to work? A. It is a right to use mere suasion. If I were to see you rushing on headlong on the breakers, and I can stop you, I would do so. Q. Do you claim that you have a right to assemble in crowds or groups upon the property of the railroad company? A. If that is where we are employed; yes. Q. But when you strike, you are no longer in the employ of the railroad company? A. No; not when we have once struck.
  • 61. Q. Then after you have struck you don't claim that you have the right to assemble there? A. Until we are ordered off? Q. But when ordered off, have you the right to refuse to go? A. It depends greatly upon who orders you off. Q. When ordered off by an official of the railroad company? A. If I am there for any unlawful purpose, I ought to go, but if I am not there for any unlawful purpose, and if I run against a man who wants to show fight or ride a big horse, I don't think I have any business to go, if I want to stay. By Senator Reyburn: Q. But do you say that you have the right to go on another man's property and stay there if he wants you to go away? A. I don't recognize any one like a day dispatcher. It is not his business. Q. But it is his business to keep the track clear? A. No; it is not. By Mr. Lindsey: Q. You did assemble at yard of the Fort Wayne and Chicago road, one hundred and fifty or two hundred of you? A. Yes. Q. Were you ordered off—ordered to leave or disperse? A. No; directly we were not. Q. By any one belonging to the road?
  • 62. A. The dispatcher told the chief of police to disperse this mob, that they were not employés of the Fort Wayne road, but rioters and loafers from Pittsburgh, and wouldn't allow their men to work. Q. You resisted this? You refused to go? A. I don't like a man to call me a liar. Q. Did you refuse to go? A. No one told me to go off the property. Q. Didn't the policemen tell you to go? A. No. Q. Didn't they undertake to disperse you? A. They got in amongst us, but they didn't push or tell us to go off. Q. But you refused to go? A. We didn't understand it that way. Q. Was it not your duty to disperse when the policemen requested you, having been instructed so to do by the officials of the railroad company? A. The police didn't tell us to disperse. Q. You knew what they came among you for, and what commands had been given to them by the officers of the railroad company? A. I heard the dispatcher say, disperse this lot of loafers and rioters from Pittsburgh. I don't know that he spoke to me. Q. Did he refer to the crowd? A. I don't know of any loafers or bummers in that crowd. By Senator Yutzy:
  • 63. Q. Were you ordered to disperse by anybody? A. No; the dispatcher didn't speak to us, but to the chief of police, that these men are a lot of rioters from Pittsburgh, and he wanted them off the property. By Mr. Lindsey: Q. Did you consider you had the right to take that property and pack it away on the side tracks? A. I thought I did perfectly right. Q. If it was in danger of being destroyed? A. Everybody appeared to be excited, and they had lost their heads, so that you couldn't get them to do anything. There were some passenger and freight cars, and a lot of cars loaded with live stock standing on one track, and nobody appeared to know what to do with them. People came to me and asked what to do, from even the dispatcher himself—he looked to me. Q. But after you had refused to work, had you any right to interfere with that property? A. We didn't interfere with the property. Q. Had you any right to do anything with it? A. If we were asked to do it we had. Q. Had you any right to interfere with that property in any way? A. Yes. Q. You understand what I mean by my question? Do you not think it was your duty, after having refused to work, to leave the premises entirely and go away? A. That depends on circumstances.
  • 64. Q. But if you were working for a man and stopped work, or he turned you off, have you any right to remain around? A. That depends a great deal on whether he wants me around or not. Q. But have you any right to interfere with his property in any way, under any circumstances? A. I would think I was a very foolish man. If my property was in danger I would like him to come and lend a hand. Q. I didn't ask any question about the property being in danger? A. We didn't interfere with the property in any way or manner. By Mr. Means: Q. Had the commander of the military refused an interview with you, or the party you represent, what would have been the consequences —what was your determination? A. I don't know as we figured that far ahead. Q. But you must have had some plan, sir? A. I didn't happen to meet him, therefore, I cannot tell you. Q. I want to know what was your determination? A. That is something nobody knows. Q. I insist upon an answer? A. It is a question I cannot answer. Q. This is the question. Had the commander of the military refused to have an interview with you or the party you represent, what was your determination—what did you intend to do?
  • 65. A. That would have depended greatly on circumstances. I don't know what we would have done. By Mr. Lindsey: Q. Did you intend to resist the militia? A. If you or any other man or the militia had raised a gun to shoot me, I undoubtedly would have resisted. Q. But answer yes or no, then explain after answering the question? A. What is the question? Q. Did you intend to resist the militia had they attempted to disperse the crowd? A. I will have to answer the question yes and no. If they had come with the requisite authority from the Governor of the State and ordered us to disperse, undoubtedly we would have obeyed them. If they had authority from the Governor of the State, I, for one, would have walked away. Q. But suppose they had authority from General Latta? A. I didn't recognize him. Q. You didn't recognize him? A. I didn't at that time. Q. Certainly you couldn't have been a law-abiding citizen if you didn't? A. I didn't at that time. By Mr. Lindsey: Q. Then you intended to use your own judgment as to whether the militia were there lawfully or unlawfully?
  • 66. A. I look upon General Huidekoper as a gentleman, and don't think he would lie. Q. Suppose he had said he was there on authority from the Governor? A. I told you I would have gone off the premises and walked away. If he had told me it was none of my business, I would have told him I would make it my business. If he had told me he was there by authority of some railroad official, I would have told him that the best thing he could do for his own and for our sake, would be to take the back track, and go away. Q. Did you see the daily papers of that week? A. No; I don't believe I did. Q. Did you see a published proclamation of the Governor's? A. I don't believe I did. Q. Did you know a proclamation had been issued? A. I had heard of it. Q. Commanding all citizens to disperse? A. I had heard of it, but I didn't read it. By Mr. Means: Q. Then you and your party were to be the judges, whether or not General Latta had authority or not? A. We were open to conviction. We thought we were endowed with a little common sense. Q. I don't doubt it for a moment—not at all. But you were to be the judges whether General Latta had authority or not?
  • 67. A. The way I came to get under that impression—an attorney, the first day of the strike, who was around there when this question came up about the Governor being out of the State, said that the troops or military could not be ordered out, because the Governor was not here. Q. Give us his name? A. I cannot give it. Q. I insist upon it? A. I refuse to answer the question. Q. If the committee insists upon an answer you certainly will have to answer, because you have sworn to tell the truth? A. Well, I well give the committee the names of any of these parties in confidence, but I don't care about telling their names to the world. I am perfectly willing to give them to the committee in confidence. I don't want to keep anything back, but I don't want to tell tales on anybody else. By Senator Reyburn: Q. Did your association have an attorney employed—the Trainmen's Union? A. Two or three were around there, sort of acting as though they were employed, but we never knew who employed them. Q. Did you consult with them? A. No; they came there and gave us advice. By Senator Yutzy: Q. Gratuitously? A. That is about it.
  • 68. By Mr. Lindsey: Q. Were they ever paid any fees? A. Not that I know of. By Senator Reyburn: Q. Were they practicing attorneys at the bar? A. Yes. By Mr. Lindsey: Q. You continued to keep up the strike there, and hold possession of the railroad property, until the arrival of the Governor of the State, did you not? A. I believe we were on the premises when the Governor arrived. Q. And had possession of the property of the railroad? A. I don't know. The property was all lying there. No one was holding it? Q. But didn't you guard it. Didn't you exercise care of it, and didn't you afterwards deliver it over to the railroad officials? A. Yes; we told them that we wouldn't have anything more to do with it, that they must get somebody else to watch it. Q. Who did you deliver it to? A. A man I did not recognize came down and took possession for Mayor Phillips or his police. Q. You surrendered the property to him? A. No, sir; I did not, but to the officers of the road. Q. What day was that?
  • 69. A. That was the evening the Governor came in. Q. The evening the Governor arrived? A. Yes. Q. Did you have any interview with the Governor on his arrival? A. Yes. Q. Tell us what that was? A. I had a little talk with him and passed the compliments of the day, and asked him to come out and say a few words to the boys, and he came out on the back platform and said something to them. We then passed on to the round-house, where there was a crowd of some five or six hundred, and he spoke a few words to them, and then went on to the city of Allegheny, where the citizens met him with a carriage and took him to Pittsburgh, by the suspension bridge. By Senator Yutzy: Q. Did you telegraph to him? A. I did. By Mr. Lindsey: Q. What was the nature of those telegrams? A. Some of them are part of history. I telegraphed along the line not to interfere with the train he was on, so as not to get him angry with us, and I telegraphed him guaranteeing him a safe passage to Allegheny city. Q. You had the power to give him a safe passage through? A. My name was good enough at that time.
  • 70. Q. Over the length of the Fort Wayne and Chicago road? A. Yes. Q. You controlled the road at that time? A. It appeared that they were not going to recognize any man's orders but mine. By Senator Reyburn: Q. But they got obstreperous at last on your hands? A. Towards the last. Q. Didn't you go to a meeting with some citizens to a hall? A. Yes. Q. And there they thought you were taking too much authority on you? A. They thought I was going back on them. At least a scab did. He supposed I was misrepresenting things at that time. At least I think so now. They were starving, and wanted coal, and I ordered a provision train and a coal train out, and one fellow wanted to kill me right off. By Mr. Lindsey: Q. So they struck on you? A. Yes; this was the following Thursday. I had not been down from the Tuesday night when the Governor arrived until this afternoon of Thursday. By Senator Yutzy: Q. What means did you take to enforce your orders after they struck on you?
  • 71. A. They did not strike on me. By Mr. Lindsey: Q. Didn't they refuse to obey your orders? A. I had ceased to exist at that time. That was on the Tuesday night, and this meeting was on Thursday afternoon. Because I would not come up, I suppose they felt sick and sore, and thought I was trying to sell them out. By Senator Reyburn: Q. Those citizens you talked about who offered you arms, were not those men the ones who went with you to the meeting? A. Neither one of them was there. Q. Didn't they ask you to protect this property, and after a conversation with you, didn't you agree to go with them to this meeting and talk to the rioters? A. There were no rioters on the Fort Wayne road. Q. Or the strikers? A. Yes. Q. Didn't you promise them to keep order, and in consideration of that didn't they agree to give you the arms to keep off the mob in case any party came to burn the town? A. No, sir; this was on the Thursday after the fire. I was at no meeting from the 27th day of June until this Thursday. By Mr. Larrabee: Q. Was there no understanding between you and the strikers on the Pennsylvania road during this time, after you got back to Allegheny
  • 72. City and took charge of things—were you acting in concert in preventing trains from going out? A. I don't know that anything particular of that kind was agreed upon. Of course we talked over things of that kind. Q. But you had communications with the parties who were striking on the Pennsylvania road? A. Yes; men were going back and forth all the time. Q. Was there anybody over there that had control of the strike there or who was looked up to as a leader or recognized as such? A. There were some three or four of them. The man supposed to be the leader showed the white feather. Q. Who was that? A. Samuel Muckle, the president of the Pan Handle division. Q. He was supposed to be the leader in the start? A. Yes. Q. Who was their leader after he showed the white feather? A. I don't know, but I think Hice. He was at Torrens station. By Senator Yutzy: Q. How did he show the white feather? A. He was a man who didn't live up to what he said he would do. Q. In what respect? A. He didn't live up to what he said he would do at the meeting. Q. What did he agree to do in the first place? A. He agreed to stand by the boys.
  • 73. Q. What were the boys to do? A. If the boys went out on a strike, Muckle was to stand by them. Q. And prevent the running of trains? A. The understanding was that every man was to quit work and go away, but not to prevent the running of trains. Muckle was discharged, and he tried to get a job in the employ of the road. His object in getting the men to strike was to get them out and then come in and scab it. Q. That is, come in and offer his services to the railroad? A. Yes. By Mr. Larrabee: Q. But were communications going on between you and the leaders of the Pennsylvania road—the leaders of the strike? Was there any concerted movement or action between you? A. No, sir. By Senator Yutzy: Q. Give us a definition of your idea of a strike. What is generally understood by railroad men, or what did the Trainmen's Union understand by a strike? A. So far as the Trainmen's Union was concerned, we considered by a strike that every man on the three grand trunk lines should go home when the hour came—just leave his train standing there. Q. You mean refuse to work? A. Yes. Q. Nothing more?
  • 74. A. That was our understanding. Q. But you were not to prevent other men from working? A. We had an understanding if a man was not a union man to coax him off if we could. Q. But if he would not be coaxed? A. Then to leave him stay. We considered that his own conscience would be enough for him. Q. But you were not to try to drive him off? A. No; a man who is a scab has a hard enough time of it. He has a hard time enough of it to make his life unbearable to him. Q. Was any violence used that you know of to prevent trains from running on the Fort Wayne and Chicago railroad? A. No, sir; none was used. I would not have allowed, so far as I was concerned. Q. By what authority did you assume charge of the Fort Wayne and Chicago railroad? A. I think I assumed authority of the Fort Wayne from telegrams I received from Mr. Layng, who is the general manager from Pittsburgh to Chicago. Q. What were those telegrams? A. I was asked to take charge of the trains and engines, and to move them to places of safety. Q. Have you those dispatches? A. I have. Q. Have you them here?
  • 75. A. No. Q. Can you produce them? A. I can, sir. Q. Will you produce them? A. Not in this city. Q. Where will you produce them? A. I will produce them anywhere where I can get them. I asked to have them sent here, but could not get them. By Mr. Larrabee: Q. Would this strike on the Fort Wayne and Chicago road have occurred if the strike on the Pennsylvania road had not occurred at that time? A. That is a pretty hard question to answer. Q. From your information—from what you know of the circumstances and the men engaged in it? A. I have not thought over that, and really I cannot give an answer. Q. Do you know whether the men on the Fort Wayne and Chicago road were making any preparations for a strike distinct from any strike upon the Pennsylvania railroad? A. Some of them were and some of them were not. Q. At this particular time that the strike occurred? A. Really, I have never thought the matter over, and I cannot answer that question, because I have not thought it over in that light at all. They may have and they may not.
  • 76. Q. You say that the main cause of the strike on the Pennsylvania road was the running of double-headers? A. That is my impression. Q. The cause of the strike upon the Fort Wayne road at that time was what? A. Several things combined. I think it was the abuse of power by the under officials more than anything else. Q. That and the ten per cent.? A. Yes; that was pretty hard to swallow. By Senator Reyburn: Q. I understood you to say in talking to some citizens you had given some figures as to the wages that could be earned after the ten per cent. reduction. Can you give those figures to the committee now? A. I didn't state the amount that could be earned, but the amount they were paying—brakeman, $1 45. Q. Per day? A. Per trip, that is called a day. By Mr. Englebert: Q. How many hours? A. The shortest run on the road was seven hours and twenty-five minutes. The longest run was eight hours and thirty-five minutes. Firemen the same as brakemen. Conductors, first class, $2 12; second class, $1 89 or $1 91, I forget which. Engineers—I don't remember the classified pay—first class, three dollars and eleven or twelve cents. That had a great deal to do with the strike—the classification—so far as the engineers were concerned.
  • 77. By Mr. Lindsey: Q. How many days could you average per week? A. The year around, or at that time? Q. At that time? A. I think the month that I was discharged I drew twenty-nine dollars and some cents—I don't know what. By Senator Yutzy: Q. As brakeman? A. Yes. I had an income of forty dollars a month besides that, and it was the only way I could live. By Mr. Lindsey: Q. Did you make all the time? A. I believe I did. I believe I lost only one trip. My impression is I did lose one trip. By Senator Reyburn: Q. Was not the amount you could earn governed by the amount of business doing by the road at that time—if the freight shipments were large you all got work? A. We all had work any how. We all came in our turn. Q. But the amount of money you made depended on the amount of the business of the road? A. Yes. By Mr. Lindsey:
  • 78. Q. You put in your six days a week—work a week at $1 40? A. I undoubtedly worked six days. Q. Every week? A. Not at that time. We were not averaging six days' work at that time. Q. Were you prior to that time? A. Really I have forgot; but the pay was running very poor. I think the business was good in January and February, March and April, but I think after that time it was very slack. By Senator Yutzy: Q. How many days did you make in any one month? A. In the month of January I made forty-four days. Q. By over work? A. Yes. By Senator Reyburn: Q. Did not the officials, when you sent your committee to them, didn't they talk over this matter with you? A. Before the strike? Q. Yes. A. No, sir. Q. Didn't you send a committee down to Philadelphia to see Mr. Scott? A. Of engineers, I believe. We heard what the engineers were doing, and got enough of the engineers. They generally patched things up
  • 79. for themselves. They didn't look after anything else. It was about the time of taking the ten per cent. off. By Mr. Engelbert: Q. What position did you hold in Trainmen's Union? A. I don't know that I held any position. I was appointed to organize the unions, and had unlimited powers. By Senator Yutzy: Q. By whom? A. By what we called—there were members appointed from each division, and they constituted a sort of grand lodge. The division I belonged to was first organized. That is where I got my power from. They sent me right out. It was a Saturday night, and I left Pittsburgh the following Monday, June 4. Q. Who organized the first lodge? A. I was the first man to take an oath. I guess all took a hand in it. Q. Were you president of that lodge? A. There was no president of that lodge at that time. Q. Were you chief of that lodge? A. I suppose I was that night. Q. What did they call the chief of that lodge—what name? A. The grand organizer. Q. Then by delegations from other lodges, you were appointed to organize lodges throughout the country?
  • 80. A. Our lodge gave me authority, and as we formed lodges, they sent in delegations to form a grand lodge, and they confirmed the action of our lodge. By Mr. Larrabee: Q. Who paid your expenses going around? A. The boys. Q. As a union or a society, or did the boys contribute what they saw fit? A. All the money I ever got, I got from the union at that time. By Mr. Lindsey: Q. From the lodge? A. Yes; from the treasurer of the lodge. By Senator Yutzy: Q. Was it an oath-bound association? A. Yes. By Mr. Means: Q. Did you go to Martinsburg, Virginia? A. I was in that neighborhood. Q. Were you at Martinsburg, Virginia? A. I was very near to it. Q. That is not an answer to my question. A. At what time?
  • 81. Q. To organize a lodge there before the strike? A. I did initiate men into the organization called the Trainmen's Union, at Martinsburg. By Senator Yutzy: Q. Did you organize lodges over the Baltimore and Ohio road? A. Yes. By Mr. Means: Q. Was it understood by your lodges that this strike was to commence at Martinsburg? A. No, sir. Q. Did you know, before the strike commenced at Martinsburg, Virginia, that it was going to take place? A. No; of course I heard all that talk. They talked most loud at Martinsburg, but I thought it was all wind. I didn't think they would strike at all. By Senator Yutzy: Q. When you were telegraphed at Oil City, were you there for the purpose of organizing lodges? A. It was Parker City. Q. Were you there for the purpose of organizing lodges? A. At that time? Q. Yes? A. I went up there to get work.
  • 82. By Mr. Lindsey: Q. How long had you been railroading? A. About eleven months altogether. Q. What had been your business before that? A. I was in the hotel business. Q. Where? A. At Collinwood, eight miles from Cleveland. Q. Were you proprietor of the hotel? A. Yes. Q. For how long? A. One year and nine months. Q. What was your business before that? A. I was in the insurance business. Q. Where? A. At Pittsburgh. Q. Is that your home? A. Yes; it is my native place. By Senator Yutzy: Q. Were you working for your father or for yourself in the insurance business? A. I represented four Chicago companies for myself.
  • 83. Q. When you returned from the oil country, you say you met some railroad men who belonged to the Baltimore and Ohio railroad? A. Of the Connellsville division. Q. Where did you meet them? A. Around the Union depot. Q. How many of them did you meet there? A. I remember three engineers who were there. Q. Any other trainmen? A. O, yes. Q. Of the Baltimore and Ohio road? A. These three engineers are all I can remember. Q. Were they the ones who telegraphed to you to come to Pittsburgh? A. No. Q. Where did those men belong to—the Baltimore and Ohio or the Pennsylvania Central? Who telegraphed you? A. To neither road. Q. Of what road were they employés? A. Of the Fort Wayne road. By Mr. Dewees: Q. How many miles of railroad had this trouble? A. I never figured it up. A good many miles. By Senator Reyburn:
  • 84. Q. You had a signal to stop trains? A. You can stop any train if you have the signal. Q. But did not your organization have a particular signal by which you could stop the trains? A. The Trainmen's Union? Q. Yes? A. Before the strike? Q. Yes? A. No, sir. By Senator Yutzy: Q. Different from the ordinary signal? A. I don't comprehend the question exactly. By Senator Reyburn: Q. Was not there an understood signal among the trainmen by which, if an engineer of a train undertook to run it, they would throw him this signal, and he would stop the train and get off? By Senator Yutzy: Q. Some peculiar signal? A. No; I saw lots of engineers that wanted the boys to do that. By Mr. Larrabee: Q. You say then that there was no signal? A. No.
  • 85. Welcome to our website – the perfect destination for book lovers and knowledge seekers. We believe that every book holds a new world, offering opportunities for learning, discovery, and personal growth. That’s why we are dedicated to bringing you a diverse collection of books, ranging from classic literature and specialized publications to self-development guides and children's books. More than just a book-buying platform, we strive to be a bridge connecting you with timeless cultural and intellectual values. With an elegant, user-friendly interface and a smart search system, you can quickly find the books that best suit your interests. Additionally, our special promotions and home delivery services help you save time and fully enjoy the joy of reading. Join us on a journey of knowledge exploration, passion nurturing, and personal growth every day! ebookbell.com