84
Object Innovations Custom Course 413C2 Robert J. Oberg Srini Manickam Student Guide Revision 2.0 ADO.NET Using Oracle and C#

ADO.NET Using Oracle and C# - ITCourseware Using Oracle and C# Rev. 2.0 Student Guide Information in this document is subject to change without notice. ... Acme Computer Case Study

  • Upload
    vumien

  • View
    215

  • Download
    2

Embed Size (px)

Citation preview

Page 1: ADO.NET Using Oracle and C# - ITCourseware Using Oracle and C# Rev. 2.0 Student Guide Information in this document is subject to change without notice. ... Acme Computer Case Study

Object Innovations Custom Course 413C2

Robert J. Oberg Srini Manickam

Student Guide Revision 2.0

ADO.NET Using Oracle and C#

Page 2: ADO.NET Using Oracle and C# - ITCourseware Using Oracle and C# Rev. 2.0 Student Guide Information in this document is subject to change without notice. ... Acme Computer Case Study

Rev. 2.0 Copyright ©2006 Object Innovations Enterprises, LLC ii All Rights Reserved

ADO.NET Using Oracle and C# Rev. 2.0 Student Guide Information in this document is subject to change without notice. Companies, names and data used in examples herein are fictitious unless otherwise noted. No part of this document may be reproduced or transmitted in any form or by any means, electronic or mechanical, for any purpose, without the express written permission of Object Innovations. Product and company names mentioned herein are the trademarks or registered trademarks of their respective owners. Copyright ©2006 Object Innovations Enterprises, LLC. All rights reserved. Object Innovations 877-558-7246 www.objectinnovations.com Printed in the United States of America on recycled paper.

Page 3: ADO.NET Using Oracle and C# - ITCourseware Using Oracle and C# Rev. 2.0 Student Guide Information in this document is subject to change without notice. ... Acme Computer Case Study

Rev. 2.0 Copyright ©2006 Object Innovations Enterprises, LLC iii All Rights Reserved

Table of Contents (Overview) Chapter 1 Database Application Basics Chapter 2 ADO.NET Fundamentals Chapter 3 ADO.NET Commands Chapter 4 DataSets and Disconnected Access Chapter 5 XML and ADO.NET Chapter 6 Data Binding Chapter 7 Creating and Using a Data Access Layer Appendix A Acme Computer Case Study Appendix B Learning Resources

Page 4: ADO.NET Using Oracle and C# - ITCourseware Using Oracle and C# Rev. 2.0 Student Guide Information in this document is subject to change without notice. ... Acme Computer Case Study

Rev. 2.0 Copyright ©2006 Object Innovations Enterprises, LLC iv All Rights Reserved

Page 5: ADO.NET Using Oracle and C# - ITCourseware Using Oracle and C# Rev. 2.0 Student Guide Information in this document is subject to change without notice. ... Acme Computer Case Study

Rev. 2.0 Copyright ©2006 Object Innovations Enterprises, LLC v All Rights Reserved

Table of Contents (Detailed)

Chapter 1 Database Application Basics .................................................................... 1 Data Modeling ................................................................................................................ 3 Data Modeling – Key Concepts...................................................................................... 4 Conceptual Model........................................................................................................... 6 Logical Model................................................................................................................. 7 Physical Data Model ....................................................................................................... 8 Performance Considerations ........................................................................................... 9 Performance Considerations ......................................................................................... 14 Acme Computer Case Study......................................................................................... 15 ORACLE_SID Environment Variable ......................................................................... 16 Buy Computer............................................................................................................... 17 Buy Computer – Web Version...................................................................................... 18 Model ............................................................................................................................ 19 Component.................................................................................................................... 20 Part ................................................................................................................................ 21 ComponentConfiguration ............................................................................................. 22 PartConfiguration.......................................................................................................... 23 System........................................................................................................................... 24 Tracking the System ID ................................................................................................ 25 SystemDetails ............................................................................................................... 26 StatusCode .................................................................................................................... 27 Relationships................................................................................................................. 28 Stored Procedure........................................................................................................... 29 Lab 1 ............................................................................................................................. 30 Summary ....................................................................................................................... 31

Chapter 2 ADO.NET Fundamentals ....................................................................... 35 Microsoft Data Access Technologies ........................................................................... 37 ODBC ........................................................................................................................... 38 OLE DB ........................................................................................................................ 39 ActiveX Data Objects (ADO)....................................................................................... 40 ADO Is Connection Oriented ....................................................................................... 41 ADO.NET ..................................................................................................................... 42 ADO.NET Architecture ................................................................................................ 43 ADO.NET Block Diagram............................................................................................ 45 .NET Data Providers..................................................................................................... 46 Namespaces for .NET Data Providers .......................................................................... 47 Oracle Data Provider for .NET ..................................................................................... 48 Basic Connection Programming ................................................................................... 49 Using Interfaces ............................................................................................................ 50 IDbConnection Properties............................................................................................. 51

Page 6: ADO.NET Using Oracle and C# - ITCourseware Using Oracle and C# Rev. 2.0 Student Guide Information in this document is subject to change without notice. ... Acme Computer Case Study

Rev. 2.0 Copyright ©2006 Object Innovations Enterprises, LLC vi All Rights Reserved

Connection String ......................................................................................................... 52 ODP.NET Connection String........................................................................................ 53 OLE DB Connection String .......................................................................................... 54 OLE DB Connection Example...................................................................................... 55 IDbConnection Methods............................................................................................... 56 Connection Life Cycle .................................................................................................. 57 ODPConnect (Step 2) ................................................................................................... 58 Connection Pooling....................................................................................................... 59 Pool Settings for Oracle ................................................................................................ 60 Connection Demo Program........................................................................................... 61 Connection Events ........................................................................................................ 62 Connection Event Demo............................................................................................... 63 ADO.NET Error Handling............................................................................................ 64 DataReader.................................................................................................................... 65 Using a DataReader ...................................................................................................... 66 IDataRecord .................................................................................................................. 67 Type-Safe Accessors..................................................................................................... 68 Finding the .NET Type ................................................................................................. 70 GetOrdinal().................................................................................................................. 71 Null Data....................................................................................................................... 72 Testing for Null............................................................................................................. 73 Using List Boxes........................................................................................................... 74 ListBox Example .......................................................................................................... 75 Lab 2A .......................................................................................................................... 77 ADO.NET with ASP.NET............................................................................................ 78 Web Client Isolation ..................................................................................................... 79 Web Client Database Code ........................................................................................... 80 Use of Session State...................................................................................................... 82 Generic Collections and Data Binding ......................................................................... 83 Lab 2B........................................................................................................................... 84 Lab 2C........................................................................................................................... 85 Summary ....................................................................................................................... 86

Chapter 3 ADO.NET Commands.......................................................................... 107 Command Objects....................................................................................................... 109 Creating Commands.................................................................................................... 110 Executing Commands ................................................................................................. 111 Sample Program.......................................................................................................... 112 Dynamic Queries ........................................................................................................ 114 Parameterized Queries ................................................................................................ 115 OracleDbType Enumeration Type.............................................................................. 116 Parameterized Query Example ................................................................................... 117 Command Types ......................................................................................................... 118 Stored Procedures ....................................................................................................... 119 Stored Procedure Example.......................................................................................... 120 Testing the Stored Procedure...................................................................................... 121

Page 7: ADO.NET Using Oracle and C# - ITCourseware Using Oracle and C# Rev. 2.0 Student Guide Information in this document is subject to change without notice. ... Acme Computer Case Study

Rev. 2.0 Copyright ©2006 Object Innovations Enterprises, LLC vii All Rights Reserved

Stored Procedures in ADO.NET................................................................................. 122 Using an Oracle REF CURSOR ................................................................................. 124 Example of REF CURSOR......................................................................................... 125 Client Program Using REF CURSOR ........................................................................ 126 Lab 3A ........................................................................................................................ 129 Lab 3B......................................................................................................................... 130 Summary ..................................................................................................................... 131

Chapter 4 Data Sets and Disconnected Access ..................................................... 145 DataSet........................................................................................................................ 147 DataSet Architecture................................................................................................... 148 Why DataSet? ............................................................................................................. 149 DataSet Components................................................................................................... 150 DataAdapter ................................................................................................................ 151 DataSet Example Program.......................................................................................... 152 Filling a DataSet ......................................................................................................... 153 Accessing a DataSet.................................................................................................... 154 Updating a DataSet Scenario ...................................................................................... 155 Example – ModelDataSet ........................................................................................... 156 Disconnected DataSet Example.................................................................................. 157 Adding a New Row..................................................................................................... 158 Searching and Updating a Row .................................................................................. 159 Deleting a Row ........................................................................................................... 160 Row Versions.............................................................................................................. 161 Row State .................................................................................................................... 162 BeginEdit and CancelEdit........................................................................................... 163 DataTable Events ........................................................................................................ 164 Updating a Database ................................................................................................... 165 Insert Command.......................................................................................................... 166 Update Command ....................................................................................................... 167 Delete Command ........................................................................................................ 168 Command Builders ..................................................................................................... 169 Filtering DataSets ....................................................................................................... 170 Example of Filtering ................................................................................................... 171 PartFinder Example Code ........................................................................................... 172 Lab 4 ........................................................................................................................... 174 Summary ..................................................................................................................... 175

Chapter 5 XML and ADO.NET............................................................................. 179 ADO.NET and XML .................................................................................................. 181 Rendering XML from a DataSet................................................................................. 182 XmlWriteMode ........................................................................................................... 183 Demo: Writing XML Data.......................................................................................... 184 Writing Data As Attributes ......................................................................................... 186 Reading XML into a DataSet...................................................................................... 188 Demo: Reading XML Data......................................................................................... 189

