You are on page 1of 59

SQL927: Using SQL Anywhere Studio

with .NET

Alex Reif
Product Manager
areif@ianywhere.com
August 15-19, 2004
Agenda

 Introduction to .NET
 ASA and ADO.NET
 ASA and Web Services
 UltraLite.NET
The Enterprise. Unwired.
The Enterprise. Unwired.

Industry and Cross Platform Solutions

Manage Unwire Unwire


Information Information People
• Adaptive Server Enterprise • Unwired Accelerator • SQL Anywhere Studio
• Adaptive Server Anywhere • Unwired Orchestrator • M-Business Anywhere
• Sybase IQ • Unwired Toolkit • Pylon Family (Mobile Email)
• Dynamic Archive • Enterprise Portal • Mobile Sales
• Dynamic ODS • Real Time Data • XcelleNet Frontline
• Replication Server Services Solutions
• OpenSwitch • PocketBuilder
• Mirror Activator • PowerBuilder Family
• PowerDesigner • AvantGo
• Connectivity Options
• EAServer
• Industry Warehouse Studio

Sybase Workspace
Agenda

 Introduction to .NET
 ASA and ADO.NET
 ASA and Web Services
 UltraLite.NET
.NET: Definition

 .NET technology enables the creation and use of XML-based


applications, processes, and Web sites as services that share
and combine information and functionality with each other by
design, on any platform or smart device, to provide tailored
solutions for organizations and individual people.

 .NET is a comprehensive family of products, built on industry


and Internet standards, that provide for each aspect of
developing (tools), managing (servers), using (building block
services and smart clients) and experiencing (rich user
experiences) Web services.

http://www.microsoft.com/net/basics/faq.asp
.NET Framework

 Infrastructure for the overall .NET platform


 Common Language Runtime (CLR)
 Managed, protected application execution environment
 C#, Visual Basic, C++, J#, …
 Common Class Libraries
 Windows Forms, ADO.NET, ASP.NET,…

 .NET Compact Framework


 Subset of .NET Framework for smart devices
 Part of Visual Studio.NET 2003
 Included on device with CE.NET (CE 4.1), add-on for older devices
.NET: Managed Code

 Code is written in desired language (C++, C#, VB.NET, Pascal,


etc.)
 Compiled into Microsoft Intermediate Language (MSIL)
 At runtime Common Language Runtime (CLR) compiles the
MSIL code and executes it
.NET Terms

 Namespace
 “A logical naming scheme for grouping related types”
 Analogous to Java packages
 iAnywhere.Data.AsaClient.AsaConnection 
iAnywhere.Data.AsaClient is the namespace
 Assembly
 “A collection of one or more files that are versioned and deployed as a
unit”
 DLLs in .NET-land
 Unlike DLLs, .NET assemblies also include version control/security
information
 GAC (Global Assembly Cache)
 “A machine-wide code cache that stores assemblies specifically
installed to be shared by many applications on the computer”
What is ADO.NET?

 Microsoft’s latest data access API


 ODBC, DAO, RDO, OLE DB, ADO
 System.Data namespace
 “Data providers” manage access to data stores
 Providers from Microsoft:
 System.Data.OleDb
 System.Data.Odbc
 System.Data.SQLClient
 System.Data.OracleClient

 “Managed provider”  “Data provider”


ADO.NET Interfaces

 Each data provider implements the following classes:


 Connection – connects to data source
 Command – executes commands
 DataReader – forward-only, read-only access to data
 DataAdapter – fills DataSet and handles updates

 Parameter – parameter to a Command object


 Transaction – provides commit/rollback functionality
 Error, Exception – collect error/warning messages
Web Services

 Definition from W3C:


 The World Wide Web is more and more used for application to
application communication. The programmatic interfaces made
available are referred to as Web services.

 SOAP (Simple Object Access Protocol)


 XML format for making requests and receiving responses
 WSDL (Web Services Descriptor Language)
 XML format for “discovering” Web Services
Agenda

 Introduction to .NET
 ASA and ADO.NET
 ASA and Web Services
 UltraLite.NET
ASA Interfaces

 ODBC
 ESQL
 OLEDB
 Open Client
 JDBC
 Perl
 PHP
 …

 ADO.NET
ADO.NET Data Providers For ASA

 OLEDB
 ODBC
 AsaClient

iAnywhere.Data.AsaClient System.Data.Oledb System.Data.Odbc

