You are on page 1of 13

12 10 2012

Build a .NET Application on the Oracle Database with Microsoft Visual Studio 2010

Sign In/Register for Account Help Select Country/Region

Communities

I am a...

I w ant to...

Search

PRODUCTS AND SERVICES Oracle Technology Network

SOLUTIONS Articles .NET

DOWNLOADS

STORE

SUPPORT

TRAINING

PARTNERS

ABOUT

Oracle Technology Netw ork

Application Development Framew ork Application Express Big Data Business Intelligence Cloud Computing Communications Database Performance & Availability Data Warehousing .NET Dynamic Scripting Languages Embedded Social Enterprise Enterprise Architecture Enterprise Management Identity & Security Java Linux Service-Oriented Architecture SQL & PL/SQL Server and Storage Administration Server and Storage Development Systems Hardw are and Architecture Systems

Build a .NET Application on the Oracle Database with Microsoft Visual Studio 2010 b y John Paul Cook Learn the basic yet essential processes involved in building a .NET application that uses an Oracle database.
Published June 2011

With the popularity of Microsoft's .NET Framework, many developers are hungry for information about the best means of integrating .NET applications with Oraclenot only in terms of basic connectivity, but also in relationship to effective and efficient application development using Microsoft Visual Studio 2010. (The Visual Studio 2005/2008 version of this article is found here. ) In this article, I'll explain the basic yet essential processes involved in building a C# or Visual Basic .NET application that uses an Oracle database, including: How to add project references to support Oracle class libraries in your .NET project How to create Oracle Database connection strings How to work with Connection, Command, and DataReader objects You will have the opportunity to apply what you have learned in three practice labs, ranging in difficulty from the relatively simple to the more complex. If you are already familiar with building .NET applications for Oracle Database with Visual Studio 2005/2008, the experience with Visual Studio 2010 is very similar. For information and labs about how to secure your application, see my article "Securing a .NET Application on the Oracle Database." (Also, see the OTN .NET Developer Center for technical articles covering a range of Oracle .NET application lifecycle issues.) Note that the free Oracle Developer Tools for Visual Studio, available for download from OTN, provides a Visual Studio add-in that makes the development of .NET apps on Oracle much easier and more intuitive. That subject is beyond our scope here, however; see the Oracle Developer Tools for Visual Studio Product Center for more information.

.NET Data Provider


In addition to basic Oracle client connectivity software, .NET applications require the use of what is known as a managed data provider (where "managed" refers to code managed by the .NET framework). The data provider is the layer between the .NET application code and the Oracle client connectivity software. In almost every case, the best performance is achieved by using a provider optimized for a specific database platform instead of the generic .NET OLE DB data provider. Oracle, Microsoft, and third-party vendors all offer .NET data providers optimized for an Oracle database. Oracle and Microsoft make their Oracle data providers available for free. Microsoft's provider for the .NET Framework is deprecated. Oracle continues to support and develop their .NET data provider, Oracle Data Provider for .NET (ODP.NET). In this article, we will use ODP.NET, which is included with the Oracle Database or as a separate download. ODP.NET provides standard ADO.NET data access, while exposing Oracle database-specific features, such as XML DB, data access performance optimizations, and Real Application Clusters load balancing and fast connection failover. The current ODP.NET version, 11.2, supports connecting to Oracle Database 9i Release 2 servers and higher versions. The database server can be on Windows, Linux, UNIX, or any other operating system platform Oracle database supports. When ODP.NET and Oracle client software are installed, application development using Visual Studio can begin. It's a good idea to confirm client connectivity before starting development. If you can connect to Oracle Database using Oracle client software, such as SQL*Plus on the same machine as Visual Studio, then your Oracle client-side software is properly installed and configured. If you are new to Oracle, see the section "Installing .NET Products" in the Oracle Datab ase 2 Day Developer's Guide for background information regarding installing and configuring ODP.NET specifically, or to the Oracle Database Documentation Library for general information about Oracle Database.

Creating a Project in Visual Studio 2010


Lets create an ODP.NET application that retrieves data from the Oracle database. Later, well see how to perform error handling with ODP.NET and handle an additional data retrieval scenario. After starting Visual Studio, the first task is to create a project. You can either click New Project as shown below or select File | New | Project.

www.oracle.com/technetwork/articles/dotnet/vs2010-oracle-dev-410461.html

1/13

12 10 2012

