ibm power systems ™ agenda key: session number: system i access in the.net world lorie dubois -...
TRANSCRIPT
8 Copyright IBM Corporation, 2008. All Rights Reserved.
This publication may refer to products that are not currently available in your country. IBM makes no commitment to make available any products referred to herein.
IBM Power Systems™
Agenda Key:Session Number:
System i Access in the .NET World
Lorie DuBois - [email protected]
System i Access Development
43ME420219
IBM Power Systems
2 © 2008 IBM Corporation
Agenda
• Microsoft Data Access Technologies• .NET Overview• ADO.NET• Data Providers for System i• System i Access for Windows .NET Provider• IBM Data Server .NET Provider• Visual Studio 2005 Integration • Examples• Performance / Coding Tips
IBM Power Systems
3 © 2008 IBM Corporation
Agenda
►Microsoft Data Access Technologies• .NET Overview• ADO.NET• Data Providers for System i• System i Access for Windows .NET Provider• IBM Data Server .NET Provider• Visual Studio 2005 Integration • Examples• Performance / Coding Tips
IBM Power Systems
4 © 2008 IBM Corporation
Microsoft Data Access Technologies
• DB-Library
• ESQL
• DAO
• ODBC, JDBC
• ADO/OLE DB
• ADO.NET
.NET is being used more and more
Today and FuturePast
IBM Power Systems
5 © 2008 IBM Corporation
Data Access Technologies
ODBC– Call-level interface for access to relational databases– Widely used– Complex
OLE DB – Designed for more generic access, not just relational databases and SQL– Higher-level than ODBC– Visual Basic / ADO simpler programming model– COM interfaces, availability of interfaces is provider-specific
JDBC– Java classes
ADO.NET– Data Providers DataSet– Disconnected access– Part of .NET Framework
DataAdapter
IBM Power Systems
6 © 2008 IBM Corporation
Agenda
• Microsoft Data Access Technologies►.NET Overview• ADO.NET• Data Providers for System i• System i Access for Windows .NET Provider• IBM Data Server .NET Provider• Visual Studio 2005 Integration • Examples• Performance / Coding Tips
IBM Power Systems
7 © 2008 IBM Corporation
.NET framework– Underlying plumbing for .NET applications– Common Language Runtime (CLR)– Unified set of class libraries
CLR– Language integration, security handling, memory/thread/process
management, exception handling, etc
ADO.NET– .NET classes enabling access to databases
ASP.NET– .NET classes to support development of Web-based applications
and Web services
.NET definitions
IBM Power Systems
8 © 2008 IBM Corporation
Assemblies vs Binaries
• Intermediate Language (IL)• JIT compiled• Self describing metadata• Referenced by namespace,
version, and culture• “Managed” code targets
the .NET Framework
• Platform specific byte codes
• Type libraries (IDL)• Referenced by Registry
• “Unmanaged” code
.NET languages VB.NET
C#
Previous Windows DLL/EXE compilers
IBM Power Systems
9 © 2008 IBM Corporation
Interesting .NET features
• Garbage collection
• IL code and JIT compiler
• “Side by side” assembly– .NET 1.1 provider– .NET 2.0 provider
• Common Language Specification
• Common Type System- Value types- Reference type
• COM and Win32 still alive but use .NET classes when available
IBM Power Systems
10 © 2008 IBM Corporation
A Short History of the .NET Framework
.NET Framework 1.0– Visual Studio 2002
– Microsoft.Data.Odbc web download
.NET Framework 1.1– Visual Studio 2003
– System.Data.Odbc
.NET Framework 2.0– .Visual Studio 2005
– Major changes to ADO.NET
– Finally –Provider Factories andcomplete System.Data.Common
.NET Framework 3.0– Basically 2.0 Framework + WinFX
• WCF Windows Communication Foundation
• WPF Windows Presentation Foundation
• WF Windows Workflow Foundation
• Card Space
– No changes to the provider
.NET Framework 3.5– Visual Studio 2008– Language Integrated Query (LINQ)
• Query language built into C#, VB• Manage relational data as objects• Compile-time support
IBM Power Systems
11 © 2008 IBM Corporation
Agenda
• Microsoft Data Access Technologies• .NET Overview►ADO.NET• Data Providers for System i• System i Access for Windows .NET Provider• IBM Data Server .NET Provider• Visual Studio 2005 Integration • Examples• Performance / Coding Tips
IBM Power Systems
12 © 2008 IBM Corporation
ADO Architecture• Used with Visual Basic
• ADO uses an underlying OLE DB provider
• MSDASQL - OLE DB provider that targets an ODBC driver
Data Source
Connection
Command
Parameters
Recordset
Record
Properties
OLE DB Provider
- Server-side cursors(read-only, updatable, static, etc) - Client cursor engine (static copy, optimistic updates)
IBM Power Systems
13 © 2008 IBM Corporation
ADO.NET Architecture
XML
Connection Transaction
CommandParameters
DataReaderDataAdapter
SELECT INSERT
UPDATE DELETE.NET Provider Data Source
Static copy, Optimistic Updates
Forward-onlyRead-only
DataRelations
DataTable
Rows
Columns
Metadata
Constraints DataSet
Disconnected
IBM Power Systems
14 © 2008 IBM Corporation
.NET Provider- System i Access .NET Provider
(IBM.Data.DB2.iSeries)
- IBM Data Server .NET Provider(IBM.Data.DB2)
OLE DB Provider- System i Access OLE DB Providers
(IBMDASQL, IBMDA400, IBMDARLA)
- OLE DB Provider for DB2® (IBMDADB2)
.NET Applications
System.Data.OleDb
System.Data.Odbc
ADO.NET
Legacy Applications
ODBC Driver- System i Access
ODBC Driver
- IBM Data Server Driver for ODBC and CLI
MSDASQL
ADO
Data Source DB2 for i5/OS
CO
M
Inte
rop
IBM Power Systems
15 © 2008 IBM Corporation
Agenda
• Microsoft Data Access Technologies• .NET Overview• ADO.NET►Data Providers for System i• System i Access for Windows .NET Provider• IBM Data Server .NET Provider• Visual Studio 2005 Integration • Examples• Performance / Coding Tips
IBM Power Systems
16 © 2008 IBM Corporation
ADO.NET Data Providers for System i
• IBM .NET providers System i Access for Windows .NET Provider (IBM.Data.DB2.iSeries) IBM Data Server .NET Provider (IBM.Data.DB2)
• Microsoft .NET Provider for OLE DB (System.Data.OleDb)– System i Access for Windows OLE DB providers
(IBMDASQL, IBMDA400)
– IBM OLE DB Provider for DB2® (IBMDADB2)
• Microsoft .NET Provider for ODBC (System.Data.Odbc)– System i Access for Windows ODBC driver
– IBM Data Server Driver for ODBC and CLI
IBM Power Systems
17 © 2008 IBM Corporation
ADO Data Providers for System i
• IBM OLE DB providers– System i Access for Windows OLE DB Providers
(IBMDASQL, IBMDA400, IBMDARLA)
– IBM OLE DB Provider for DB2® (IBMDADB2)
• Microsoft OLE DB provider for ODBC (MSDASQL)– MSDASQL originally not supported in 64-bit, but due to popular demand,
is now in Windows Server 2008 and Vista SP1• System i Access ODBC driver• IBM Data Server Driver for ODBC and CLI
IBM Power Systems
18 © 2008 IBM Corporation
Agenda
• Microsoft Data Access Technologies• .NET Overview• ADO.NET• Data Providers for System i►System i Access for Windows .NET Provider• IBM Data Server .NET Provider• Visual Studio 2005 Integration • Examples• Performance / Coding Tips
IBM Power Systems
19 © 2008 IBM Corporation
General Information
• Part of System i Access for Windows 5761-XE1 no additional license needed
• V5R3M0 / V5R4M0 Target the 1.0 and 1.1 .NET Framework
• V6R1M0 Requires the 2.0 .NET Framework
• Works with System i database server jobs (QZDASOINIT)
• N-2 Support for iSeries / System i – V5R3M0, V5R4M0, V6R1M0
• Using an older application with the V6R1M0 provider requires:- Recompilation with Visual Studio 2005, or- Assembly redirect (machine.config or app.config) 10.0.0.0 12.0.0.0
• Documentation installed as part of the Toolkit component, in \Client Access\MRIxxxx folder (cwbmptch.hlp)
IBM Power Systems
20 © 2008 IBM Corporation
Features of the System i Access for Windows.NET Provider (V5R4M0)• Namespace IBM.Data.DB2.iSeries (iDB2Connection, iDB2Command…)• SQL statements and Stored Procedures• Commitment Control (local transactions)• Connection Pooling• SQL and System naming• LibraryList• LOBs• Unicode• Threads• IASPs (multiple databases)• Works with System i servers only• IntelliSense• Multiple active result sets• Works with all Access for Windows authentication and comm protocols
IBM Power Systems
21 © 2008 IBM Corporation
V6R1M0 Enhancements
• Support for .NET Framework 2.0 base class model (System.Data.Common)
• 64-bit support (one DLL does both 32-bit and 64-bit) – install SP1• Distributed transactions via System.Transactions• Multi-row (block) inserts using the AddBatch method• Permission classes• Many new ConnectionString properties• Integration with Visual Studio 2005 wizards• CommandBuilder enhancements• Decimal float and Datalink data types• Improved control over sending and receiving
data in blocks
V6R1
IBM Power Systems
22 © 2008 IBM Corporation
New Classes in V6R1M0
• iDB2ConnectionStringBuilder• iDB2DataSourceEnumerator• iDB2DataLink data type• iDB2DecFloat16 and iDB2DecFloat34 data types• iDB2Factory• iDB2Permission / iDB2PermissionAttribute• iDB2NullValueException• iDB2TransactionFailedException
IBM Power Systems
23 © 2008 IBM Corporation
New ConnectionString properties in V6R1M0
• Properties corresponding to new Special Registers:
– ApplicationName – default value is the name of the .exe program
– ClientAccounting– ClientProgram ID– ClientUser ID– ClientWorkstation
• Decimal float properties:– DecfloatErrorOption– DecfloatRoundingMode– DecNumericAsString property also
applies to Decimal float types
23
• Distributed Transaction properties:– Enlist– TransactionCompletionTimeout– XaLockTimeout– XaTransactionTimeout
• Miscellaneous properties:– AutocommitIsolationLevel– BlockSize– EnablePreFetch– LobBlockSize– NumericErrorOption– PersistSecurityInfo– QueryStorageLimit
IBM Power Systems
24 © 2008 IBM Corporation
New ConnectionString properties in V6R1M0
• Schema property:– SchemaSearchList
Only used with the GetSchema methods
Useful with Visual Studio Server Explorer
24
• Properties that can inherit from iDB2ProviderSettings or be set on the ConnectionString:
– DateTimeAsString– DecNumericAsString– CharBitDataAsString– CharBitDataCcsid
Setting these properties on the ConnectionString overrides whatever may be set in iDB2ProviderSettings.
When SchemaSearchList is notspecified, the default value depends on the naming convention:
SQL naming DefaultCollectionSystem naming LibraryList
IBM Power Systems
25 © 2008 IBM Corporation
New iDB2CommandBuilder options in V6R1M0
• SetAllValues property – affects data sent on the Update command– False ties in with new DB2 for i5/OS Extended Indicator support– True same behavior as in the past
• ConflictOption property – affects how optimistic updates are performed– CompareAllSearchableValues
• Same behavior as in the past all searchable values checked in WHERE clause
– CompareRowVersion• Requires new Row Change Timestamp• Better optimistic update method only row change timestamp and RID are checked in
WHERE clause
– OverwriteChanges• Only key values are used in the WHERE clause when making updates
Careful, this option does not detect conflicting changes
IBM Power Systems
26 © 2008 IBM Corporation
For more information
• System i Access for Windows .NET Provider web page– http://www.ibm.com/systems/i/software/access/windows/dotnet/
• NET Technical Reference - cwbmptch.hlp– Found in ..\IBM\Client Access\Mrixxxx directory
Documents all the class interfaces for the .NET Provider
• “V6R1 Breathes New Life into DB2 for i5/OS .NET Provider”– http://www.mcpressonline.com/database/db2/v6r1-breathes-new-life-into-db2-for-i
5/os-net-provider.html
• Redbook – “Integrating DB2 Universal Database for iSeries with Microsoft ADO .NET”– http://www.redbooks.ibm.com/abstracts/sg246440.html?Open
describes the older ADO.NET 1.0/1.1 provider functionality
IBM Power Systems
27 © 2008 IBM Corporation
Agenda
• Microsoft Data Access Technologies• .NET Overview• ADO.NET• Data Providers for System i• System i Access for Windows .NET Provider► IBM Data Server .NET Provider• Visual Studio 2005 Integration • Examples• Performance / Coding Tips
IBM Power Systems
28 © 2008 IBM Corporation
General Information• Several pieces of the puzzle:
– IBM Data Server .NET Provider (version 9.0 or 9.5)– IBM Database Add-ins for Visual Studio 2005
• IBM Data Server Client contains both the .NET Provider and the VS Add-ins
– DB2 Connect license required for access to System i
• Several packaging schemes, see: Types of IBM data server clients athttp://publib.boulder.ibm.com/infocenter/db2luw/v9r5/index.jsp?topic=/com.ibm.db2.luw.qb.client.doc/doc/c0022612.html
• Support for – 1.1 .NET Framework– 2.0 and 3.0 .NET Framework– 64-bit operating systems (no Itanium support)
• requires 2.0+ Framework• packaged as separate 32-bit and 64-bit assemblies
• Works with System i DRDA server jobs (QRWTSRVR)
IBM Power Systems
29 © 2008 IBM Corporation
Features of the IBM Data Server .NET Provider (V9.0)
• Namespace IBM.Data.DB2 (DB2Connection, DB2Command…)• SQL statements and Stored Procedures, SQL naming only• Local and Distributed transactions• Federated database support• Connection Pooling• Unicode• Threads• Support for many types of database servers, not just System I
– DB2® -- Linux, UNIX, Windows, z/OS, System i– UniVerse® version 10.2 or later use “ServerType=UNIVERSE” in ConnectionString– UniData® version 7.1.11 or later use “ServerType=UNIDATA” in ConnectionString
• The following .NET Provider features are not supported by U2 servers (UniVerse and UniData):
– Multiple active result sets– LOBs, XML– DB2BulkCopy, DB2ResultSet, DB2Types,
ExecutePageReader, UpdateBatchSize
IBM Power Systems
30 © 2008 IBM Corporation
Features of the IBM Data Server .NET Provider (V9.5)
The V9.5 release extends functionality of the 9.0 release:
• Support for IBM Informix® Dynamic Server (IDS), version 11.10 and later– Can use IBM.Data.DB2 provider (DB2Connection, DB2Command, etc), or
IBM.Data.Informix provider (IfxConnection, IfxCommand, etc), the behavior is the same
IBM Power Systems
31 © 2008 IBM Corporation
DB2 Development Add-ins for Visual Studio 2005
The DB2 Add-ins for Visual Studio 2005 9.5 contain many features:
• Support for many different types of IBM Data Servers
• Integration with Visual Studio Server Explorer– IBM Server Explorer no longer used
• Designers to create, clone, and modify database objects– Tables and Views– Stored Procedures and Functions
• Web Services– Create and deploy Web services for WAS CE v1.1 / Apache Tomcat v5.5– Create and deploy IIS Web Services
• New filters for viewing different types of tables and selecting schemas to display
• Enhanced XML tooling– Register Annotated XML Schema– Generate Web services for Annotated XML Schema
• Support for federated databases (Nicknames)
IBM Power Systems
32 © 2008 IBM Corporation
Supported tools
• Visual Studio 2005 supported by V9 and 9.5
• Visual Studio 2008 supported by V9.5 FP1
• LINQ – not supported yet but high priority
• Enterprise Framework Library – not supported yet but high priority
IBM Power Systems
33 © 2008 IBM Corporation
For more information
• IBM Data Server .NET Provider– DB2 Connect
http://www.ibm.com/software/data/db2/db2connect
– Recommended reading list: DB2 for Linux, UNIX, and Windows development:http://www.ibm.com/developerworks/db2/library/techarticle/dm-0509poon2/
– DB2 and .NET FAQhttp://www.ibm.com/developerworks/wikis/display/DB2/DB2+and+.NET+FAQ
– DB2 Version 9.5 for Linux, UNIX, and Windows:Developing ADO.NET and OLE DB Applicationsftp://ftp.software.ibm.com/ps/products/db2/info/vr95/pdf/en_US/db2ane950.pdf
• IBM Database Add-ins for Visual Studio 2005– Overview of IBM Database Add-ins for Visual Studio 2005 .NET
http://www.ibm.com/developerworks/db2/library/techarticle/dm-0512surange/
IBM Power Systems
34 © 2008 IBM Corporation
Agenda
• Microsoft Data Access Technologies• .NET Overview• ADO.NET• Data Providers for System i• System i Access for Windows .NET Provider• IBM Data Server .NET Provider► Visual Studio 2005 Integration• Examples• Performance / Coding Tips
IBM Power Systems
35 © 2008 IBM Corporation
Visual Studio 2005 Integration – Server Explorer
• DataSource
• SchemaSearchList
System i Access for Windows .NET Provider
Schema names must be properly delimited
Generic Microsoft GUIs
IBM Power Systems
36 © 2008 IBM Corporation
Visual Studio 2005 Integration – Server Explorer
The schema(s) listed here are those listed in the SchemaSearchList property
System i Access for Windows .NET Provider
IBM Power Systems
37 © 2008 IBM Corporation
Visual Studio 2005 Integration – Server Explorer
IBM Data Server .NET Provider
Schema names must be properly cased, without delimiters
Be sure to set theSchemaFilter!
IBM generated GUIs
Database name is the RDB / IASP name
IBM Power Systems
38 © 2008 IBM Corporation
Visual Studio 2005 Integration – Server Explorer
IBM Data Server .NET Provider
The items listed here are those contained in the schemas listed in the Schema filter
IBM Power Systems
39 © 2008 IBM Corporation
Visual Studio 2005 Integration – Providers
You can also connect to OLE DB, ODBC, etc
IBM Power Systems
40 © 2008 IBM Corporation
IBM Database Add-ins for Visual Studio 2005
File New Project…
IBM Power Systems
41 © 2008 IBM Corporation
IBM Database Add-ins for Visual Studio 2005
View Toolbars
IBM Power Systems
42 © 2008 IBM Corporation
IBM Database Add-ins for Visual Studio 2005
Project settings
Debugging stored procedures is not supported with System i
IBM Power Systems
43 © 2008 IBM Corporation
IBM Database Add-ins for Visual Studio 2005
Tools IBM Database Tools
IBM Power Systems
44 © 2008 IBM Corporation
IBM Database Add-ins for Visual Studio 2005
Help settings
IBM Power Systems
45 © 2008 IBM Corporation
Agenda
• Microsoft Data Access Technologies• .NET Overview• ADO.NET• Data Providers for System i• System i Access for Windows .NET Provider• IBM Data Server .NET Provider• Visual Studio 2005 Integration ► Examples• Performance / Coding Tips
IBM Power Systems
46 © 2008 IBM Corporation
Examples
• Generic coding with Provider Factories• Visual Studio Drag and Drop• Distributed Transactions• AddBatch method for quickly filling a table• ConnectionStringBuilder• Federated Database scenario
IBM Power Systems
47 © 2008 IBM Corporation
Example: Generic coding with Provider Factories
• Use Provider Factories for database-agnostic programming:– Different factory name– Different ConnectionString– Possibly different Parameter marker formats (@name, ?)– Almost everything else the same
DbProviderFactory
methods
IBM Power Systems
48 © 2008 IBM Corporation
Example: Generic coding with Provider Factories
// Different provider factory names
DbProviderFactory factory = DbProviderFactories.GetFactory("IBM.Data.DB2.iSeries");
// DbProviderFactory factory = DbProviderFactories.GetFactory("IBM.Data.DB2");
DbConnection cn = factory.CreateConnection();
DbConnectionStringBuilder sb = factory.CreateConnectionStringBuilder();
// Different Connection-String properties
sb["DataSource"] = "mySystemi"; // IBM System i Access for Windows .NET Provider
// sb["Server"] = "mySystemi:446"; // IBM Data Server .NET Provider
// sb["Database"] = "mySystemi";
// sb["User ID"] = “ldubois”;
// sb["Password"] = "myPassword";
cn.ConnectionString = sb.ConnectionString;
cn.Open();
IBM Power Systems
49 © 2008 IBM Corporation
Example: Visual Studio Drag and Drop
• In this example, we’ll use the Visual Studio designers to:– Create a data source
– Select a table from the data source and see a TableAdapter automatically created for us
– Drag and drop the data from the table onto our Windows Form
– Run the application and see a data grid showing the data from our table
– Insert a row, delete a row, and update a row without writing any code
IBM Power Systems
50 © 2008 IBM Corporation
Example: Visual Studio Drag and Drop
1. Create a new Visual Studio Project C# Windows app
IBM Power Systems
51 © 2008 IBM Corporation
Example: Visual Studio Drag and Drop
2. Select Add New Data Source…
3. Select Database and click Next
IBM Power Systems
52 © 2008 IBM Corporation
Example: Visual Studio Drag and Drop
4. Select New Connection…
5. Click Change… if you want to change the provider for the connection
6. Set the properties for the connection and click OK
IBM Power Systems
53 © 2008 IBM Corporation
Example: Visual Studio Drag and Drop
7. Now that you created the connection, click Next to continue
8. Save the information to the Application Configuration file and click Next to continue
IBM Power Systems
54 © 2008 IBM Corporation
Example: Visual Studio Drag and Drop
9. Select a table (it must contain a primary or unique key) and click Finish.
10.The project’s Class View should now contain a TableAdapter, which includes generated code.
IBM Power Systems
55 © 2008 IBM Corporation
Example: Visual Studio Drag and Drop
11.Next, if your Data Sources toolbox window is not visible, select Data Show Data Sources
12.You should see a window that includes the DataSet you added earlier in step 9.
IBM Power Systems
56 © 2008 IBM Corporation
Example: Visual Studio Drag and Drop
13.Drag the table from the DataSet onto your Windows Form. Adjust the form to make your table columns visible
IBM Power Systems
57 © 2008 IBM Corporation
Example: Visual Studio Drag and Drop
14.Save your changes and Run the application. You should see a grid showing the data from your table.
Note the Navigation Bar buttons that allow you to add a row, delete a row, and send updates to the server.
IBM Power Systems
58 © 2008 IBM Corporation
Example: Visual Studio Drag and Drop
15.Next, click the button on the Navigation Bar to add a new row. Enter data for each column. Here, we added the row with ITEMID 1004. You can add more rows if you want.
Note: The new row is NOT TRANSMITTED TO THE SERVER YET. The new row is only stored locally in the application.
IBM Power Systems
59 © 2008 IBM Corporation
Example: Visual Studio Drag and Drop
16.Next, highlight a row and click the button on the Navigation Bar to delete a row. Here, we are deleting the row with ITEMID 1003. You can delete more rows if you want.
Note: The deleted row STILL EXISTS AT THE SERVER. The delete request is only stored locally in the application.
IBM Power Systems
60 © 2008 IBM Corporation
Example: Visual Studio Drag and Drop
17.Next, change some data in a row. Here, we changed the Quantity column for the first row from 500 to 499. You can change more data if you want.
Note: The changed row HAS NOT BEEN CHANGED AT THE SERVER. The change request is only stored locally in the application.
IBM Power Systems
61 © 2008 IBM Corporation
Example: Visual Studio Drag and Drop
18.Finally, click the button on the Navigation Bar to send all the changes to the server. In this example, we have 3 changes pending:
• A new row inserted with ITEMID 1004
• The row with ITEMID 1003 was deleted
• The row with ITEMID 1001 was changed
Now you should see the changes on the server. Run a SELECT * from your table and see the changes.
IBM Power Systems
62 © 2008 IBM Corporation
Example: Visual Studio Drag and Drop
• You can look at the source code to see the code generated by the Visual Studio designers.
IBM Power Systems
63 © 2008 IBM Corporation
Example: Distributed Transactions• System.Transactions namespace simplifies programming
– MS DTC must be enabled for XA Transactions:• dcomcnfg.exe (Component Services)• Expand Component Services Computers• Right-click on My Computer, select Properties• Click on the MSDTC tab and then on the Security Configuration button Enable XA Transactions and Network DTC Access
– Distributed Transaction Coordinator Service (msdtc.exe) must be started
– MSDTC registry entry must include the name of the DLL used for XA
IBM Power Systems
64 © 2008 IBM Corporation
Example: Distributed Transactions
• If the Connection has automatic transaction enlistment enabled (Enlist=true), then the connection will automatically enlist at .Open() time if there is an active transaction.
• Simple! No need to manually start the transaction or code the Commit/Rollback
DbCommand cmd = factory.CreateCommand();
using (TransactionScope scope = new TransactionScope(TransactionScopeOption.Required)){
myConnection.Open();cmd.Connection = myConnection;cmd.CommandText = "INSERT INTO MYTABLE VALUES(1, ‘test data')";cmd.ExecuteNonQuery();scope.Complete();
}
IBM Power Systems
65 © 2008 IBM Corporation
Example: AddBatch method for filling a table
• Using AddBatch to initialize an entire table reduces network traffic– Must be an INSERT statement– Must be parameterized – no literal values– Cannot use with LOB Locators– With Autocommit on, some inserts may work and others fail– Limit of 32767 rows per Execute– Specific to System i Access for Windows .NET Provider
• Note: The IBM Data Server .NET Provider has a class called DB2BulkCopy which allows copies from a DataTable into a server table.
IBM Power Systems
66 © 2008 IBM Corporation
Example: AddBatch method for filling a table
cmd.CommandText = "insert into mylib.mytable values(@parm1, @parm2)";cmd.DeriveParameters(); // Now the parameters are defined.
cmd.Parameters["@parm1"].Value = Row1Value1;cmd.Parameters["@parm2"].Value = Row1Value2;cmd.AddBatch(); // Now the first row is cached
cmd.Parameters["@parm1"].Value = Row2Value1;cmd.Parameters["@parm2"].Value = Row2Value2;cmd.AddBatch(); // Now the second row is cached … etc … cmd.Parameters["@parm1"].Value = RownValue1;cmd.Parameters["@parm2"].Value = RownValue2;cmd.AddBatch(); // Now the nth row is cached
cmd.ExecuteNonQuery(); // Now all the cached rows are inserted and the cache is cleared
IBM Power Systems
67 © 2008 IBM Corporation
Example: ConnectionStringBuilder
• Simplifies initialization of ConnectionStrings• Queryable keys• Dynamic generation of Connection properties• More secure
– Can’t inject “extra” properties
• Compile-time check when using provider-specific object Can also use IntelliSense
IBM Power Systems
68 © 2008 IBM Corporation
Example: ConnectionStringBuilder
Build a ConnectionString using the ConnectionStringBuilder for the
System i Access for Windows .NET Provider
static String buildConnectionString()
{
iDB2ConnectionStringBuilder sb = new iDB2ConnectionStringBuilder();
sb.DataSource = "mySystemi";
sb.UserID = "ldubois";
sb.ConnectionTimeout = 60;
sb.Naming = iDB2NamingConvention.System;
sb.LibraryList = "lib1, lib2";
return sb.ConnectionString;
}
IBM Power Systems
69 © 2008 IBM Corporation
Example: ConnectionStringBuilder
List the names and types of all the ConnectionString properties for the specified provider
static void queryConnectionStringProperties(String providerFactory){
DbProviderFactory factory = DbProviderFactories.GetFactory(providerFactory);
DbConnectionStringBuilder sb =factory.CreateConnectionStringBuilder();
foreach (String key in sb.Keys){
Console.Write("Key name: " + key);Console.WriteLine(", Key type: " + sb[key].GetType());
}}
IBM Power Systems
70 © 2008 IBM Corporation
Example: Federated Database Scenario
The police investigator wants to get the information on felons in the area– Conviction history records are managed by the State authorities and are
stored on a DB2 for i5/OS database.
– Current parole records including address information and are managed by the local police department and are stored in DB2 for Windows
– Federated Database function allows police investigator to submit a single query that joins criminal records data from the state database against current residency data for parolees.
Conviction History
DB2 for i5/OS(owned by state)
Parole Records
DB2 for Windows(owned by local PD)
FederatedDatabase
DB2 ServerPolice Investigator
IBM Power Systems
71 © 2008 IBM Corporation
Agenda
• Microsoft Data Access Technologies• .NET Overview• ADO.NET• Data Providers for System i• System i Access for Windows .NET Provider• IBM Data Server .NET Provider• Examples► Performance / Coding Tips
IBM Power Systems
72 © 2008 IBM Corporation
Performance Coding Tips
• Take advantage of Connection Pooling
• Use Parameters instead of literal values in SQL statements– Prepare once / Execute many
– INSERT INTO MYTABLE VALUES (@PARAM1) instead of
– INSERT INTO MYTABLE VALUES (‘abcde’)
• Use AddBatch to quickly fill a table
• Build SQL queries to retrieve only the data you need
• Optimistic Update performance– Nullable fields require an extra IF check
– Use CommandBuilder’s new CompareRowVersion + Row Change Timestamp
• Use Stored Procedures to reduce data flowing across the wire
IBM Power Systems
73 © 2008 IBM Corporation
Performance Coding Tips
• ConnectionString properties– BlockSize
– DataCompression
– EnablePreFetch
– LobBlockSize
– MaximumInlineLobSize
– MinimumPoolSize
– Pooling
– QueryOptimizeGoal
IBM Power Systems
74 © 2008 IBM Corporation
Performance Coding Tips
• When using LOBs– Use a DataReader or the Command’s ExecuteScalar method
– Avoid using a DataAdapter
– MaximumInlineLobSize- LOBs are either transferred ‘inline’ with the rest of the data, or in ‘chunks’- Test with your unique data!
– LobBlockSize specifies the ‘chunk’ size- Only affects LOBs that are read in ‘chunks’- Inline LOB data is controlled by the regular BlockSize property
IBM Power Systems
75 © 2008 IBM Corporation
Other Coding Tips
• Call an object’s Close or Dispose method when finished with it– Dispose() is there for a reason
– Objects that implement IDisposable often need some special cleanup that is not done if you let the garbage disposer handle it
– Example: iDB2Connection.Close(), iDB2Command.Dispose()
– C# USING statement automatically disposes
• Call IsDBNull method of iDB2DataReader before calling a Get method
• Make sure to handle Exceptions
IBM Power Systems
76 © 2008 IBM Corporation
System i Access for Windows sessions
31ME 420219 V6R1 System i Access for Windows: What’s New
33ME 409159 System i Access for Windows: Data Transfer Tips and Techniques
41ME 401918 Performance Tune System i Access ODBC
43ME 420219 System i Access in the .NET World
46ME 403971 System i Access for Windows: Security and Communications Tips
IBM Power Systems
77 © 2008 IBM Corporation
Appendix
• ADO.NET Comparisions to Other DB Access Models• Additional Information
IBM Power Systems
78 © 2008 IBM Corporation
• Multiple languages (> 25?)• 1 IL• 1 platform today
(Windows)• Dynamic web: ASP.NET• Database access:
ADO.NET
• 1 language• 1 IL• Multiple platforms
(JVM)• Dynamic web: JSPs• Database access:
JDBC SQL/J
.NET vs J2EE
IBM Power Systems
79 © 2008 IBM Corporation
.NET vs COM
• Designed to build Internet
Applications
• “Managed” by the .NET runtime
• Common Language Runtime (like JVM)
• Can call COM objects through COM Interop bridge
• Modified to work in Internet App world
• “Unmanaged”
• Standard DLLs
• Windows still based on COM
IBM Power Systems
80 © 2008 IBM Corporation
Mapping of ADO Objects to ADO.NET
ADO object Corresponding ADO.NET object
Command DbCommand
Command.Parameters collection DbCommand.Parameters (DbParameterCollection)
Command.Properties collection DbCommand properties
Connection DbConnection
Connection.Errors collection DbException
Connection.Properties collection DbConnection properties
Error DbException.ErrorCode
Field DataColumn of a DataRow or column of a DataReader
Field.Properties collection Column metadata returned from the DataReader’s GetSchemaTable method or the DataAdapter’s FillSchema method
Parameter DbParameter
Record DataRow of a DataTable or “current” row of a DataReader
Record.Fields collection DataColumns of a DataRow or columns of a DataReader
Recordset DbDataReader for read-only forward-only, DbDataAdapter with DataTable for updatable
Recordset.Fields collection DataColumns of a DataRow or columns of a DataReader
Recordset.Properties collection DbDataReader properties or DbDataAdapter properties
IBM Power Systems
81 © 2008 IBM Corporation
Enhance your development experience with these Add-ins / Plug-ins
• Microsoft programmer: DB2 add-ins for Visual Studio .NET make building complete DB2 applications a natural experience for VS.NET users. No .NET programmer should be without these!
• Java programmer: IBM WebSphere Studio/RAD plug-ins allow Java programmers to build DB2 applications within the Java IDE
• PHP programmer: comprehensive PHP service and support for developers with Zend Core – Zend Core enables PHP application use of all DB2 server environments
(including eServer System i and zSeries via DB2 Connect).
• Database programmer: DB2 Development Center, an Integrated Development Environment (IDE) for building server-side objects that does not require knowledge of a programming language
IBM Power Systems
82 © 2008 IBM Corporation
DB2 Mobility on Demand
POS - Mobile Devices
IBM Data Server .NET Provider
Sync Server
DB2Everyplace
DB2EveryplaceEnter an
Order
Proactive Medicine
Manage Inventory
DB2 fori5/OS
Occasionally Connected
Always Connected W
IFI
HTML, XHTML, W
AP, WML, J
2ME,
.NET C
ompact Framework etc.
Included with DB2 Enterprise Server Edition V9.5 and DB2 Database Enterprise Developer Edition V9.5
IBM Power Systems
83 © 2008 IBM Corporation
Sample Code Disclaimer
This material contains IBM copyrighted sample programming source code for your consideration. This sample code has not been thoroughly tested under all conditions. IBM, therefore, cannot guarantee or imply reliability, serviceability, or function. IBM provides no program services for this material. This material is provided "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT. SOME JURISDICTIONS DO NOT ALLOW THE EXCLUSION OF IMPLIED WARRANTIES, SO THE ABOVE EXCLUSIONS MAY NOT APPLY TO YOU. IN NO EVENT WILL IBM BE LIABLE TO ANY PARTY FOR ANY DIRECT, INDIRECT, SPECIAL OR OTHER CONSEQUENTIAL DAMAGES FOR ANY USE OF THIS MATERIAL INCLUDING, WITHOUT LIMITATION, ANY LOST PROFITS, BUSINESS INTERRUPTION, LOSS OF PROGRAMS OR OTHER DATA ON YOUR INFORMATION HANDLING SYSTEM OR OTHERWISE, EVEN IF EXPRESSLY ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
84
IBM System i
© 2008 IBM Corporationi want an i.
8 IBM Corporation 1994-2008. All rights reserved.References in this document to IBM products or services do not imply that IBM intends to make them available in every country.
Trademarks of International Business Machines Corporation in the United States, other countries, or both can be found on the World Wide Web at http://www.ibm.com/legal/copytrade.shtml.
Intel, Intel logo, Intel Inside, Intel Inside logo, Intel Centrino, Intel Centrino logo, Celeron, Intel Xeon, Intel SpeedStep, Itanium, and Pentium are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States and other countries.Linux is a registered trademark of Linus Torvalds in the United States, other countries, or both.Microsoft, Windows, Windows NT, and the Windows logo are trademarks of Microsoft Corporation in the United States, other countries, or both.IT Infrastructure Library is a registered trademark of the Central Computer and Telecommunications Agency which is now part of the Office of Government Commerce.ITIL is a registered trademark, and a registered community trademark of the Office of Government Commerce, and is registered in the U.S. Patent and Trademark Office.UNIX is a registered trademark of The Open Group in the United States and other countries.Java and all Java-based trademarks are trademarks of Sun Microsystems, Inc. in the United States, other countries, or both.Other company, product, or service names may be trademarks or service marks of others.
Information is provided "AS IS" without warranty of any kind.
The customer examples described are presented as illustrations of how those customers have used IBM products and the results they may have achieved. Actual environmental costs and performance characteristics may vary by customer.
Information concerning non-IBM products was obtained from a supplier of these products, published announcement material, or other publicly available sources and does not constitute an endorsement of such products by IBM. Sources for non-IBM list prices and performance numbers are taken from publicly available information, including vendor announcements and vendor worldwide homepages. IBM has not tested these products and cannot confirm the accuracy of performance, capability, or any other claims related to non-IBM products. Questions on the capability of non-IBM products should be addressed to the supplier of those products.
All statements regarding IBM future direction and intent are subject to change or withdrawal without notice, and represent goals and objectives only.
Some information addresses anticipated future capabilities. Such information is not intended as a definitive statement of a commitment to specific levels of performance, function or delivery schedules with respect to any future products. Such commitments are only made in IBM product announcements. The information is presented here to communicate IBM's current investment and development activities as a good faith effort to help with our customers' future planning.
Performance is based on measurements and projections using standard IBM benchmarks in a controlled environment. The actual throughput or performance that any user will experience will vary depending upon considerations such as the amount of multiprogramming in the user's job stream, the I/O configuration, the storage configuration, and the workload processed. Therefore, no assurance can be given that an individual user will achieve throughput or performance improvements equivalent to the ratios stated here.
Prices are suggested U.S. list prices and are subject to change without notice. Starting price may not include a hard drive, operating system or other features. Contact your IBM representative or Business Partner for the most current pricing in your geography.
Photographs shown may be engineering prototypes. Changes may be incorporated in production models.
Trademarks and Disclaimers