ASA OLEDB Driver ASA ODBC Driver

ASA
ASA Data Provider

 Implements iAnywhere.Data.AsaClient namespace


 AsaConnection, AsaCommand, AsaDataReader etc.
 Supports Windows (.NET framework) and Windows CE
(Compact .NET framework)
 Available since 8.0.2.4122
Example using DataReader (C#)

AsaConnection conn = new AsaConnection(


“dsn=ASA 9.0 Sample” );
conn.Open();
AsaCommand cmd = new AsaCommand(
“select emp_lname from employee”, conn );
AsaDataReader reader = cmd.ExecuteReader();
while( reader.Read() ) {
str = reader.GetString( 0 );
Console.WriteLine( str );
}
reader.Close();
conn.Close();
Example using DataAdapter (VB.NET)

Dim conn As New iAnywhere.Data.AsaClient. AsaConnection()


conn.ConnectionString = “dsn=ASA 9.0 Sample"
conn.Open()

Dim ds As New DataSet()


Dim da As New AsaDataAdapter("select * from employee", conn)
da.Fill(ds, "Employees")

DGEmployees.DataSource = ds
DGEmployees.DataMember = "Employees"
Using the ASA Data Provider

 Use Visual Studio.NET (VS.NET 2003 preferred)

 Reference the provider in your project (required)


 Project menu, Add Reference
 In the .NET tab, find iAnywhere.Data.AsaClient.dll
 If the provider is not listed, find it in %ASANY9%\win32

 Reference provider in your code (optional)


 Allows you to use ASA provider classes without namespace prefix
 C#: using iAnywhere.Data.AsaClient
 VB.NET: Imports iAnywhere.Data.AsaClient
Demo: ASA and ADO.NET

using iAnywhere.Data.AsaClient;

private void button1_Click(object sender, System.EventArgs e)


{
AsaConnection conn;
AsaDataAdapter da;
DataSet ds;

conn = new AsaConnection("dsn=asa 9.0 sample");


conn.Open();

ds = new DataSet();

da = new AsaDataAdapter("select * from product", conn);


da.Fill(ds, "product");

dataGrid1.DataSource = ds;
dataGrid1.DataMember = "product";
}
ASA ADO.NET Data Provider

 Classes  Enumerations
 AsaConnection  AsaDbType
 AsaError
 AsaException  Delegates
 AsaInfoMessageEventHandler
 AsaCommand
 AsaRowUpdatedEventHandler
 AsaParameter
 AsaDataReader
 AsaRowUpdatingEventHandler
 AsaDataAdapter

 AsaCommandBuilder
 AsaErrorCollection
 AsaInfoMessageEventArgs
 AsaParameterCollection
 AsaPermission
 AsaPermissionAttribute
 AsaRowUpdatedEventArgs
 AsaRowUpdatingEventArgs
 AsaTransaction
ADO.NET Application Tasks

 Connecting
 Error handling
 Executing SQL
 Retrieving data
 Transactions
 Disconnected result sets
Connecting

 AsaConnection
 Represents a connection to an ASA database
 Uses normal ASA connection strings
 Optional use of event handlers (InfoMessage, StateChange)
Connection Example

using iAnywhere.Data.AsaClient;

private AsaConnection myConn;

myConn = new iAnywhere.Data.AsaClient.AsaConnection();

myConn.ConnectionString =
"Data Source=ASA 9.0 Sample;UID=DBA;PWD=SQL";

myConn.Open();
Connection Pooling

 ADO.NET spec dictates that connection pooling be enabled


by default
 Even on Windows CE!
 Disable in connection string: POOLING=false

 ASA engine may not auto-stop with pooling enabled


 Connection object must be destroyed first

myConn.ConnectionString =
“POOLING=FALSE;Data Source=ASA 9.0 Sample;UID=DBA;PWD=SQL";
Error Handling

 AsaException
 Thrown by a failed statement (try/catch)
 Message parameter contains error message
 Errors property is a collection of ASAError objects

 AsaError
 More detailed ASA-specific error information
 Message, NativeError, Source, SqlState
Errors and Exceptions Example

try {
myConn = new AsaConnection(
"Data Source=ASA 9.0 Sample;UID=DBA;PWD=SQL” );
myConn.Open();
} catch( AsaException ex ) {
MessageBox.Show(
ex.Errors[0].Source + " : " +
ex.Errors[0].Message + " (" +
ex.Errors[0].NativeError.ToString() + ")",
"Failed to connect" );
}
Executing SQL

 AsaCommand
 Represents a SQL statement or stored procedure that is executed
against an Adaptive Server Anywhere database
 Parameter property is a collection AsaParameter objects

 Multiple methods to execute your SQL


 ExecuteNonQuery (returns a row count)
 ExecuteReader (returns result set – DataReader)
 ExecuteScalar (returns a single value – column 1, row 1)

 Stored procedures
 Use the name of the procedure as the statement (no “call” or “exec”)
 Set the CommandType property to StoredProcedure
AsaCommand Example

AsaConnection myConn;
AsaCommand myCmd;
int num_depts;

myConn = new AsaConnection();


myConn.ConnectionString = "ENG=asademo9;UID=DBA;PWD=SQL";
myConn.Open();

myCmd = new AsaCommand("select count(*) from department", myConn );


num_depts = Int32.Parse( myCmd.ExecuteScalar().ToString() );
Retrieving Data

 AsaDataReader
 Read-only, forward-only result set from a query or stored procedure
(rows are fetched as needed)
 GetXXX methods to get column value as specific data types
 Read method moves to next row

 AsaDataAdapter
 Used to fill a DataSet; fetches all rows and closes cursor
 More on this later…
DataReader Example

myConn = new AsaConnection("ENG=asademo9;pwd=sql;uid=dba");


AsaCommand cmd = new AsaCommand("select * from department",
myConn);
AsaDataReader reader;

myConn.Open();
reader = cmd.ExecuteReader();
while( reader.Read() ) {
int dept_id = reader.GetInt32(0);
string dept_name = reader.GetString(1);
MessageBox.Show( "dept_id: " + dept_id +
"\ndept_name: " + dept_name );
}
reader.Close();
DataReader Example – BLOBs

AsaConnection myConn = new AsaConnection("ENG=myEngine;UID=DBA;PWD=SQL");


myConn.Open();

AsaCommand cmd = new AsaCommand(


"select bitmap from images where id = 1", myConn);
AsaDataReader reader = cmd.ExecuteReader();

byte[] bitmap;
long len;

if( reader.Read() )
{
// get the length of the BLOB by passing a NULL buffer
len = reader.GetBytes(0, 0, null, 0, 0);
bitmap = new byte[len];

// get the BLOB


reader.GetBytes(0, 0, bitmap, 0, (int)len);
}
reader.Close();
Transactions

 AsaTransaction
 Represents a SQL transaction
 Returned by ASAConnection.BeginTransaction()
 Commit, Rollback methods
 IsolationLevel property

 Autocommit is on by default in ADO.NET


 Disable by explicitly using an AsaTransaction

myTran = myConn.BeginTransaction();
myCmd = new AsaCommmand(
“call sp_update_some_data()”, myConn, myTran );

myTran.Commit();
Disconnected Result Sets

 ADO.NET DataSet (System.Data.DataSet)


 Disconnected data access
 In-memory cache of data retrieved from database
 A collection of DataTables which consist of:
• DataRow (data)
• DataColumn (schema)
• DataRelation (relate DataTables via DataColumns)
 Can read/write data/schema as XML documents
 Works with data providers to load and modify data using the
provider’s DataAdapter

 9.0: DataSet returned to SOAP requests


AsaDataAdapter

 AsaDataAdapter
 Represents a set of commands and a database connection used to fill
a DataSet and to update a database
 Fill method fetches all rows and closes cursor
 Update method applies changes to DataSet to database (beware of
ConcurrencyException!)
 SelectCommand, InsertCommand, UpdateCommand,
DeleteCommand properties

 AsaCommandBuilder
 Attached to an AsaDataAdapter
 Given a SELECT statement, generates corresponding
INSERT/UPDATE/DELETE statements
DataAdapter Example
AsaDataAdapter da;
AsaCommandBuilder cb;
DataSet ds;

private void btnConnect_Click(object sender, System.EventArgs e)


{
da = new AsaDataAdapter("select * from product", "dsn=ASA 9.0 Sample");
cb = new AsaCommandBuilder(da);

ds = new DataSet();
da.Fill(ds, "product");

dataGrid1.DataSource = ds;
dataGrid1.DataMember = "product";
}

private void btnSave_Click(object sender, System.EventArgs e)


{
da.Update(ds.Tables["product"]);
}
Application Deployment

 ASA ADO.NET Provider has two files


 iAnywhere.Data.AsaClient.dll (managed code)
 dbdata9.dll (native code)
 Both files must be deployed
 Version of files (i.e. build number) must match
 iAnywhere.Data.AsaClient.dll will throw error if versions don’t match

iAnywhere.Data.AsaClient.dll dbdata9.dll

Your
Application
ASA

.NET Common Language Runtime


Updating the ASA Provider

 At compile time, .NET compilers use strong name of


referenced assemblies
 Strong name includes both name AND version
 Microsoft’s attempt to eliminate “DLL hell”
 At run time, .NET looks for assemblies based on strong name

 An application was compiled with iAnywhere.Data.AsaClient


version 9.0.1.1234 will only run with version 9.0.1.1234
UNLESS you have a publisher policy file in place
Publisher Policy Files

 Policy files redirect one version of an assembly to another


 Installed into GAC
 ASA EBFs install policy files, for example:
 Application built against 9.0.1.1000
 EBF applied to machine; upgrade to 9.0.1.1883
• EBF installs policy file
• Requests for 9.0.0.0 – 9.0.1.1883 redirected to 9.0.1.1883
 %ASANY9%\win32\iAnywhere.Data.AsaClient.dll.config

 Security is built-in to policy files


 Policy files cannot be compiled without private key assembly was
signed with
 Only iAnywhere can create policy files for iAnywhere assemblies
Example Policy File

<configuration>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity
name="iAnywhere.Data.AsaClient"
publicKeyToken="f222fc4333e0d400"
/>
<bindingRedirect
oldVersion="9.0.1.0-1883"
newVersion="9.0.1.1883"
/>
</dependentAssembly>
</assemblyBinding>
</runtime>
</configuration>
Application Deployment: Win32

 Files can go anywhere in the path or program directory

 iAnywhere.Data.AsaClient.dll
 Register with gacutil.exe (shipped with .NET)

 dbdata9.dll
 No registration required
Application Deployment: Windows CE

 One iAnywhere.Data.AsaClient.dll for all CE platforms


 Deploy to the Windows or application directory
 Visual Studio.NET will deploy automatically

 Separate dbdata9.dll for each CE platform


 In %ASANY9%\ce\xxx
 Can go in Windows directory or your application’s directory on the device

 Policy files are not supported by .NET Compact Framework


 .NET will automatically use newest version of iAnywhere.Data.AsaClient.dll
that it finds

 Make sure to use the CE version of the DLLs!


.NET Compact Framework Tips

 Emulator
 Run ASA on desktop, not emulator
 Deploying ASA to Pocket PC 2002 (or higher) Emulator
• Create x86 CAB file, map drive from device to desktop

 Device
 Connecting to ASA on device from desktop using ActiveSync:
http://www.ianywhere.com/developer/technotes/activesync_asa.html
Agenda

 Introduction to .NET
 ASA and ADO.NET
 ASA and Web Services
 UltraLite.NET
ASA: Built-in HTTP Server

 New feature in 9.0.0

 Provides Web Services to applications


 RAW, HTML, XML, SOAP, DISH
 .NET applications consume these services easily
 9.0.2: more support for other Web Service clients

 No dynamic HTML generation engine (like JSP/ASP/etc.)


 “HTTP Server”, not “Web Server”

 HTTP server enabled on dbeng9/dbsrv9 command line


 -xs [http|https]
CREATE SERVICE Statement

CREATE SERVICE service-name TYPE service-type-
string [ attributes ] [ AS statement ]

attributes:
[ AUTHORIZATION { ON | OFF } ]
[ SECURE { ON | OFF } ]
[ USER { user-name | NULL } ]
[ URL [ PATH ] { ON | OFF | ELEMENTS } ]
[ USING { SOAP-prefix | NULL } ]

service-type-string:
{ 'RAW' | 'HTML' | 'XML' | 'SOAP' | 'DISH' }
ASA: SOAP and DISH Services

 SOAP
 Result set automatically formatted as a SOAP response
 http://www.w3.org/TR/soap/

 DISH
 “Deduce Ideal SOAP Handler”
 Groups SOAP services together
 Generates WSDL
ASA SOAP Example

 CREATE SERVICE "MyService"


TYPE 'DISH'
AUTHORIZATION OFF
USER DBA
USING "MyService";

 CREATE SERVICE "MyService/EmployeeList"


TYPE 'SOAP'
AUTHORIZATION OFF
USER DBA
AS SELECT emp_lname, emp_fname FROM employee;

 URL is: http://localhost/MyService


Demo: Consuming SOAP From .NET

 Enable the HTTP server


 dbeng9 -xs http

 Create the service


 CREATE SERVICE …

 In Visual Studio.NET, create class to access Web Service


 System.Web.Services.Protocols.HttpWebClientProtocol
 Done automatically with “Add Web Reference”

 Consume the results


 Result set returned as System.Data.DataSet
Agenda

 Introduction to .NET
 ASA and ADO.NET
 ASA and Web Services
 UltraLite.NET
UltraLite.NET - Today

 .NET wrapper for UltraLite Component API


 All .NET languages supported
 Platform support
 Pocket PC (.NET Compact Framework)
 Windows XP (desktop .NET Framework)
 Namespace is iAnywhere.UltraLite

 SQL928 Building Hand-held Database Applications Using


UltraLite
 Wednesday, 3:30 PM, Captiva 2
UltraLite Components - Class Hierarchy

DatabaseManager ConnectionParms

Connection DatabaseSchema PublicationSchema

Table

Column ColumnSchema

TableSchema IndexSchema

PreparedStatement ResultSet

ResultSetSchema
SyncResult

SyncParms
Using UltraLite.NET
Private Function NewProductList() As Boolean
Dim p As Table = _conn.GetTable("ULProduct")
p.Open("ULProductName")
Dim n As Long = p.RowCount
Dim i As Long = 0
If n > 0 Then
_prodNames = New String(n - 1) {}
_prodPrices = New Integer(n - 1) {}
Dim cid As Short = p.Schema.GetColumnID("prod_name")
Dim pid As Short = p.Schema.GetColumnID("price")
While p.MoveNext()
_prodNames(i) = p.GetString(cid)
_prodPrices(i) = p.GetInt(pid)
i = i + 1
End While
Else
_prodNames = Nothing
_prodPrices = Nothing
End If
p.Close()
Return True
End Function
Sneak Preview: UltraLite.NET for ADO.NET

 SQL Anywhere Studio 9.0.2


 ADO.NET Data Provider for UltraLite

 Namespace is iAnywhere.Data.UltraLite
 ASA: iAnywhere.Data.AsaClient

 Co-existence with the original UltraLite.NET API

 Benefits
 Easy application migration to ASA
 More familiar API for .NET developers
Demo: UltraLite.NET and ADO.NET
Summary

 Does SQL Anywhere Studio support .NET?

YES!
iAnywhere at TechWave2004

 Ask the iAnywhere Experts on the Technology Boardwalk (exhibit hall)


 Drop in during exhibit hall hours and have all your questions answered by our technical
experts!
 Appointments outside of exhibit hall hours are also available to speak one-on-one with
our Senior Engineers. Ask questions or get your yearly technical review – ask us for
details!

 TechWave ToGo Channel


 TechWave To Go, an AvantGo channel providing up-to-date information about
TechWave classes, events, maps and more – also, keep up to date with the TechWave
Newsletter – now available via your handheld device!
 www.ianywhere.com/techwavetogo

 Mobile and Wireless Email using Pylon Anywhere


 iAnywhere is providing access to your corporate email at TechWave using Pylon
Anywhere. You can keep up-to-date with your latest email, calendar, contacts, and tasks
from your PDA or any Web-client! Visit the iAnywhere demo station in the Sybase booth
or our “Ask the Experts” area in the Technology Boardwalk (Exhibit Hall) for details on
how you can evaluate Pylon Anywhere yourself!
iAnywhere at TechWave2004
 Wi-Fi Hotspots – brought to you by Intel
 You can enjoy wireless internet access via Wi-Fi hotspots provided by Intel. Using
either a laptop or PDA that is Wi-Fi 802.11b wirelessly-enabled, visitors can access
personal email, the internet and “TechWave ToGo”

 Developer Community
 A one-stop source for technical information!

 Access to newsgroups,new betas and code samples


 Monthly technical newsletters
 Technical whitepapers,tips and online product documentation
 Current webcast,class,conference and seminar listings
 Excellent resources for commonly asked questions
 All available express bug fixes and patches
 Network with thousands of industry experts

 http://www.ianywhere.com/developer/
Questions?

Alex Reif
Product Manager
areif@ianywhere.com

You might also like