Build a .NET Application on the Oracle Database with Microsoft Visual Studio 2010

Figure 1 Creating a new project in Visual Studio 2010 A New Project dialog box appears. On the left side of the dialog box under Installed Templates, select the programming language of your choice. In our example, Visual Basic was chosen. On the middle of the dialog, choose a project template. To keep things simple, a Windows Forms Application is selected.

Figure 2 Using the New Project dialog You'll want to specify meaningful names for the project name (we used OraWinApp) and the solution name (we used OraWinApp). A solution contains one or more projects. When a solution contains only one project, many people use the same name for both. Notice that there is a dropdown list box allowing you to specify which version of the .NET Framework you want to target. If you are writing applications for an older

www.oracle.com/technetwork/articles/dotnet/vs2010-oracle-dev-410461.html

2/13

12 10 2012

Build a .NET Application on the Oracle Database with Microsoft Visual Studio 2010
version of the .NET Framework, you should select the appropriate version from the dropdown list. Click the Ok button to continue. Adding a Reference Because our project must connect to an Oracle database, it is necessary to add a reference to the ODP.NET DLL containing the data provider of our choice. Within the Solution Explorer on the right side of Visual Studio, select the project name, right click and select Add Reference. Alternatively, you can go to the menu bar and select Project and then select Add Reference.

Figure 3 Adding a reference The Add Reference dialog box appears. Select the .NET tab. Visual Studio will construct a list of .NET components available for you to add to your project. This may take several seconds. When complete, you can click on the Component Name column to alphabetize the component list.

Figure 4 Selecting the ODP.NET Managed Data Provider for .NET 4

www.oracle.com/technetwork/articles/dotnet/vs2010-oracle-dev-410461.html

3/13

12 10 2012

Build a .NET Application on the Oracle Database with Microsoft Visual Studio 2010
ODP.NET is found under the Oracle.DataAccess component name. Select Oracle.DataAccess from the list, then click the OK button to make the ODP.NET data provider known to your project. Be sure to select the correction version. Since this is a .NET 4 project, the 4.112.2.0 version of Oracle.DataAccess was chosen here, but you can chose any ODP.NET version beginning with 4. Visual Basic/C# Statements After adding references, it is standard practice to add Visual Basic Imports statements or C# using statements. Technically, these statements are not required, but they do allow you to refer to database objects without using lengthy, fully qualified names. By convention, these statements appear at or near the top of a code file, before the namespace or class declaration. IprsOal.aacesCin 'Vsa BscOPNTOal mngdpoie mot rceDtAcs.let iul ai D.E rce aae rvdr uigOal.aacesCin;/ C OPNTOal mngdpoie sn rceDtAcs.let / # D.E rce aae rvdr If you added the reference, Intellisense will help you complete the addition of an Imports or using statement as shown in Figure 5.

Figure 5 Adding an Imports statement in Visual Basic Connection Strings and Objects An Oracle connection string is inseparable from Oracle names resolution. In this article, we will connect to Oracles sample HR schema with user id hr and password hr. The tnsnames.ora file is an Oracle network configuration file that defines database addresses for establishing connections. Suppose we had a database alias of OraDb defined in a tnsnames.ora file as follows: Oab rD= (ECITO= DSRPIN (DRS_IT ADESLS= (DRS=POOO=C)HS=RSV)PR=51) ADES(RTCLTP(OTOARR(OT12) ) (ONC_AA CNETDT= (EVRDDCTD SRE=EIAE) (EVC_AEOC) SRIENM=RL ) ) The OraDb alias defines the database address connection information for the client. To use the OraDb alias defined in the tnsnames.ora file shown above, you would use the following syntax: DmoabA Srn ="aaSuc=rD;srI=rPswr=r"'Vsa Bsc i rd s tig Dt oreOabUe dh;asodh; iul ai srn oab="aaSuc=rD;srI=rPswr=r" / C tig rd Dt oreOabUe dh;asodh;; / # You can modify the connection string to obviate the need for the tnsnames.ora file, however. Simply replace the name of the alias with how it would be defined in a tnsnames.ora file. The database alias in this article is specific to my database setup. (Click here for more information about creating a database alias for your database.) 'Vsa Bsc iul ai DmoabA Srn ="aaSuc=DSRPIN"_ i rd s tig Dt ore(ECITO= +"ADES(RTCLTP(OTOARR(OT12)"_ (DRS=POOO=C)HS=RSV)PR=51) +"CNETDT=SRIENM=RL); _ (ONC_AA(EVC_AEOC))" +"srI=rPswr=r" Ue dh;asodh; / C / #