Page 8: ADO.NET Using Oracle and C# - ITCourseware Using Oracle and C# Rev. 2.0 Student Guide Information in this document is subject to change without notice. ... Acme Computer Case Study

Rev. 2.0 Copyright ©2006 Object Innovations Enterprises, LLC viii All Rights Reserved

DataSets and XML Schema........................................................................................ 191 Demo: Writing XML Schema..................................................................................... 192 ModelSchema.xsd....................................................................................................... 193 Reading XML Schema................................................................................................ 194 XmlReadMode............................................................................................................ 195 Demo: Reading XML Schema.................................................................................... 196 XML Data in DataTables............................................................................................ 198 Typed DataSets ........................................................................................................... 199 Table Adapter ............................................................................................................. 200 Demo: Creating a Typed DataSet Using Visual Studio.............................................. 201 Using the Typed Data Set ........................................................................................... 207 Synchronizing DataSets and XML ............................................................................. 208 Using XmlDataDocument........................................................................................... 209 XML Serialization ...................................................................................................... 211 XML Serialization Code Example.............................................................................. 212 Default Constructor..................................................................................................... 213 Lab 5 ........................................................................................................................... 214 Summary ..................................................................................................................... 215

Chapter 6 Data Binding.......................................................................................... 219 Data Binding Concept................................................................................................. 221 Simple Data Binding................................................................................................... 222 Binding to a List ......................................................................................................... 223 SimpleList Example.................................................................................................... 224 Complex Data Binding Example ................................................................................ 225 Binding to DataGrid.................................................................................................... 227 DataGrid in Visual Studio 2005.................................................................................. 228 Complex Data Binding ............................................................................................... 229 DataView .................................................................................................................... 230 Filtering and Sorting ................................................................................................... 231 DataView and Data Binding ....................................................................................... 232 DataView Example ..................................................................................................... 233 New Data Binding....................................................................................................... 235 BindingSource Architecture ....................................................................................... 236 Binding to a List ......................................................................................................... 237 Setting up the Bindings............................................................................................... 238 Category Class ............................................................................................................ 239 Code in the Form ........................................................................................................ 240 DataGridView Control................................................................................................ 242 DataGridView Sample Program ................................................................................. 243 DataGridView Sample Code....................................................................................... 244 DataGridView Binding ............................................................................................... 246 Data Binding in ASP.NET.......................................................................................... 247 Web Forms Data Binding ........................................................................................... 248 Lab 6A ........................................................................................................................ 249 Lab 6B......................................................................................................................... 250

Page 9: ADO.NET Using Oracle and C# - ITCourseware Using Oracle and C# Rev. 2.0 Student Guide Information in this document is subject to change without notice. ... Acme Computer Case Study

Rev. 2.0 Copyright ©2006 Object Innovations Enterprises, LLC ix All Rights Reserved

Summary ..................................................................................................................... 251

Chapter 7 Creating and Using a Data Access Layer ........................................... 261 One-Tier Systems........................................................................................................ 263 Disadvantages of One-Tier ......................................................................................... 264 PCs .............................................................................................................................. 265 PC LANs..................................................................................................................... 266 Database Servers......................................................................................................... 267 Client/Server Systems................................................................................................. 268 Fat Clients ................................................................................................................... 269 Scalability and Flexibility........................................................................................... 270 Three-Tier Systems..................................................................................................... 271 Application Servers..................................................................................................... 273 Benefits of Three-Tier Architecture ........................................................................... 274 Three-Tier Architecture using .NET........................................................................... 275 User Interface Components......................................................................................... 278 Designing User Process Components ......................................................................... 279 Data Access Components ........................................................................................... 280 Lab 7 ........................................................................................................................... 282 Summary ..................................................................................................................... 283

Appendix A Acme Computer Case Study................................................................ 295

Appendix B Learning Resources .............................................................................. 303

Page 10: ADO.NET Using Oracle and C# - ITCourseware Using Oracle and C# Rev. 2.0 Student Guide Information in this document is subject to change without notice. ... Acme Computer Case Study

Rev. 2.0 Copyright ©2006 Object Innovations Enterprises, LLC x All Rights Reserved

Page 11: ADO.NET Using Oracle and C# - ITCourseware Using Oracle and C# Rev. 2.0 Student Guide Information in this document is subject to change without notice. ... Acme Computer Case Study

OraAdoCs Chapter 1

Rev. 2.0 Copyright © 2006 Object Innovations Enterprises, LLC 1 All Rights Reserved

Chapter 1

Database Application Basics

Page 12: ADO.NET Using Oracle and C# - ITCourseware Using Oracle and C# Rev. 2.0 Student Guide Information in this document is subject to change without notice. ... Acme Computer Case Study

OraAdoCs Chapter 1

Rev. 2.0 Copyright © 2006 Object Innovations Enterprises, LLC 2 All Rights Reserved

Database Application Basics

Objectives

After completing this unit you will be able to:

• Explain what data modeling is.

• Understand how designing an application blends with data modeling.

• Decide how to design a database application for high performance.

• Outline the Acme Computer case study database and perform simple queries against it.

Page 13: ADO.NET Using Oracle and C# - ITCourseware Using Oracle and C# Rev. 2.0 Student Guide Information in this document is subject to change without notice. ... Acme Computer Case Study

OraAdoCs Chapter 1

Rev. 2.0 Copyright © 2006 Object Innovations Enterprises, LLC 3 All Rights Reserved

Data Modeling

• Analysis of Data objects and their relationships to other data objects.

− Data Modeling is an initial step towards Database Design.

• Why Data Modeling is important?

− Data Modeling is a representation of the software requirements, graphically, from the data perspective.

− Incorrect Data Model leads to incorrect applications.

− Example: SSN are unique.

− Violation: An employee table not having a unique index on SSN.

− Data Modeling is one of the early phases of Application Development; mistakes are highly visible and costly.

• What a Data Model is not?

− A Data Model does not capture the behavior of the data.

• Data modeling is a progression from abstract thoughts to concrete action.

− Conceptual Model

− Logical Model

− Physical Schema

Page 14: ADO.NET Using Oracle and C# - ITCourseware Using Oracle and C# Rev. 2.0 Student Guide Information in this document is subject to change without notice. ... Acme Computer Case Study

OraAdoCs Chapter 1

Rev. 2.0 Copyright © 2006 Object Innovations Enterprises, LLC 4 All Rights Reserved

Data Modeling – Key Concepts

• Entities

− Entities are subjects that the application needs to deal with.

(e.g.) Customers, and Orders

• Attributes

− Attributes are characteristics of the Entities.

(e.g.) Every Customer has a First Name, Last Name and Address.

• Relations

− Relationship between Entities.

Page 15: ADO.NET Using Oracle and C# - ITCourseware Using Oracle and C# Rev. 2.0 Student Guide Information in this document is subject to change without notice. ... Acme Computer Case Study

OraAdoCs Chapter 1

Rev. 2.0 Copyright © 2006 Object Innovations Enterprises, LLC 5 All Rights Reserved

Relationships

• In general, relationships cover the existence or non-existence of instance(s) of an entity with respect to that of another entity.

• One-To-Many Relationships

− For every instance of an entity there may exists one or more instances of another entity.

(e.g.) A Customer can place one or more Orders.

− An Order can have one or more Items.

− A Computer Component can have one or more Parts.

• Many-To-Many Relationships

− For every instance of an entity there may exists one or more instances of another entity. And vice-versa.

− One X relates to many Ys and one Y relates to many Xs.

(e.g.) An Order can have one or more Items. An Item can be in one or more Orders.

• Relationships can be diagrammed.

− A popular kind of diagram is an entity-relationship diagram.

− An example of a relationship diagram is provided later in the chapter, illustrating the Acme Computer database used as our case study.

Page 16: ADO.NET Using Oracle and C# - ITCourseware Using Oracle and C# Rev. 2.0 Student Guide Information in this document is subject to change without notice. ... Acme Computer Case Study

OraAdoCs Chapter 1

Rev. 2.0 Copyright © 2006 Object Innovations Enterprises, LLC 6 All Rights Reserved

Conceptual Model

• Conceptual Model

− Process of constructing a model of information used in an enterprise, independent of any physical considerations.

− First step in data modeling

− A model on data as business sees it, not as technology sees it.

− Includes high level, important Entities and their Relationships.

− Does not contain any Attributes or Key information.

Page 17: ADO.NET Using Oracle and C# - ITCourseware Using Oracle and C# Rev. 2.0 Student Guide Information in this document is subject to change without notice. ... Acme Computer Case Study

OraAdoCs Chapter 1

Rev. 2.0 Copyright © 2006 Object Innovations Enterprises, LLC 7 All Rights Reserved

Logical Model

• Logical Model

− Process of detailing a conceptual model on specific data model but independent of a particular DBMS product and other physical considerations.

− Second step in data modeling

− A model on data as technology sees it, but vendor independent. (Logical model does not care whether it is Oracle or SQL Server).

− All Entities required for the system to function are present.

− Primary and Foreign Key information are present.

− At least of First Normal Form.

− Separate entities to depict many-to-many relationships

(e.g.) OrderItems that tells which Order contain what Items.

− Dependent of type of the Data Model but independent of physical constraints.

Page 18: ADO.NET Using Oracle and C# - ITCourseware Using Oracle and C# Rev. 2.0 Student Guide Information in this document is subject to change without notice. ... Acme Computer Case Study

OraAdoCs Chapter 1

Rev. 2.0 Copyright © 2006 Object Innovations Enterprises, LLC 8 All Rights Reserved

Physical Data Model

• Physical data model

− Process of producing a description of the implementation of the logical model on secondary storage device.

− Third step in Data Modeling.

− Describes the organizations of the data files, indexes, relationships, security and integrity constraints.