www.oracle.com/technetwork/articles/dotnet/vs2010-oracle-dev-410461.html

4/13

12 10 2012

Build a .NET Application on the Oracle Database with Microsoft Visual Studio 2010
srn oab="aaSuc=DSRPIN" tig rd Dt ore(ECITO= +"ADES(RTCLTP(OTOARR(OT12)" (DRS=POOO=C)HS=RSV)PR=51) +"CNETDT=SRIENM=RL); (ONC_AA(EVC_AEOC))" +"srI=rPswr=r" Ue dh;asodh;; As you can see above, the username and password are embedded in the connection string in clear text. This is the simplest approach to creating a connection string. However, the clear text approach is undesirable from a security perspective. In particular, you must understand that compiled .NET application code is only marginally more secure than the clear text source code files. It is very easy to decompile .NET DLL and EXE files and view the original clear text contents. (Encryption is in fact the appropriate solution, but that subject would be a quite lengthy digression from our discussion here.) Next, you must instantiate a connection object from the connection class. The connection string must be associated with the connection object. Dmcn A NwOalCneto(rd)'Vsa Bsc i on s e rceoncinoab iul ai OalCneto cn =nwOalCneto(rd) / C rceoncin on e rceoncinoab; / # Notice that the connection string is associated with the connection object by being passed through the object's constructor, which is overloaded. The constructor's other overload allows the following alternative syntax: Dmcn A NwOalCneto( 'Vsa Bsc i on s e rceoncin) iul ai cn.oncintig=oab onCnetoSrn rd OalCneto cn =nwOalCneto(;/ C rceoncin on e rceoncin) / # cn.oncintig=oab onCnetoSrn rd; After associating a connection string with a connection object, use the Open method to make the actual connection. cn.pn)'Vsa Bsc onOe( iul ai cn.pn) / C onOe(; / # We'll cover error handling later. Command Object The command object is used to specify the SQL command text that is executed, either a SQL string or a stored procedure. Similar to the connection object, it must be instantiated from its class and it has an overloaded constructor. In this sample, ODP.NET will perform a SQL query to return the department_name from the departments table where the department_id is 10. DmslA Srn ="eetdprmn_aefo dprmnsweedprmn_d=1"'Vsa Bsc i q s tig slc eatetnm rm eatet hr eateti 0 iul ai DmcdA NwOalCmadsl cn) i m s e rceomn(q, on cdCmadye=CmadyeTx m.omnTp omnTp.et srn sl="slc dprmn_aefo dprmnsweedprmn_d=1" / C tig q eet eatetnm rm eatet hr eateti 0; / # OalCmadcd=nwOalCmadsl cn) rceomn m e rceomn(q, on; cdCmadye=CmadyeTx; m.omnTp omnTp.et Using different overloads, the syntax can be structured slightly differently. The command object has methods for executing the command text, which will be seen in the next section. Different methods are appropriate for different types of SQL commands. Retrieving a Scalar Value Retrieving data from the database can be accomplished by instantiating an OracleDataReader object and using the OracleCommands ExecuteReader method, which returns an OracleDataReader object. Returned data is accessible by passing either the column name or zerobased column ordinal to the OracleDataReader. Dmd A OalDtRae =cdEeueedr)'Vsa Bsc i r s rceaaedr m.xctRae( iul ai d.ed) rRa( Lbl.et=d.tm"eatetnm" 'rtiv b clm nm ae1Tx rIe(dprmn_ae) eree y oun ae Lbl.et=d.tm0 'rtiv tefrtclm i teslc ls ae1Tx rIe() eree h is oun n h eet it Lbl.et=d.eSrn()'rtr a.E dt tp ae1Tx rGttig0 eun NT aa ye Lbl.et=d.eOalSrn()'rtr a Oal dt tp ae1Tx rGtrcetig0 eun n rce aa ye C# developers must use accessor type methods for retrieving data. There are typed accessors for returning .NET native data types and others for returning native Oracle data types, all of which are available in C#, Visual Basic, or any other .NET language. Zero-based ordinals are passed to the accessors to specify which column to return. OalDtRae d =cdEeueedr) / C rceaaedr r m.xctRae(; / # d.ed) rRa(; lbl.et=d[dprmn_ae]TSrn(;/ C rtiv b clm nm ae1Tx r"eatetnm".otig) / # eree y oun ae lbl.et=d.eSrn()TSrn(; / rtr a.E dt tp ae1Tx rGttig0.otig) / eun NT aa ye lbl.et=d.eOalSrn()TSrn(; / rtr a Oal dt tp ae1Tx rGtrcetig0.otig) / eun n rce aa ye In this simplified example, the returned value of department_name is a string and is used to set the value of the label control's text property, which is also a string. But if department_id, which is not a string, had been retrieved instead, there would be a data type mismatch. The .NET runtime attempts to implicitly convert from one data type to another when the source and destination data types don't match. Sometimes the data types are incompatible and the implicit conversion fails, throwing an exception. But even when it works, it's still better to use explicit data type conversions instead of implicit data type conversion. An explicit cast to integer is shown below: Lbl.et=Ct(rIe(dprmn_d) 'Vsa Bscitgrt srn cs ae1Tx Srd.tm"eateti") iul ai nee o tig at C# is not as forgiving as Visual Basic on implicit conversions. You'll find yourself doing explicit conversions: lbl.et=d.eIt6"eateti".otig) / C ae1Tx rGtn1(dprmn_d)TSrn(; / # You can explicitly cast scalar values as well as arrays. Close and Dispose Either the connection object's Close or the Dispose method should be called to close the connection to the database. The Dispose method calls the Close method implicitly.