− Specific to a database product.

− Normalized to a level that meets the requirements.

− Results in an actual Database that a program can interface with.

Page 19: ADO.NET Using Oracle and C# - ITCourseware Using Oracle and C# Rev. 2.0 Student Guide Information in this document is subject to change without notice. ... Acme Computer Case Study

OraAdoCs Chapter 1

Rev. 2.0 Copyright © 2006 Object Innovations Enterprises, LLC 9 All Rights Reserved

Performance Considerations

• The Data Model strongly effects application performance.

• Mistakes made in the data model that affect performance are often costly (more time and effort) to correct.

− Example. Highly de-normalized data model will affect query time.

• Gather performance statistics often and tune the application periodically.

• Major Database performance criteria

− Query timing

− Update / Insert timing

− Scalability

• For effective Query timing

− Index helps to improve query timing

− Index the frequently accessed columns in a table.

− Consider bit map index for the fields can only two states

− Do not index column that have very less common values

Page 20: ADO.NET Using Oracle and C# - ITCourseware Using Oracle and C# Rev. 2.0 Student Guide Information in this document is subject to change without notice. ... Acme Computer Case Study

OraAdoCs Chapter 1

Rev. 2.0 Copyright © 2006 Object Innovations Enterprises, LLC 10 All Rights Reserved

Performance Considerations

• For efficient Update / Insert timing

− Indices affect the update / insert timing in a negative way.

− Disable indices during mass update or insert.

− Consider using other utilities like SqlLoader to load high volume data.

− Highly normalized data model will cause more time in update/insert because of lookup table references.

− Where possible, use stage tables to bulk load the data and later update /insert the actual tables using stored procedures.

Page 21: ADO.NET Using Oracle and C# - ITCourseware Using Oracle and C# Rev. 2.0 Student Guide Information in this document is subject to change without notice. ... Acme Computer Case Study

OraAdoCs Chapter 1

Rev. 2.0 Copyright © 2006 Object Innovations Enterprises, LLC 11 All Rights Reserved

Performance Considerations

• Scalability

− The System’s ability to process more operations or transactions in a given period, in particular by adding more or more powerful processors.

− Use high performance bulk loading methods when loading data from external systems.

− Normalize reasonably to achieve balance between storage and performance.

• Some signs of an application not tuned for high-performance

− Many SQL Statements require more than 5 tables to join.

This indicates some denormalization is required in the data model.

− Frequent uses of Max or Min in nested Select statements

This indicates the need for a data model change to distinguish the latest or greatest data by flags or by storing them redundantly.

− Many tables having only single column indexes.

Not having multiple column indexes can cause long index scans and merges.

− Extremely large tables.

Page 22: ADO.NET Using Oracle and C# - ITCourseware Using Oracle and C# Rev. 2.0 Student Guide Information in this document is subject to change without notice. ... Acme Computer Case Study

OraAdoCs Chapter 1

Rev. 2.0 Copyright © 2006 Object Innovations Enterprises, LLC 12 All Rights Reserved

Performance Considerations

• When to Normalize When to De-normalize?

− Normalizing tend to help when query activity is low and update activity is high.

− Denormalization helps when update activity is intense and low query activity.

Page 23: ADO.NET Using Oracle and C# - ITCourseware Using Oracle and C# Rev. 2.0 Student Guide Information in this document is subject to change without notice. ... Acme Computer Case Study

OraAdoCs Chapter 1

Rev. 2.0 Copyright © 2006 Object Innovations Enterprises, LLC 13 All Rights Reserved

Performance Considerations

• Oracle specific performance considerations:

− Use hints to hint Oracle database for using Rule-Based or Cost-Based optimization.

− Form the query to avoid “in” clauses that do sort inherently, instead use “WHERE EXISTS”

• Oracle specific tools for performance monitoring:

− SQL_TRACE

Facilitates writing a trace file containing performance statistics for the SQL Statements being executed.

− TKPROF

Utility that helps to interpret the SQL_TRACE file output.

− EXPLAIN PLAN

A statement that can be included in a single SQL statement to explain the execution plan that Oracle will be using to fulfill the request.

− ANALYZE TABLE

Calculates important performance statistics of a table such as number of rows, and number of distinct values per column.

− UTLBSTAT.sql and UTLESTAT.sql

Scripts that help to take snapshot of program activity such as physical reads.

Page 24: ADO.NET Using Oracle and C# - ITCourseware Using Oracle and C# Rev. 2.0 Student Guide Information in this document is subject to change without notice. ... Acme Computer Case Study

OraAdoCs Chapter 1

Rev. 2.0 Copyright © 2006 Object Innovations Enterprises, LLC 14 All Rights Reserved

Performance Considerations

• Performance considerations in .NET Middle Tier

− Use Data Readers for looping through voluminous data.

− Use Data Sets (in-memory databases) for less voluminous and frequently referred lookup data.

− Use Database Connection Pooling. Connectivity is one of the costly resources.

• Performance considerations in .NET User Interfaces

− Perform validations at the client level wherever possible to reduce network traffic.

− Consider storing less size re-usable data in application level state variables such as Session, where possible.

Page 25: ADO.NET Using Oracle and C# - ITCourseware Using Oracle and C# Rev. 2.0 Student Guide Information in this document is subject to change without notice. ... Acme Computer Case Study

OraAdoCs Chapter 1

Rev. 2.0 Copyright © 2006 Object Innovations Enterprises, LLC 15 All Rights Reserved

Acme Computer Case Study

• For examples, this course uses a database for the Acme Computer Company.

• Acme Computer manufactures and sells computers, taking orders both over the Web and by phone.

− The Order Entry System supports ordering custom-built systems.

− A Windows Forms front-end provides a rich client user interface. This system is used internally by employees of Acme, who take orders over the phone.

− A Web interface is provided for retail customers, enabling them to configure and buy their system over the Internet.

• The heart of the system is a relational database, whose schema is described below.

− The Order Entry System is responsible for gathering information from the customer and updating the database tables to reflect fulfilling the order.

− More details are provided in Appendix A.

Page 26: ADO.NET Using Oracle and C# - ITCourseware Using Oracle and C# Rev. 2.0 Student Guide Information in this document is subject to change without notice. ... Acme Computer Case Study

OraAdoCs Chapter 1

Rev. 2.0 Copyright © 2006 Object Innovations Enterprises, LLC 16 All Rights Reserved

ORACLE_SID Environment Variable

• To run the example programs in the course using the Oracle Data Provider for .NET you need to set the ORACLE_SID environment variable.

− For Oracle 10g Express Edition this environment variable should be set to xe.

• You can create and set this environment variable from the System applet in the Control Panel.

Page 27: ADO.NET Using Oracle and C# - ITCourseware Using Oracle and C# Rev. 2.0 Student Guide Information in this document is subject to change without notice. ... Acme Computer Case Study

OraAdoCs Chapter 1

Rev. 2.0 Copyright © 2006 Object Innovations Enterprises, LLC 17 All Rights Reserved

Buy Computer

• The first case study using the database provides a Windows Form front-end for configuring and buying a custom-built computer.

− See BuyComputer\Step2 in the CaseStudy directory.

− This program uses a connected data-access model and is developed over the next several chapters.

− Additional programs will be developed later using disconnected datasets.

− We will also provide many examples of ADO.NET Web applications using ASP.NET.

Page 28: ADO.NET Using Oracle and C# - ITCourseware Using Oracle and C# Rev. 2.0 Student Guide Information in this document is subject to change without notice. ... Acme Computer Case Study

OraAdoCs Chapter 1

Rev. 2.0 Copyright © 2006 Object Innovations Enterprises, LLC 18 All Rights Reserved

Buy Computer – Web Version

• We also provide an ASP.NET Web version of this case study.

− See CaseStudy\BuyComputerWeb\Step2.

• There are parallel case study lab tracks building the Windows and the Web versions of the program.

Page 29: ADO.NET Using Oracle and C# - ITCourseware Using Oracle and C# Rev. 2.0 Student Guide Information in this document is subject to change without notice. ... Acme Computer Case Study

OraAdoCs Chapter 1

Rev. 2.0 Copyright © 2006 Object Innovations Enterprises, LLC 19 All Rights Reserved

Model

• The Model table shows the models of computer systems available and their base price.

− The total system price will be calculated by adding the base price (which includes the chassis, mother board, power supply, and so on) to the components that are configured into the system.

− ModelId is the primary key.

Page 30: ADO.NET Using Oracle and C# - ITCourseware Using Oracle and C# Rev. 2.0 Student Guide Information in this document is subject to change without notice. ... Acme Computer Case Study

OraAdoCs Chapter 1

Rev. 2.0 Copyright © 2006 Object Innovations Enterprises, LLC 20 All Rights Reserved

Component

• The Component table shows the various components that can be configured into a system.

− Where applicable, a unit of measurement is shown.

− CompId is the primary key.

Page 31: ADO.NET Using Oracle and C# - ITCourseware Using Oracle and C# Rev. 2.0 Student Guide Information in this document is subject to change without notice. ... Acme Computer Case Study

OraAdoCs Chapter 1

Rev. 2.0 Copyright © 2006 Object Innovations Enterprises, LLC 21 All Rights Reserved

Part

• The Part table gives the details of all the various component parts that are available.

− The type of component is specified by CompId.

− The optional Description can be used to further specify certain types of components. For example, both CRT and Flatscreen monitors are provided.

− Although not used in the basic order entry system, fields are provided to support an inventory management system, providing a restock quantity and date.

− Note that parts can either be part of a complete system or sold separately.

− PartId is the primary key.

... and additional rows

Page 32: ADO.NET Using Oracle and C# - ITCourseware Using Oracle and C# Rev. 2.0 Student Guide Information in this document is subject to change without notice. ... Acme Computer Case Study

OraAdoCs Chapter 1

Rev. 2.0 Copyright © 2006 Object Innovations Enterprises, LLC 22 All Rights Reserved

ComponentConfiguration

• The ComponentConfiguration table shows which components are available for each model.

− We show the ComponentConfiguration table for ModelId = 1 (Economy).

Page 33: ADO.NET Using Oracle and C# - ITCourseware Using Oracle and C# Rev. 2.0 Student Guide Information in this document is subject to change without notice. ... Acme Computer Case Study

OraAdoCs Chapter 1

Rev. 2.0 Copyright © 2006 Object Innovations Enterprises, LLC 23 All Rights Reserved

PartConfiguration

• The PartConfiguration table shows which parts are available for each model.

− Besides specifying valid configurations, this table is also important in optimizing the performance and scalability of the Order Entry System.

− In the ordering process a customer first selects a model. Then a dataset can be constructed containing the data relevant to that particular model without having to download a large amount of data that is not relevant.

− ModelId and PartId are a primary key.

− We show the first few rows of the PartConfiguration table.

Page 34: ADO.NET Using Oracle and C# - ITCourseware Using Oracle and C# Rev. 2.0 Student Guide Information in this document is subject to change without notice. ... Acme Computer Case Study

OraAdoCs Chapter 1

Rev. 2.0 Copyright © 2006 Object Innovations Enterprises, LLC 24 All Rights Reserved

System

• The System table shows information about complete systems that have been ordered.

− Systems are built to order, and so the System table only gets populated as systems are ordered.

− The base model is shown in the System table, and the various components comprising the system are shown in the SystemDetails table.

− The price is calculated from the price of the base model and the components. Note that part prices may change, but once a price is assigned to the system, that price sticks (unless later discounted on account of a return).

− A status code shows the system status, Ordered, Built, and so on. If a system is returned, it becomes available at a discount as a “refurbished” system.

− SystemId is the primary key.

− The System table becomes populated as systems are ordered.

Page 35: ADO.NET Using Oracle and C# - ITCourseware Using Oracle and C# Rev. 2.0 Student Guide Information in this document is subject to change without notice. ... Acme Computer Case Study

OraAdoCs Chapter 1

Rev. 2.0 Copyright © 2006 Object Innovations Enterprises, LLC 25 All Rights Reserved

Tracking the System ID

• Oracle allows you to declare an auto-incrementing counter object, known as a sequence.

− The starting value is the seed, and the amount by which the value increases or decreases with each row is called the increment.

− When you insert a new row into the system table, you use the "next value" in the sequence:

insert into system values (SystemIDSequence.nextval, :modelid, :price, :status);

• Several of the primary keys in the tables of the AcmeComputer database will need to be generated using sequences.

− For example, the SystemId column tracks the "ID number" for newly ordered systems. Each ID number needs to be different.

Page 36: ADO.NET Using Oracle and C# - ITCourseware Using Oracle and C# Rev. 2.0 Student Guide Information in this document is subject to change without notice. ... Acme Computer Case Study

OraAdoCs Chapter 1

Rev. 2.0 Copyright © 2006 Object Innovations Enterprises, LLC 26 All Rights Reserved

SystemDetails

• The SystemDetails table shows the parts that make up a complete system.

− Certain components, such as memory modules and disks, can be in a multiple quantity. (In the first version of the case study, the quantity is always 1.)

− SystemId and PartId are the primary key.

− The SystemDetails table becomes populated as systems are ordered.

Page 37: ADO.NET Using Oracle and C# - ITCourseware Using Oracle and C# Rev. 2.0 Student Guide Information in this document is subject to change without notice. ... Acme Computer Case Study

OraAdoCs Chapter 1

Rev. 2.0 Copyright © 2006 Object Innovations Enterprises, LLC 27 All Rights Reserved

StatusCode

• The StatusCode table provides a description for each status code.

− Status is the primary key.

Page 38: ADO.NET Using Oracle and C# - ITCourseware Using Oracle and C# Rev. 2.0 Student Guide Information in this document is subject to change without notice. ... Acme Computer Case Study

OraAdoCs Chapter 1

Rev. 2.0 Copyright © 2006 Object Innovations Enterprises, LLC 28 All Rights Reserved

Relationships

• The tables discussed have the following relationships shown in the diagram below.

− This is an example of an entity-relationship diagram discussed earlier in the chapter.

Page 39: ADO.NET Using Oracle and C# - ITCourseware Using Oracle and C# Rev. 2.0 Student Guide Information in this document is subject to change without notice. ... Acme Computer Case Study

OraAdoCs Chapter 1

Rev. 2.0 Copyright © 2006 Object Innovations Enterprises, LLC 29 All Rights Reserved

Stored Procedure

• A stored procedure spInsertSystem is provided for inserting a new system into the System table.

− This procedure returns as an output parameter the system ID that is generated as an identity column.

CREATE OR REPLACE PROCEDURE spInsertSystem (ModelId integer, Price number, Status integer) RETURN integer AS BEGIN insert System(SystemID, ModelId, Price, Status) values(systemIDsequence.nextval, :ModelId, :Price, :Status) return systemidsequence.currval; END /

Page 40: ADO.NET Using Oracle and C# - ITCourseware Using Oracle and C# Rev. 2.0 Student Guide Information in this document is subject to change without notice. ... Acme Computer Case Study

OraAdoCs Chapter 1

Rev. 2.0 Copyright © 2006 Object Innovations Enterprises, LLC 30 All Rights Reserved

Lab 1

Querying the AcmeComputer Database

In this lab, you will set up the AcmeComputer database on your system. You will also perform a number of queries against the database. Doing these queries will both help to familiarize you with the database and serve as a review of SQL.

Detailed instructions are contained in the Lab 1 write-up at the end of the chapter.

Suggested time: 60 minutes

Page 41: ADO.NET Using Oracle and C# - ITCourseware Using Oracle and C# Rev. 2.0 Student Guide Information in this document is subject to change without notice. ... Acme Computer Case Study

OraAdoCs Chapter 1

Rev. 2.0 Copyright © 2006 Object Innovations Enterprises, LLC 31 All Rights Reserved

Summary

• Data Modeling is the graphical representation of the User Requirements from the perspective of data.

• There are three phases of Data Modeling:

− Conceptual Data Modeling

− Logical Data Modeling

− Physical Data Modeling

• Data Modeling is one of the key steps in application development.

• Data Modeling has a high impact on the application’s performance.

Page 42: ADO.NET Using Oracle and C# - ITCourseware Using Oracle and C# Rev. 2.0 Student Guide Information in this document is subject to change without notice. ... Acme Computer Case Study

OraAdoCs Chapter 1

Rev. 2.0 Copyright © 2006 Object Innovations Enterprises, LLC 32 All Rights Reserved

Lab 1

Querying the AcmeComputer Database

Introduction In this lab, you will set up the AcmeComputer database on your system. You will also perform a number of queries against the database. Doing these queries will both help to familiarize you with the database and serve as a review of SQL. Suggested Time: 60 minutes Root Directory: OIC\OraAdoCs Directories: Labs\Lab1\Queries (save your queries here) Chap01\Queries (answers) Databases (database files) Database: AcmeComputer Part 1. Set up the Database Perform the following steps to setup the database using Oracle 10g Express Edition (XE). If the database has already been se tup on your system, you may proceed to Part 2. 1. Install the Oracle XE database on your system, if needed. Make a note of what the