www.oracle.com/technetwork/articles/dotnet/vs2010-oracle-dev-410461.html

5/13

12 10 2012

Build a .NET Application on the Oracle Database with Microsoft Visual Studio 2010
cn.ls( onCoe) 'Vsa Bsc iul ai cn.ips( 'Vsa Bsc onDsoe) iul ai cn.ls(; / C onCoe) / # cn.ips(;/ C onDsoe) / # You don't have to explicitly call Close or Dispose if you use VB's Using keyword or C#'s using keyword. uig(rceoncincn =nwOalCneto(rd) / C sn OalCneto on e rceoncinoab) / # { cn.pn) onOe(; OalCmadcd=nwOalCmad) rceomn m e rceomn(; cdCneto =cn; m.oncin on cdCmadet="eetdprmn_aefo dprmnsweedprmn_d=1" m.omnTx slc eatetnm rm eatet hr eateti 0; cdCmadye=CmadyeTx; m.omnTp omnTp.et OalDtRae d =cdEeueedr) rceaaedr r m.xctRae(; d.ed) rRa(; lbl.et=d.eSrn() ae1Tx rGttig0; } In addition, OracleCommand includes a Dispose method; OracleDataReader includes a Close and Dispose method. Closing and disposing .NET objects free up system resources, ensuring more efficient application performance, which is especially important under high load conditions. You can experiment with some of the concepts we've learned here in Lab 1 (Retrieving Data from the Database) and Lab 2 (Adding Interactivity). Error Handling When an error occurs, .NET applications should gracefully handle the error and inform the user with a meaningful message. Try-Catch-Finally structured error handling is a part of .NET languages. Here is a relatively minimalist example of using the Try-Catch-Finally syntax: 'Vsa Bsc iul ai Ty r cn.pn) onOe( DmcdA NwOalCmad i m s e rceomn cdCneto =cn m.oncin on cdCmadet="eetdprmn_aefo dprmns"_ m.omnTx slc eatetnm rm eatet +"hr dprmn_d="+TxBx.et wee eateti eto1Tx cdCmadye=CmadyeTx m.omnTp omnTp.et I d.ed)Te f rRa( hn Lbl.et=d.tm"eatetnm" 'o ued.tm0 ae1Tx rIe(dprmn_ae) r s rIe() EdI n f Cthe A Ecpin'cthsayerr ac x s xeto ace n ro Msaeo.hwe.esg.otig) esgBxSo(xMsaeTSrn() Fnly ial 'I ara apiain ptcenpcd hr. n el plcto, u lau oe ee EdTy n r / C / # ty r { cn.pn) onOe(; OalCmadcd=nwOalCmad) rceomn m e rceomn(; cdCneto =cn; m.oncin on cdCmadet="eetdprmn_aefo dprmnsweedprmn_d="+txBx.et m.omnTx slc eatetnm rm eatet hr eateti eto1Tx; cdCmadye=CmadyeTx; m.omnTp omnTp.et i (rRa()/ C f d.ed) / # { lbl.et=d[dprmn_ae]TSrn(; ae1Tx r"eatetnm".otig) / o ued.eOalSrn()TSrn( / r s rGtrcetig0.otig) } } cth(xeto e)/ cthsayerr ac Ecpin x / ace n ro { Msaeo.hwe.esg.otig); esgBxSo(xMsaeTSrn() } fnly ial { / I ara apiain ptcenpcd hr. / n el plcto, u lau oe ee } Although this approach will gracefully capture any errors in attempting to get data from the database, it is not user friendly. For example, look at the following message displayed when the database is unavailable:

Figure 6 An ORA-12545 error caught and displayed to the user An ORA-12545 is quite meaningful for an Oracle DBA or developer, but not for an end user. A better solution is to add an additional Catch statement to trap for the most common database errors and provide user-friendly messages. 'Vsa Bsc iul ai

www.oracle.com/technetwork/articles/dotnet/vs2010-oracle-dev-410461.html

6/13

12 10 2012

Build a .NET Application on the Oracle Database with Microsoft Visual Studio 2010
Cthe A OalEcpin'cthsol Oal err ac x s rcexeto ace ny rce ros Slc Cs e.ubr eet ae xNme Cs 1 ae Msaeo.hw"ro atmtn t isr dpiaedt.) esgBxSo(Err tepig o net ulct aa" Cs 155 ae 24 Msaeo.hw"h dtbs i uaalbe" esgBxSo(Te aaae s nvial.) Cs Es ae le Msaeo.hw"aaaeerr "+e.esg.otig) esgBxSo(Dtbs ro: xMsaeTSrn() EdSlc n eet Cthe A Ecpin'cthsayerr ac x s xeto ace n ro Msaeo.hwe.esg.otig) esgBxSo(xMsaeTSrn() / C / # cth(rcexeto e)/ cthsol Oal err ac OalEcpin x / ace ny rce ros { sic (xNme) wth e.ubr { cs 1 ae : Msaeo.hw"ro atmtn t isr dpiaedt.) esgBxSo(Err tepig o net ulct aa"; bek ra; cs 155 ae 24: Msaeo.hw"h dtbs i uaalbe"; esgBxSo(Te aaae s nvial.) bek ra; dfut eal: Msaeo.hw"aaaeerr "+e.esg.otig); esgBxSo(Dtbs ro: xMsaeTSrn() bek ra; } } cth(xeto e)/ cthsayerrntpeiul cuh ac Ecpin x / ace n ro o rvosy agt { Msaeo.hwe.esg.otig); esgBxSo(xMsaeTSrn() } Notice the two Catch statements in the code sample above. If there aren't any Oracle errors to catch, the first Catch statement branch is skipped, leaving any other non-Oracle error to be caught by the second Catch statement. Catch statements must be ordered in the code from most specific to most general. After implementing the user-friendly exception handling code, the ORA-12545 error message appears as follows:

Figure 7 A user-friendly error message for an ORA-12545 error The Finally code block is always executed regardless of whether or not an error occurred. It is where cleanup code belongs. If you don't use Using or using, you should dispose your connection and other objects in the Finally code block.

Retrieving Multiple Values Using a DataReader


Thus far our examples have only showed how to retrieve a single value. An OracleDataReader can retrieve values for multiple columns and multiple rows. First consider a multiple column, single row query: slc dprmn_d dprmn_ae lcto_dfo dprmnsweedprmn_d=1 eet eateti, eatetnm, oaini rm eatet hr eateti 0 To keep things simple for this article, we are using a single table, the departments table. To obtain the values of the columns, either zero-based ordinals or column names can be used. Ordinals are relative to the order in the query. Thus, the location_id column's value can be retrieved in Visual Basic by using either dr.Item(2) or dr.Item("location_id"). Here is a code snippet that concatenates the department_name and location_id columns from the previous query: Lbl.et="h "+d.tm"eatetnm" +"dprmn i i "_ ae1Tx Te rIe(dprmn_ae) eatet s n +d.tm"oaini" 'V rIe(lcto_d) B lbl.et="h "+d[dprmn_ae]TSrn( +"dprmn i i "+ ae1Tx Te r"eatetnm".otig) eatet s n d[lcto_d]TSrn(; / C r"oaini".otig) / # Now consider a query that returns multiple rows: slc dprmn_d dprmn_ae lcto_dfo dprmns eet eateti, eatetnm, oaini rm eatet To process multiple rows returned from an OracleDataReader, some type of looping construct is needed. Furthermore, a control that can display multiple rows is desirable. An OracleDataReader is a forward-only, read-only cursor, so it can't be bound to an updateable or fully scrollable control such as a Windows Forms DataGrid control. An OracleDataReader is compatible with a ListBox control, as the following code snippet illustrates: Wied.ed)'Vsa Bsc hl rRa( iul ai LsBx.tm.d(Te"+d.tm"eatetnm" _ ito1IesAd"h rIe(dprmn_ae) +"dprmn i i "+d.tm"oaini") eatet s n rIe(lcto_d) EdWie n hl wie(rRa()/ C hl d.ed) / # { lsBx.tm.d(Te"+d[dprmn_ae]TSrn( +"dprmn i i "+ ito1IesAd"h r"eatetnm".otig) eatet s n d[lcto_d]TSrn() r"oaini".otig); } Lab 3 (Retrieve Multiple Columns and Rows with an OracleDataReader) highlights some of these concepts.

www.oracle.com/technetwork/articles/dotnet/vs2010-oracle-dev-410461.html

7/13

12 10 2012

Build a .NET Application on the Oracle Database with Microsoft Visual Studio 2010 Building and Running on Windows x64
When running Visual Studio 2010 on a Windows x64 operating system, you can use the Configuration Manager to change the target platform type. Select the solution in the Solution Explorer, right-click, and select Configuration Manager.

Figure 8 You can use the Configuration Manager to change the target platform type when building on Windows x64.

Summary
This article has introduced you to the process of accessing Oracle databases using .NET programming languages. You should now have the capability to connect to the database and retrieve multiple columns and rows.

Lab 1: Retrieving Data from the Database


We begin with the requirement that you've created a project and added a reference as shown previously in this article. Continue by adding a button control and a label control to the Windows form. Be sure to leave room above the controls to allow additions that will be made in Lab 2.

www.oracle.com/technetwork/articles/dotnet/vs2010-oracle-dev-410461.html

8/13

12 10 2012

Build a .NET Application on the Oracle Database with Microsoft Visual Studio 2010

Figure 9 Lab 1 form with button and label controls Add code to retrieve data from the Oracle database and display the results on the form. Put the code in a click event handler for the button. The easiest way to get started with this task is to double click the button because it will create a stub for the event handler.

Figure 10 Click event handler stub. Add Visual Basic Imports statements before the Public Class declaration or C# using statements before the namespace declaration. IprsOal.aacesCin 'Vsa Bsc OPNTOal mngdpoie mot rceDtAcs.let iul ai, D.E rce aae rvdr uigOal.aacesCin;/ C,OPNTOal mngdpoie sn rceDtAcs.let / # D.E rce aae rvdr Add the Visual Basic version of the click event handler code between the Private Sub and End Sub statements (be sure to replace ORASRVR with your server's host name and replace the service name entry with your databases service name): DmoabA Srn ="aaSuc=DSRPIN(DRS_IT"_ i rd s tig Dt ore(ECITO=ADESLS= +"ADES(RTCLTP(OTOARR(OT12)) _ (DRS=POOO=C)HS=RSV)PR=51)" +"CNETDT=SRE=EIAE)SRIENM=RL); _ (ONC_AA(EVRDDCTD(EVC_AEOC))" +"srI=rPswr=r" Ue dh;asodh; Dmcn A NwOalCneto(rd)'Vsa Bsc i on s e rceoncinoab iul ai cn.pn) onOe( DmcdA NwOalCmad i m s e rceomn cdCneto =cn m.oncin on cdCmadet=_ m.omnTx "eetdprmn_aefo dprmnsweedprmn_d=1" slc eatetnm rm eatet hr eateti 0 cdCmadye=CmadyeTx m.omnTp omnTp.et

www.oracle.com/technetwork/articles/dotnet/vs2010-oracle-dev-410461.html

9/13

12 10 2012

Build a .NET Application on the Oracle Database with Microsoft Visual Studio 2010
Dmd A OalDtRae =cdEeueedr) i r s rceaaedr m.xctRae( d.ed) 'rpaeti saeeti nx lb rRa( elc hs ttmn n et a Lbl.et=d.tm"eatetnm" 'o d.tm0,rmv i nx lb ae1Tx rIe(dprmn_ae) r rIe() eoe n et a d.ips( rDsoe) cdDsoe) m.ips( cn.ips( onDsoe) Add the following C# code to the click event handler between the { and } curly braces for the button's click event handler (be sure to replace ORASRVR with your server's host name and replace the service name entry with your databases service name): srn oab="aaSuc=DSRPIN(DRS_IT" tig rd Dt ore(ECITO=ADESLS= +"ADES(RTCLTP(OTOARR(OT12)) (DRS=POOO=C)HS=RSV)PR=51)" +"CNETDT=SRE=EIAE)SRIENM=RL); (ONC_AA(EVRDDCTD(EVC_AEOC))" +"srI=rPswr=r" Ue dh;asodh;; OalCneto cn =nwOalCneto(rd) / C rceoncin on e rceoncinoab; / # cn.pn) onOe(; OalCmadcd=nwOalCmad) rceomn m e rceomn(; cdCneto =cn; m.oncin on cdCmadet= m.omnTx "eetdprmn_aefo dprmnsweedprmn_d=1" slc eatetnm rm eatet hr eateti 0; cdCmadye=CmadyeTx; m.omnTp omnTp.et OalDtRae d =cdEeueedr) rceaaedr r m.xctRae(; d.ed) / rpaeti saeeti nx lb rRa(; / elc hs ttmn n et a lbl.et=d[dprmn_ae]TSrn(; / rmv i nx lb ae1Tx r"eatetnm".otig) / eoe n et a d.ips(; rDsoe) cdDsoe) m.ips(; cn.ips(; onDsoe) Run the application. Click the button. You should see the following:

Figure 11 Data successfully retrieved

Lab 2: Adding Interactivity


Now that the basics of database access are implemented in the code, the next step is to add interactivity to the application. Instead of running the hard coded query, a textbox control can be added to accept a user input for the department number (i.e., department_id). Add a textbox control and another label control to the form as shown below. Set the text property of the Label2 control to Enter department_id: and make sure that the Text property of TextBox1 isn't set to anything.

www.oracle.com/technetwork/articles/dotnet/vs2010-oracle-dev-410461.html

10/13

12 10 2012

Build a .NET Application on the Oracle Database with Microsoft Visual Studio 2010

Figure 12 Lab 2 form with button and label controls Modify the code that defines the select string: cdCmadet=_ m.omnTx "eetdprmn_aefo dprmnsweedprmn_d=" slc eatetnm rm eatet hr eateti _ +TxBx.et'B eto1Tx V cdCmadet="eetdprmn_aefo dprmnsweedprmn_d="+txBx.et / C m.omnTx slc eatetnm rm eatet hr eateti eto1Tx; / # Run the application. Test the application by entering 10 for the department_id. Retest the application by entering an invalid department_id (e.g., 12). The application will abort.

Figure 13 An unhandled exception Modify your code to prevent an error when an invalid department_id is entered. Recall that the ExecuteReader method actually returns an object. Replace the line containing dr.Read with all of the following statements. I d.ed)Te 'Vsa Bsc f rRa( hn iul ai Lbl.et=d.tm"eateti".otig) ae1Tx rIe(dprmn_d)TSrn( Es le Lbl.et="eateti ntfud ae1Tx dprmn_d o on" EdI n f i (rRa()/ C f d.ed) / # { lbl.et=d[dprmn_d]TSrn(; ae1Tx r"eateti".otig); }