SYSTEM password is. (If the Oracle database has already been installed, simply find out what the SYSTEM password is and go directly to Step 2.

2. Start SQL*Plus by running All Programs | Oracle Database 10g Express Edition | Run SQL Command Line.

3. Connect to your Oracle database, using the username of SYSTEM and the password that you identified in Step 1. Issue the following command: connect system. Enter the password in response to the prompt.

4. Execute the script called AcmeSchema.sql by typing the following command:

start c:\oic\databases\acmeschema.sql This will create a user called acme in the database, with a password of computer. 5. Execute the script AcmeData.sql by typing the following:

start c:\oic\databases\acmedata.sql

Page 43: ADO.NET Using Oracle and C# - ITCourseware Using Oracle and C# Rev. 2.0 Student Guide Information in this document is subject to change without notice. ... Acme Computer Case Study

OraAdoCs Chapter 1

Rev. 2.0 Copyright © 2006 Object Innovations Enterprises, LLC 33 All Rights Reserved

Part 2. Browse the Database For this part browse the database using the Web browser based admin tool, which you can run by All Programs | Oracle Database 10g Express Edition | Go To Database Home Page. 1. Login as user acme and password computer.

2. Click the Object Browser icon. You will initially see a list of tables.

3. Select the MODEL table and view the schema that is displayed.

4. Click on Data and view the data in the table.

5. On the left side select Procedures and examine the two stored procedures in the database.

6. On the left side select Packages and examine the three packages in the database. Look at both the Specification and the Body.

Part 3. Perform Queries Create and execute the following queries using SQL*Plus or the browser admin tool. For the latter, click on the SQL icon after you have logged in. 1. Connect (log in) to the acme account.

2. Show all the information about models from the Model table. (SelectModel.sql)

3. Show all the information about components from the Component table. (AllComponents.sql).

4. Show the component ID and description of each component available for the Economy model. Hint: you will need to perform an inner join with the ComponentConfiguration table. (EconomyComponents.sql)

Page 44: ADO.NET Using Oracle and C# - ITCourseware Using Oracle and C# Rev. 2.0 Student Guide Information in this document is subject to change without notice. ... Acme Computer Case Study

OraAdoCs Chapter 1

Rev. 2.0 Copyright © 2006 Object Innovations Enterprises, LLC 34 All Rights Reserved

5. Show the part ID, price and part size of all hard drives that are available for the Deluxe model. (DeluxeHarddrives.sql)

6. The next exercises involve buying a deluxe system that is configured to have the fastest CPU, the most memory, the largest hard drive, and the fastest CDROM. As a first step, write a query that will determine the prices and quantity on hand of these components. (PricesQtyDeluxe.sql) Note that the supplied file provides several SQL statements separated by semicolons. You can run multiple commands this way using SQL*PLUS. You can Paste using the system menu of Run SQL Command Line.

7. Next, write a query that will invoke the stored procedure spinsertsystem to insert the deluxe system you are buying into the System. You will need to know the price of this system, which you can calculate from the results of the previous query. Don’t forget to include the base price of a deluxe system. To verify that the new system has indeed been inserted, add SQL code to your query to show all systems before and after the stored procedure has been executed. Make a note of the SystemId of the new system that has been added. (InsertDeluxe.sql)

8. Examine the stored procedure spUpdatesystemDetailsAndPart in the Acme Computer database. This stored procedure allows you to insert a system detail record. For the SystemId, it uses the current value of the systemidsequence sequence. This stored procedure also decrements QtyOnHand in the Part table for the part being added to the SystemDetails table. Write a query that will invoke this stored procedure for each component of the system described in Step 6. (InsertDeluxeDetails.sql)

9. Run the query from Step 6 again and verify that the quantity of each part has indeed been decremented.

10. Create a query to show the part ID, price and QtyOnHand for each part in a system given the SystemId. Make sure the SystemId is the same as created in Step 7. Run this query against the deluxe system that you have just added to the database through your purchase. (ShowDeluxeParts.sql)

Page 45: ADO.NET Using Oracle and C# - ITCourseware Using Oracle and C# Rev. 2.0 Student Guide Information in this document is subject to change without notice. ... Acme Computer Case Study

OraAdoCs Chapter 5

Rev. 2.0 Copyright © 2006 Object Innovations Enterprises, LLC 179 All Rights Reserved

Chapter 5

XML and ADO.NET

Page 46: ADO.NET Using Oracle and C# - ITCourseware Using Oracle and C# Rev. 2.0 Student Guide Information in this document is subject to change without notice. ... Acme Computer Case Study

OraAdoCs Chapter 5

Rev. 2.0 Copyright © 2006 Object Innovations Enterprises, LLC 180 All Rights Reserved

XML and ADO.NET

Objectives

After completing this unit you will be able to:

• Discuss the strong coupling between ADO.NET and XML.

• Render a DataSet into XML.

• Control the format of XML rendered from a DataSet.

• Read XML into a DataSet.

• Exchange schema information between DataSets and XML.

• Use Visual Studio 2005 database wizards with Oracle databases.

• Use Visual Studio 2005 to create typed DataSets.

• Show how to synchronize information between an XML document and a DataSet.

• Show how to serialize data to a flat file using XML.

Page 47: ADO.NET Using Oracle and C# - ITCourseware Using Oracle and C# Rev. 2.0 Student Guide Information in this document is subject to change without notice. ... Acme Computer Case Study

OraAdoCs Chapter 5

Rev. 2.0 Copyright © 2006 Object Innovations Enterprises, LLC 181 All Rights Reserved

ADO.NET and XML

• Unlike many other data access technologies, ADO.NET was architected after XML had become a core software technology.

• As a result, XML is very integral to ADO.NET, not something bolted on afterwards.

• There are many ways in which ADO.NET is closely coupled to XML.

− You can easily render XML from a DataSet, and you can control the format of the XML, such as whether something will be an element or an attribute.

− You can read XML into a DataSet.

− You can exchange schema information between XML and DataSets.

• The key fact is that a DataSet is equally comfortable with interfacing to either XML or relational data.

• You can synchronize a DataSet with an XML document, so that updates to either one will automatically propagate to the other.

Page 48: ADO.NET Using Oracle and C# - ITCourseware Using Oracle and C# Rev. 2.0 Student Guide Information in this document is subject to change without notice. ... Acme Computer Case Study

OraAdoCs Chapter 5

Rev. 2.0 Copyright © 2006 Object Innovations Enterprises, LLC 182 All Rights Reserved

Rendering XML from a DataSet

• It is very easy to render XML from a DataSet by using one of the overloaded WriteXml() methods.

− They all write out the current data in the DataSet.

• The main methods are: public void WriteXml(string fileName); // Writes to a file public void WriteXml(Stream stream); // Writes to a stream public void WriteXml(TextWriter writer); // Writes using a TextWriter public void WriteXml(XmlWriter writer); // Writes using an XmlWriter

Page 49: ADO.NET Using Oracle and C# - ITCourseware Using Oracle and C# Rev. 2.0 Student Guide Information in this document is subject to change without notice. ... Acme Computer Case Study

OraAdoCs Chapter 5

Rev. 2.0 Copyright © 2006 Object Innovations Enterprises, LLC 183 All Rights Reserved

XmlWriteMode

• An optional second parameter in WriteXml() specifies additional data that can be written out, such as schema information and a DiffGram showing original data as well as the current data.

public void WriteXml(string fileName, XmlWriteMode mode);

• The possible modes are specified in the XmlWriteMode enumeration.

DiffGram Write the data as a DiffGram, showing the original as well as the current data.

IgnoreSchema Write only the current data without any schema information.

WriteSchema Write both the data and the XSD schema, which is shown inline.

• We will discuss schema a little later in this chapter.

Page 50: ADO.NET Using Oracle and C# - ITCourseware Using Oracle and C# Rev. 2.0 Student Guide Information in this document is subject to change without notice. ... Acme Computer Case Study

OraAdoCs Chapter 5

Rev. 2.0 Copyright © 2006 Object Innovations Enterprises, LLC 184 All Rights Reserved

Demo: Writing XML Data

• You can perform this demonstration starting with the ShowModelXml project in the Demos directory.

1. Build and run the program.

2. Click the Read Database button. You will then see the data from the Model table displayed in a listbox.

3. Click Write XML. The DataSet will then be rendered into XML, in the file ModelData.xml.

<?xml version="1.0" standalone="yes"?> <NewDataSet> <Model> <MODELID>1</MODELID> <MODELNAME>Economy</MODELNAME> <BASEPRICE>300</BASEPRICE> </Model> <Model> <MODELID>2</MODELID> <MODELNAME>Standard</MODELNAME> <BASEPRICE>350</BASEPRICE> </Model> ... </NewDataSet>

Page 51: ADO.NET Using Oracle and C# - ITCourseware Using Oracle and C# Rev. 2.0 Student Guide Information in this document is subject to change without notice. ... Acme Computer Case Study

OraAdoCs Chapter 5

Rev. 2.0 Copyright © 2006 Object Innovations Enterprises, LLC 185 All Rights Reserved

Writing XML Data – Code

• The DataSet is created when the form is loaded, using standard code like we have seen before.

private DataSet ds; private OracleDataAdapter da; private void Form1_Load(object sender, System.EventArgs e) { OracleConnection conn = new OracleConnection(); conn.ConnectionString = "User ID=acme;password=computer"; OracleCommand cmd = conn.CreateCommand(); cmd.CommandText = "select * from Model"; da = new OracleDataAdapter(cmd); da.MissingSchemaAction = MissingSchemaAction.AddWithKey; OracleCommandBuilder builder = new OracleCommandBuilder(da); ds = new DataSet(); }

− Note the AddWithKey for MissingSchemaAction. This will be important for us later in capturing the primary key schema information.

• The DataSet is filled and shown. da.Fill(ds, "Model"); ShowDataSet();

• The XML is written out. ds.WriteXml("..\\..\\ModelData.xml");

Page 52: ADO.NET Using Oracle and C# - ITCourseware Using Oracle and C# Rev. 2.0 Student Guide Information in this document is subject to change without notice. ... Acme Computer Case Study

OraAdoCs Chapter 5

Rev. 2.0 Copyright © 2006 Object Innovations Enterprises, LLC 186 All Rights Reserved

Writing Data As Attributes

• By default, all data will be written as XML elements.

• You can specify that some data will be written as attributes.

• As an example, build and run the ModelAttribute program.

• Check Use Attribute and click Write XML. The XML file ModelAttribute.xml will be created:

<?xml version="1.0" standalone="yes"?> <NewDataSet> <Model MODELID="1"> <MODELNAME>Economy</MODELNAME> <BASEPRICE>300</BASEPRICE> </Model> <Model MODELID="2"> <MODELNAME>Standard</MODELNAME> <BASEPRICE>350</BASEPRICE> </Model> ... </NewDataSet>

Page 53: ADO.NET Using Oracle and C# - ITCourseware Using Oracle and C# Rev. 2.0 Student Guide Information in this document is subject to change without notice. ... Acme Computer Case Study

OraAdoCs Chapter 5

Rev. 2.0 Copyright © 2006 Object Innovations Enterprises, LLC 187 All Rights Reserved

Writing Data as Attributes – Code

• Here is the code for writing out the XML data.

− Depending on the checkbox, we write it out in the default format as all elements, or with ModelId as an attribute.

− To specify the use of an XML attribute for a column, set the ColumnMapping property to MappingType.Attribute.

try { DataTable dt = ds.Tables["Model"]; if (chkAttribute.Checked == true) { dt.Columns["ModelId"].ColumnMapping = MappingType.Attribute; ds.WriteXml("..\\..\\ModelAttribut.xml"); } else { dt.Columns["ModelId"].ColumnMapping = MappingType.Element; ds.WriteXml("..\\..\\ModelElement.xml"); } } catch (Exception ex) { MessageBox.Show(ex.Message, "Error"); }

• We use exception handling in many examples to enable us to recover gracefully from errors.

− In a later demonstration we will encounter some errors.

Page 54: ADO.NET Using Oracle and C# - ITCourseware Using Oracle and C# Rev. 2.0 Student Guide Information in this document is subject to change without notice. ... Acme Computer Case Study

OraAdoCs Chapter 5

Rev. 2.0 Copyright © 2006 Object Innovations Enterprises, LLC 188 All Rights Reserved

Reading XML into a DataSet

• Reading XML has similar methods to those for writing XML.

• The main overloaded ReadXml() methods with one parameter are:

public XmlReadMode ReadXml(string fileName); // Reads from a file public XmlReadMode ReadXml(Stream stream); // Reads from a stream public XmlReadMode ReadXml( TextReader reader); // Reads using a TextReader public XmlReadMode ReadXml( XmlReader reader // Reads using an XmlReader

• As with writing, there are additional overloaded methods taking a second parameter, XmlReadMode.

− The XmlReadMode enumeration is more complex than the corresponding one for writing, and we will discuss it later in connection with reading schema information.

Page 55: ADO.NET Using Oracle and C# - ITCourseware Using Oracle and C# Rev. 2.0 Student Guide Information in this document is subject to change without notice. ... Acme Computer Case Study

OraAdoCs Chapter 5

Rev. 2.0 Copyright © 2006 Object Innovations Enterprises, LLC 189 All Rights Reserved

Demo: Reading XML Data

• Continue the demo with the ShowModelXml program in the Demos directory.

1. To show the effects of reading in an XML file, edit the file ModelData.xml to add a new model.

<?xml version="1.0" standalone="yes"?> <NewDataSet> ... <Model> <MODELID>3</MODELID> <MODELNAME>Deluxe</MODELNAME> <BASEPRICE>400</BASEPRICE> </Model> <Model> <MODELID>4</MODELID> <MODELNAME>Notebook</MODELNAME> <BASEPRICE>350</BASEPRICE> </Model> </NewDataSet> 2. Run the program and do not click the Read Database button.

Instead, try to populate the DataSet initially from the XML file. Click the Read XML button. You will get an exception.

Page 56: ADO.NET Using Oracle and C# - ITCourseware Using Oracle and C# Rev. 2.0 Student Guide Information in this document is subject to change without notice. ... Acme Computer Case Study

OraAdoCs Chapter 5

Rev. 2.0 Copyright © 2006 Object Innovations Enterprises, LLC 190 All Rights Reserved

Demo: Reading XML Data

3. You need a schema in the DataSet. You can get this by reading the Database. Do that now. You will get another error.

4. The DataSet is not in a consistent state from our two different attempts to populate it. To start clean, click the Clear button, which will create a fresh DataSet. Then click ReadDatabase. You now have the original data (and a schema).

5. Now click the Read XML button. This time, there is a schema in the DataSet, and the read operation works. You should see the new model that you added in the XML file.

Page 57: ADO.NET Using Oracle and C# - ITCourseware Using Oracle and C# Rev. 2.0 Student Guide Information in this document is subject to change without notice. ... Acme Computer Case Study

OraAdoCs Chapter 5

Rev. 2.0 Copyright © 2006 Object Innovations Enterprises, LLC 191 All Rights Reserved

DataSets and XML Schema

• Schema is key in working with DataSets.

− Database schema is required for interfacing a DataSet with a database.

− Schema information can be captured as XSD schema for working with XML.

− The XSD schema is also convenient as a serialized form of the schema in a DataSet.

• There are two ways to write out XSD schema information from a DataSet.

− Use the WriteSchema option of the XmlWriteMode enumeration in the WriteXml() method. This will yield inline schema in an XML document.

− Use the WriteXmlSchema() method. This will yield a standalone XSD schema.

• Our ShowModelXml example program writes out schema in both formats.

ds.WriteXmlSchema("..\\..\\ModelSchema.xsd"); ds.WriteXml("..\\..\\Model.xml", XmlWriteMode.WriteSchema);

Page 58: ADO.NET Using Oracle and C# - ITCourseware Using Oracle and C# Rev. 2.0 Student Guide Information in this document is subject to change without notice. ... Acme Computer Case Study

OraAdoCs Chapter 5

Rev. 2.0 Copyright © 2006 Object Innovations Enterprises, LLC 192 All Rights Reserved

Demo: Writing XML Schema

• Continue the demo with the ShowModelXml program in the Demos directory.

1. To show the effects of writing out XSD schema information, start up the program fresh, and click Read Database.

2. Schema information has now been read into the DataSet along with the data. Click the Write XML Schema button.

3. Examine the files ModelSchema.xsd and Model.xml that are created. The first file shows standalone schema, and the second shows inline schema along with the XML data. To see the first file as text data, you may open it with a text editor such as Notepad.

Page 59: ADO.NET Using Oracle and C# - ITCourseware Using Oracle and C# Rev. 2.0 Student Guide Information in this document is subject to change without notice. ... Acme Computer Case Study

OraAdoCs Chapter 5

Rev. 2.0 Copyright © 2006 Object Innovations Enterprises, LLC 193 All Rights Reserved

ModelSchema.xsd

<?xml version="1.0" standalone="yes"?> <NewDataSet> <xs:schema id="NewDataSet" xmlns="" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata" xmlns:msprop="urn:schemas-microsoft-com:xml-msprop"> <xs:element name="NewDataSet" msdata:IsDataSet="true"> <xs:complexType> <xs:choice maxOccurs="unbounded"> <xs:element name="Model" msprop:BaseTable.0="MODEL"> <xs:complexType> <xs:sequence> <xs:element name="MODELID" msprop:OraDbType="107" msprop:BaseColumn="MODELID" type="xs:decimal" /> <xs:element name="MODELNAME" msprop:OraDbType="126" msprop:BaseColumn="MODELNAME"> <xs:simpleType> <xs:restriction base="xs:string"> <xs:maxLength value="20" /> </xs:restriction> </xs:simpleType> </xs:element> <xs:element name="BASEPRICE" msprop:OraDbType="122" msprop:BaseColumn="BASEPRICE" type="xs:float" /> </xs:sequence> </xs:complexType> </xs:element> </xs:choice> </xs:complexType> <xs:unique name="Constraint1" msdata:PrimaryKey="true"> <xs:selector xpath=".//Model" /> <xs:field xpath="MODELID" /> </xs:unique> </xs:element> </xs:schema>

Page 60: ADO.NET Using Oracle and C# - ITCourseware Using Oracle and C# Rev. 2.0 Student Guide Information in this document is subject to change without notice. ... Acme Computer Case Study

OraAdoCs Chapter 5

Rev. 2.0 Copyright © 2006 Object Innovations Enterprises, LLC 194 All Rights Reserved

Reading XML Schema

• There are two methods for reading XML schema.

− Use one of the overloaded ReadXmlSchema() methods. The method shown reads the schema from a file. Other overloads can read from a stream or by using TextReader or XmlReader.

public XmlReadMode ReadXmlSchema(string fileName);

− Use the ReadXml() method with the second parameter of type XmlReadMode.

• Our example program illustrates the first method. private void cmdReadSchema_Click(object sender, System.EventArgs e) { ds = new DataSet(); ds.ReadXmlSchema("..\\..\\ModelSchema.xsd"); }

• By the way, we have been saving our XML and XSD files in the source directory, so they won’t be deleted if we clean up the binary directories.

Page 61: ADO.NET Using Oracle and C# - ITCourseware Using Oracle and C# Rev. 2.0 Student Guide Information in this document is subject to change without notice. ... Acme Computer Case Study

OraAdoCs Chapter 5

Rev. 2.0 Copyright © 2006 Object Innovations Enterprises, LLC 195 All Rights Reserved

XmlReadMode

• The XmlReadMode enumeration has quite a few options.

IgnoreSchema Ignore any inline schema and read data into the existing schema of the DataSet.

InferSchema Ignore any inline schema. Infer schema from the data and load the data into the DataSet.

ReadSchema Read the schema and add to any existing schema, throwing an exception if there are discrepancies. Load the data into the DataSet.

Fragment Read XML documents such as ones generated by FOR XML queries in SQL Server.

DiffGram Read a DiffGram and apply changes from the DiffGram to the DataSet.

Auto Perform the most appropriate action based on the data. This is the default, and may also be the slowest.

• For details, including a discussion of DiffGrams,

please refer to the MSDN documentation.

Page 62: ADO.NET Using Oracle and C# - ITCourseware Using Oracle and C# Rev. 2.0 Student Guide Information in this document is subject to change without notice. ... Acme Computer Case Study

OraAdoCs Chapter 5

Rev. 2.0 Copyright © 2006 Object Innovations Enterprises, LLC 196 All Rights Reserved

Demo: Reading XML Schema

• Continue the demo with the ShowModelXml program in the Demos directory.

1. To show the effects of reading XSD schema information, start up the program fresh, and click Read XML Schema.

2. Click Read XML. You will now be able to read the XML file without having had to read the database for the purpose of getting schema into the DataSet. You should see the additional model that you added to the XML file.

3. Try clicking Update Database. You will get an error, because the DataSet does not know about the first three rows already being in the database.

Page 63: ADO.NET Using Oracle and C# - ITCourseware Using Oracle and C# Rev. 2.0 Student Guide Information in this document is subject to change without notice. ... Acme Computer Case Study

OraAdoCs Chapter 5

Rev. 2.0 Copyright © 2006 Object Innovations Enterprises, LLC 197 All Rights Reserved

Demo: Reading XML Schema

4. Click the Clear button to get a fresh, empty DataSet.

5. Edit the ModelData.xml file to that there is only the new model you want to add.

<?xml version="1.0" standalone="yes"?> <NewDataSet> <Model> <MODELID>4</MODELID> <MODELNAME>Notebook</MODELNAME> <BASEPRICE>350</BASEPRICE> </Model> </NewDataSet> 6. Click Read XML Schema and then Read XML. You should

now see only one row.

7. Now click Update Database. This time you should succeed in updating one row. To verify, click Clear and then Read Database. You should now see that there are four rows in the Model table.

Page 64: ADO.NET Using Oracle and C# - ITCourseware Using Oracle and C# Rev. 2.0 Student Guide Information in this document is subject to change without notice. ... Acme Computer Case Study

OraAdoCs Chapter 5

Rev. 2.0 Copyright © 2006 Object Innovations Enterprises, LLC 198 All Rights Reserved

XML Data in DataTables

• In .NET 2.0 you can read and write XML data in and out of a DataTable, without the DataTable being part of a DataSet.

• An example program is ShowModelTable, which reads and writes the file Model.xml.

− This file contains schema information, as DataTable cannot infer schema.

− The code for reading and writing XML is simplicity itself:

dt.ReadXml("..\\..\\Model.xml"); ... dt.WriteXml("..\\..\\Model.xml", XmlWriteMode.WriteSchema);

Page 65: ADO.NET Using Oracle and C# - ITCourseware Using Oracle and C# Rev. 2.0 Student Guide Information in this document is subject to change without notice. ... Acme Computer Case Study

OraAdoCs Chapter 5

Rev. 2.0 Copyright © 2006 Object Innovations Enterprises, LLC 199 All Rights Reserved

Typed DataSets

• Although the coding is straightforward, there is one problem in working with ordinary DataSets: they are not typed, so casting is ubiquitous.

− This can cause a runtime error if, for example, a wrong column name is supplied.

• The ShowModelXml program we have been working with contains typical casting code used with untyped DataSets.

private void ShowDataSet() { lstModel.Items.Clear(); DataTable dt = ds.Tables["Model"]; foreach (DataRow row in dt.Rows) { Model m = new Model( (int) (decimal) row["ModelId"], (string) row["ModelName"], (decimal) (float) row["BasePrice"]); lstModel.Items.Add(m); } }

• Corresponding code for a typed DataSet is type-safe. (The single cast is an artifact of our Model class.)

foreach (ModelDs.MODELRow row in modelDs1.MODEL) { Model m = new Model((int) row.MODELID, row.MODELNAME, row.BASEPRICE); lstModel.Items.Add(m); }

Page 66: ADO.NET Using Oracle and C# - ITCourseware Using Oracle and C# Rev. 2.0 Student Guide Information in this document is subject to change without notice. ... Acme Computer Case Study

OraAdoCs Chapter 5

Rev. 2.0 Copyright © 2006 Object Innovations Enterprises, LLC 200 All Rights Reserved

Table Adapter

• .NET 2.0 introduces a new strongly-typed class, TableAdapter that is the strongly-typed equivalent of DataAdapter.

• With the TableAdapter you can connect to the database and execute queries against the database and fill a DataTable.

• Visual Studio 2005 will automatically generate a strongly-typed TableAdatper associated with a specific table in your database.

• You can then populate a strongly-typed DataTable with just a few lines of code.

− For example, see the program TypedModel in the chapter directory. Examine the file Form1.cs.

using TypedModel.ModelDsTableAdapters; using TypedModel.Properties; ... private MODELTableAdapter ta; private ModelDs.MODELDataTable dt; ... ta = new MODELTableAdapter(); dt = ta.GetData();

Page 67: ADO.NET Using Oracle and C# - ITCourseware Using Oracle and C# Rev. 2.0 Student Guide Information in this document is subject to change without notice. ... Acme Computer Case Study

OraAdoCs Chapter 5

Rev. 2.0 Copyright © 2006 Object Innovations Enterprises, LLC 201 All Rights Reserved

Demo: Creating a Typed DataSet Using Visual Studio

• As you will see by examining the file for ModelDs.Designer.cs, the code for a robust typed DataSet is quite long and intricate.

• Fortunately, a typed DataSet can be created for you automatically by Visual Studio.

• As a demonstration, let’s create a Windows application TypedModel with a typed DataSet for the Model table in the AcmeComputer database.

− Do your work in the Demos directory.

1. Use Visual Studio to create a new Windows Application called TypedModel. Save the solution in the Demos directory.

2. Provide a simple user interface consisting of a list box.

3. Right-click on the TypedModel project in solution explorer and choose Add | New Item from the context menu.

Page 68: ADO.NET Using Oracle and C# - ITCourseware Using Oracle and C# Rev. 2.0 Student Guide Information in this document is subject to change without notice. ... Acme Computer Case Study

OraAdoCs Chapter 5

Rev. 2.0 Copyright © 2006 Object Innovations Enterprises, LLC 202 All Rights Reserved

Demo: Creating a Typed DataSet

4. In the dialog box that comes up choose DataSet as the template and type in ModelDs.xsd as the name. (Visual Studio will use this name for the name of your class, and you will get a conflict if you use the name “Model”, which is the same as the table in the database.)

5. Click Add.

6. Open up DataBase Explorer in Express Edition or Server Explorer in full-blown Visual Studio.

Page 69: ADO.NET Using Oracle and C# - ITCourseware Using Oracle and C# Rev. 2.0 Student Guide Information in this document is subject to change without notice. ... Acme Computer Case Study

OraAdoCs Chapter 5

Rev. 2.0 Copyright © 2006 Object Innovations Enterprises, LLC 203 All Rights Reserved

Demo: Creating a Typed DataSet

7. Right-click on Data Connections and select .NET Framework Provider for OLE DB as the data source.

8. Click OK. In the Add Connection dialog that comes up, Choose Oracle Provider for .NET as the OLE DB Provider. For server name, enter xe (or orcl if you are using full-blown Oracle). Enter acme as the user name and computer as the password.

9. Click Test Connection, which should succeed. Click OK.

10. Examine the connection information in app.config.

... <connectionStrings> <add name= "Typed_Model.Properties.Settings.ConnectionString" connectionString= "Provider=OraOLEDB.Oracle.1;Data Source=xe; Password=computer;User ID=acme" providerName="System.Data.OleDb" /> </connectionStrings> ...

Page 70: ADO.NET Using Oracle and C# - ITCourseware Using Oracle and C# Rev. 2.0 Student Guide Information in this document is subject to change without notice. ... Acme Computer Case Study

OraAdoCs Chapter 5

Rev. 2.0 Copyright © 2006 Object Innovations Enterprises, LLC 204 All Rights Reserved

Demo: Creating a Typed DataSet

11. Open up the tables for the AcmeComputer database and select the MODEL table.

12. Drag the MODEL table onto the designer surface of ModelDs.xsd. You will be warned about saving the connection string in the configuration file as plain text. Say Yes. You will see a DataSet for MODEL.

Page 71: ADO.NET Using Oracle and C# - ITCourseware Using Oracle and C# Rev. 2.0 Student Guide Information in this document is subject to change without notice. ... Acme Computer Case Study

OraAdoCs Chapter 5

Rev. 2.0 Copyright © 2006 Object Innovations Enterprises, LLC 205 All Rights Reserved

Demo: Creating a Typed DataSet

13. The file ModelDs.Designer.cs has now been generated. You will find this file underneath ModelDs.xsd.

14. We can now write code to use this DataSet for accessing the Model table in the AcmeComputer database. For the complete example, see the TypedModel project in the chapter directory, which includes the file Model.cs that we have used many times.

Page 72: ADO.NET Using Oracle and C# - ITCourseware Using Oracle and C# Rev. 2.0 Student Guide Information in this document is subject to change without notice. ... Acme Computer Case Study

OraAdoCs Chapter 5

Rev. 2.0 Copyright © 2006 Object Innovations Enterprises, LLC 206 All Rights Reserved

Demo: Creating a Typed DataSet

• Build the project. You can now use the Object Browser to examine the various classes that were generated automatically for you.

− This information will help you write the (simple) code required to populate the list box with data from the MODEL table.

Page 73: ADO.NET Using Oracle and C# - ITCourseware Using Oracle and C# Rev. 2.0 Student Guide Information in this document is subject to change without notice. ... Acme Computer Case Study

OraAdoCs Chapter 5

Rev. 2.0 Copyright © 2006 Object Innovations Enterprises, LLC 207 All Rights Reserved

Using the Typed Data Set

• Here is the code for our simple example. using TypedModel.ModelDsTableAdapters; using TypedModel.Properties; ... private string connstr; private MODELTableAdapter ta; private ModelDs.MODELDataTable dt; private void Form1_Load(object sender, EventArgs e) { Settings set = Settings.Default; connstr = set.ConnectionString; ta = new MODELTableAdapter(); dt = ta.GetData(); ShowModels(); } private void ShowModels() { lstModel.Items.Clear(); foreach (ModelDs.MODELRow row in dt) { Model m = new Model((int)row.MODELID, row.MODELNAME, row.BASEPRICE); lstModel.Items.Add(m); } }

Page 74: ADO.NET Using Oracle and C# - ITCourseware Using Oracle and C# Rev. 2.0 Student Guide Information in this document is subject to change without notice. ... Acme Computer Case Study

OraAdoCs Chapter 5

Rev. 2.0 Copyright © 2006 Object Innovations Enterprises, LLC 208 All Rights Reserved

Synchronizing DataSets and XML

• A powerful feature of the XML support in ADO.NET is the capability of automatically keeping an XML document synchronized with a DataSet.

− You can then update either the DataSet or the XML document, and the other will immediately reflect the change.

• As an example, consider the ModelDOM program.

− Top listbox shows a relational view of data in DataSet.

− The bottom multi-line textbox shows a hierarchical view of the corresponding XML document, accessed through the XML Document Object Model (DOM).

− These two are always in synch!

Page 75: ADO.NET Using Oracle and C# - ITCourseware Using Oracle and C# Rev. 2.0 Student Guide Information in this document is subject to change without notice. ... Acme Computer Case Study

OraAdoCs Chapter 5

Rev. 2.0 Copyright © 2006 Object Innovations Enterprises, LLC 209 All Rights Reserved

Using XmlDataDocument

• The key class supporting this synchronizing is XmlDataDocument in the System.Xml namespace.

− This class derives from XmlDocumenet, which is the .NET class giving access to the DOM.

• The sample program sets up the XmlDataDocument as part of filling the DataSet.

private XmlDataDocument xmlDoc; ... private void FillDataSet() { ds = new DataSet(); // Fill the data set and set up data table da.Fill(ds, "Model"); dt = ds.Tables["Model"]; // Set up the XML document xmlDoc = new XmlDataDocument(ds); // Show the data set and document ShowDataSet(); ShowDataDocument(); }

Page 76: ADO.NET Using Oracle and C# - ITCourseware Using Oracle and C# Rev. 2.0 Student Guide Information in this document is subject to change without notice. ... Acme Computer Case Study

OraAdoCs Chapter 5

Rev. 2.0 Copyright © 2006 Object Innovations Enterprises, LLC 210 All Rights Reserved

Using XmlDataDocument (Cont’d)

• The ShowDocument() method displays the XML document using the DOM.

private void ShowDataDocument() { string NL = Environment.NewLine; XmlNodeList models = xmlDoc.GetElementsByTagName("Model"); string output = ""; foreach (XmlNode node in models) { output += "Model" + NL; foreach (XmlNode n in node.ChildNodes) { output += " " + n.InnerText + NL; } } txtDOM.Text = output; }

• The ShowDocument() method is called whenever the DataSet is changed.

private void cmdAdd_Click(object sender, System.EventArgs e) { DataRow row = dt.NewRow(); row["ModelId"] = Convert.ToInt32(txtId.Text); row["ModelName"] = txtName.Text; row["BasePrice"] = Convert.ToDecimal(txtPrice.Text); dt.Rows.Add(row); ShowDataSet(); ShowDataDocument(); }

Page 77: ADO.NET Using Oracle and C# - ITCourseware Using Oracle and C# Rev. 2.0 Student Guide Information in this document is subject to change without notice. ... Acme Computer Case Study

OraAdoCs Chapter 5

Rev. 2.0 Copyright © 2006 Object Innovations Enterprises, LLC 211 All Rights Reserved

XML Serialization

• The .NET Framework provides great support for serializing data using XML.

− This can be useful if you are persisting data in a program.

− Some data may be stored in a DataSet, which can be written to XML as we have seen.

− Other data may not be in a DataSet, but we can still easily store it as an XML document.

• As an example, let’s see how we could save the state of a single Model object.

− The example program is SerializeModel.

− Change the data, click Save. The data for this object is then written out to the file Model.xml (in directory bin\Debug).

− You could then verify that it can be restored by clicking Clear followed by Restore.

Page 78: ADO.NET Using Oracle and C# - ITCourseware Using Oracle and C# Rev. 2.0 Student Guide Information in this document is subject to change without notice. ... Acme Computer Case Study

OraAdoCs Chapter 5

Rev. 2.0 Copyright © 2006 Object Innovations Enterprises, LLC 212 All Rights Reserved

XML Serialization Code Example

... using System.Xml.Serialization; using System.IO; ... private void cmdSave_Click(object sender, System.EventArgs e) { int id = Convert.ToInt32(txtId.Text); string name = txtName.Text; decimal price = Convert.ToDecimal(txtPrice.Text); Model m = new Model(id, name, price); XmlSerializer ser = new XmlSerializer(typeof(Model)); FileStream fs = new FileStream("model.xml", FileMode.Create); ser.Serialize(fs, m); fs.Close(); } private void cmdRestore_Click(object sender, System.EventArgs e) { XmlSerializer ser = new XmlSerializer(typeof(Model)); FileStream fs = new FileStream("model.xml", FileMode.Open); Model m = (Model) ser.Deserialize(fs); txtId.Text = m.ModelId.ToString(); txtName.Text = m.ModelName.ToString(); txtPrice.Text = string.Format("{0:F2}", m.BasePrice); fs.Close(); }

Page 79: ADO.NET Using Oracle and C# - ITCourseware Using Oracle and C# Rev. 2.0 Student Guide Information in this document is subject to change without notice. ... Acme Computer Case Study

OraAdoCs Chapter 5

Rev. 2.0 Copyright © 2006 Object Innovations Enterprises, LLC 213 All Rights Reserved

Default Constructor

• The class that is being serialized must have a default constructor.

− The .NET Framework requires this during the serialization process.

// Model.cs using System; public class Model { public int ModelId; public string ModelName; public decimal BasePrice; public Model() { } public Model(int id, string name, decimal price) { ModelId = id; ModelName = name; BasePrice = price; } public override string ToString() { return ModelId + " " + ModelName + " " + string.Format("{0:C}", BasePrice); } }

Page 80: ADO.NET Using Oracle and C# - ITCourseware Using Oracle and C# Rev. 2.0 Student Guide Information in this document is subject to change without notice. ... Acme Computer Case Study

OraAdoCs Chapter 5

Rev. 2.0 Copyright © 2006 Object Innovations Enterprises, LLC 214 All Rights Reserved

Lab 5

Creating and Using a Typed DataSet

In this lab, you will use Visual Studio 2005 to create a typed DataSet for accessing the Component table. You will also write a program to display the components using the typed DataSet that you created.

Detailed instructions are contained in the Lab 5 write-up at the end of the chapter.

Suggested time: 30 minutes

Page 81: ADO.NET Using Oracle and C# - ITCourseware Using Oracle and C# Rev. 2.0 Student Guide Information in this document is subject to change without notice. ... Acme Computer Case Study

OraAdoCs Chapter 5

Rev. 2.0 Copyright © 2006 Object Innovations Enterprises, LLC 215 All Rights Reserved

Summary

• There is a strong coupling between ADO.NET and XML.

• You can easily render the data in a DataSet into XML using overloaded WriteXml() methods.

• You can control whether data in the DataSet gets rendered in XML elements or attributes.

• You can read XML into a DataSet using ReadXml() methods.

• Schema information can be exchanged between DataSets and XML.

• You can use Visual Studio 2005 to create typed DataSets.

• The XmlDataDocument class supports synchronization of information between an XML document and a DataSet.

• XML Serialization allows you to serialize data to a flat file using XML.

Page 82: ADO.NET Using Oracle and C# - ITCourseware Using Oracle and C# Rev. 2.0 Student Guide Information in this document is subject to change without notice. ... Acme Computer Case Study

OraAdoCs Chapter 5

Rev. 2.0 Copyright © 2006 Object Innovations Enterprises, LLC 216 All Rights Reserved

Lab 5

Creating and Using a Typed DataSet

Introduction In this lab, you will use Visual Studio 2005 to create a typed DataSet for accessing the Component table. You will also write a program to display the components using the typed DataSet that you created.

Suggested Time: 30 minutes Root Directory: OIC\OraAdoCs Directories: Labs\Lab5\TypedComponent (do your work here) Chap05\TypedComponentl (answer) Database: AcmeComputer 1. If you have not already done so, add a connection in Server Explorer to your Oracle

Acme Computer database. Use the .NET Framework Data Provider for OLE DB as the .NET data provider and either the Oracle or Microsoft OLE DB provider.

2. Create a new C# Windows Application TypedComponent.

3. Add a list box to the form of your Windows application and make the title of the main form Typed Component.

4. Add a new DataSet ComponentDs.xsd to your project.

Page 83: ADO.NET Using Oracle and C# - ITCourseware Using Oracle and C# Rev. 2.0 Student Guide Information in this document is subject to change without notice. ... Acme Computer Case Study

OraAdoCs Chapter 5

Rev. 2.0 Copyright © 2006 Object Innovations Enterprises, LLC 217 All Rights Reserved

5. In Server Explorer open up your connection to the Acme Computer database and drag the COMPONENT table onto the designer surface of the DataSet.

6. Examine the file app.config. If necessary, provide the proper Password part of the connection string.

7. Copy the file Component.cs from the BuyComputer case study into your working directory and add it to your project.

8. Change the namespace in Component.cs to TypedComponent.

9. Provide the following using statements.

using TypedComponent.ComponentDsTableAdapters; using TypedComponent.Properties; 10. In the Form1 class add the following data members.

private string connstr; private COMPONENTTableAdapter ta; private ComponentDs.COMPONENTDataTable dt; 11. Add a handler for the form load event. In this handler provide code to do the

following.

a. Assign connstr from information in the application’s configuration file, using the Settings property.

b. Initialize ta by instantiating a new COMPONENTTableAdapter.

c. Populate the DataTable dt by calling GetData().

d. Call a helper method ShowComponents() to display the DataTable in the list box.

private void Form1_Load(object sender, EventArgs e) { Settings set = Settings.Default; connstr = set.ConnectionString; ta = new COMPONENTTableAdapter(); dt = ta.GetData(); ShowComponents(); } 12. Implement ShowComponents() by code similar to ShowModels() in the class demo.

private void ShowComponents() { lstComp.Items.Clear(); foreach (ComponentDs.COMPONENTRow row in dt) { Component c = new Component((int)row.COMPID,

Page 84: ADO.NET Using Oracle and C# - ITCourseware Using Oracle and C# Rev. 2.0 Student Guide Information in this document is subject to change without notice. ... Acme Computer Case Study

OraAdoCs Chapter 5

Rev. 2.0 Copyright © 2006 Object Innovations Enterprises, LLC 218 All Rights Reserved

row.DESCRIPTION, row.UNIT); lstComp.Items.Add(c); } } 13. Build and test.