www.oracle.com/technetwork/articles/dotnet/vs2010-oracle-dev-410461.html

11/13

12 10 2012

Build a .NET Application on the Oracle Database with Microsoft Visual Studio 2010
es le { lbl.et="eateti ntfud; ae1Tx dprmn_d o on" } Test the application by entering a department_id that does not exist. Now the application no longer aborts. Enter the letter A instead of a number and click the button. The application aborts. Clearly, our application needs a better approach to handling errors. Although it could be argued that the application should not allow the user to make invalid inputs that would cause an error, ultimately the application must have robust error handling added. Not all errors are preventable, so error handling must be implemented.

Lab 3: Retrieve Multiple Columns and Rows with an OracleDataReader


Now that a single value has been retrieved, the next step is to retrieve multiple columns and rows with an OracleDataReader. A ListBox control is added to the form to display the results. Add a ListBox control to the form. Resize the control to fill most of the width of the form as shown below.

Figure 14 Form with ListBox added Remove the where clause from the query and add the additional columns: cdCmadet=_ m.omnTx "eetdprmn_d dprmn_ae lcto_dfo dprmns 'V slc eateti, eatetnm, oaini rm eatet" B cdCmadet="eetdprmn_d dprmn_ae lcto_dfo dprmns" / C m.omnTx slc eateti, eatetnm, oaini rm eatet ; / # The query results will be read in a while loop and will populate the ListBox control. Modify your Visual Basic code to look like this, making the appropriate changes to the host and service name for your database: DmoabA Srn ="aaSuc=DSRPIN(DRS_IT"_ i rd s tig Dt ore(ECITO=ADESLS= +"ADES(RTCLTP(OTOARR(OT12)) _ (DRS=POOO=C)HS=RSV)PR=51)" +"CNETDT=SRE=EIAE)SRIENM=RL); _ (ONC_AA(EVRDDCTD(EVC_AEOC))" +"srI=rPswr=r" Ue dh;asodh; Dmcn A NwOalCneto(rd)'Vsa Bsc i on s e rceoncinoab iul ai cn.pn) onOe( DmcdA NwOalCmad i m s e rceomn cdCneto =cn m.oncin on cdCmadet=_ m.omnTx "eetdprmn_d dprmn_ae lcto_dfo dprmns 'V slc eateti, eatetnm, oaini rm eatet" B cdCmadye=CmadyeTx m.omnTp omnTp.et Dmd A OalDtRae =cdEeueedr) i r s rceaaedr m.xctRae( Wied.ed) hl rRa( LsBx.tm.d(Te"+d.tm"eatetnm" +_ ito1IesAd"h rIe(dprmn_ae) "dprmn i i "+d.tm"oaini".otig) eatet s n rIe(lcto_d)TSrn() EdWie n hl d.ips( rDsoe) cdDsoe) m.ips( cn.ips( onDsoe) Mdf yu C cd t lo lk ti: oiy or # oe o ok ie hs srn oab="aaSuc=DSRPIN(DRS_IT" tig rd Dt ore(ECITO=ADESLS= +"ADES(RTCLTP(OTOARR(OT12)) (DRS=POOO=C)HS=RSV)PR=51)" +"CNETDT=SRE=EIAE)SRIENM=RL); (ONC_AA(EVRDDCTD(EVC_AEOC))" +"srI=rPswr=r" Ue dh;asodh;;

www.oracle.com/technetwork/articles/dotnet/vs2010-oracle-dev-410461.html

12/13

12 10 2012

Build a .NET Application on the Oracle Database with Microsoft Visual Studio 2010
OalCneto cn =nwOalCneto(rd) / C rceoncin on e rceoncinoab; / # cn.pn) onOe(; OalCmadcd=nwOalCmad) rceomn m e rceomn(; cdCneto =cn; m.oncin on cdCmadet="eetdprmn_d dprmn_ae lcto_dfo dprmns18; m.omnTx slc eateti, eatetnm, oaini rm eatet.6" cdCmadye=CmadyeTx; m.omnTp omnTp.et OalDtRae d =cdEeueedr) rceaaedr r m.xctRae(; wie(rRa() hl d.ed) { lsBx.tm.d(Te"+d[dprmn_ae]TSrn( + ito1IesAd"h r"eatetnm".otig) "dprmn i i "+d[lcto_d]TSrn() eatet s n r"oaini".otig); } d.ips(; rDsoe) cdDsoe) m.ips(; cn.ips(; onDsoe) Run the application. The ListBox should be populated with all of the department names and locations from the departments table. The code downloads have error handling implemented.

John Paul Cook (johnpaulcook@email.com) is a database and .NET consultant based in Houston. He is the author of numerous articles on .NET, Oracle, and virtualization and has been developing relational database applications since 1986. His current interests include Visual Studio 2010 and Oracle Database 11g. He is an Oracle certified DBA and a Microsoft Most Valuable Professiona

E-mail this page

Printer View

Subscribe About Oracle Careers Contact Us Site Maps Legal Notices Terms of Use Your Privacy Rights

Oracle Mobile

www.oracle.com/technetwork/articles/dotnet/vs2010-oracle-dev-410461.html

13/13

You might also like